diff --git a/.github/workflows/multi tenancy_Integration.yml b/.github/workflows/multi tenancy_Integration.yml index e71b024ba..e0c04f9ac 100644 --- a/.github/workflows/multi tenancy_Integration.yml +++ b/.github/workflows/multi tenancy_Integration.yml @@ -172,6 +172,9 @@ jobs: CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} CLIENT_SECRET_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_SECRET_MT }} CLIENT_ID_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_ID_MT }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + CMIS_URL: ${{ secrets.CMIS_URL }} CF_ORG: ${{ secrets.CF_ORG }} CAPAUTH_URL: ${{ secrets.CAPAUTH_URL }} AUTHURLMT1: ${{ secrets.AUTHURLMT1 }} @@ -180,6 +183,8 @@ jobs: CF_PASSWORD: ${{ secrets.CF_PASSWORD }} NOSDMROLEUSERNAME: ${{ secrets.NOSDMROLEUSERNAME }} NOSDMROLEUSERPASSWORD: ${{ secrets.NOSDMROLEUSERPASSWORD }} + DEFAULTREPOSITORYID: ${{ secrets.DEFAULTREPOSITORYID }} + DEFAULTREPOSITORYIDMT: ${{ secrets.DEFAULTREPOSITORYIDMT }} run: | echo "🚀 Preparing credentials for ${{ matrix.tokenFlow }} - ${{ matrix.tenant }}..." set +x @@ -198,6 +203,10 @@ jobs: password="$CF_PASSWORD" noSDMRoleUsername="$NOSDMROLEUSERNAME" noSDMRoleUserPassword="$NOSDMROLEUSERPASSWORD" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + defaultRepositoryID="$DEFAULTREPOSITORYID" + defaultRepositoryIDMT="$DEFAULTREPOSITORYIDMT" echo "::add-mask::$clientSecret" echo "::add-mask::$clientID" @@ -207,6 +216,9 @@ jobs: echo "::add-mask::$password" echo "::add-mask::$noSDMRoleUsername" echo "::add-mask::$noSDMRoleUserPassword" + echo "::add-mask::$CMIS_URL" + echo "::add-mask::$cmisClientID" + echo "::add-mask::$cmisClientSecret" if [ -z "$appUrl" ]; then echo "❌ Error: appUrl is not set"; exit 1; fi if [ -z "$appUrlMT" ]; then echo "❌ Error: appUrlMT is not set"; exit 1; fi @@ -221,6 +233,9 @@ jobs: if [ -z "$password" ]; then echo "❌ Error: password is not set"; exit 1; fi if [ -z "$noSDMRoleUsername" ]; then echo "❌ Error: noSDMRoleUsername is not set"; exit 1; fi if [ -z "$noSDMRoleUserPassword" ]; then echo "❌ Error: noSDMRoleUserPassword is not set"; exit 1; fi + if [ -z "$CMIS_URL" ]; then echo "❌ Error: CMIS_URL is not set"; exit 1; fi + if [ -z "$cmisClientID" ]; then echo "❌ Error: cmisClientID is not set"; exit 1; fi + if [ -z "$cmisClientSecret" ]; then echo "❌ Error: cmisClientSecret is not set"; exit 1; fi cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Switch to Versioned Repository 🔄 + run: | + echo "🔄 Switching REPOSITORY_ID to versioned repository..." + cf set-env bookshop-mt-srv REPOSITORY_ID "${{ secrets.VERSIONEDREPOSITORYID }}" + echo "🔄 Restaging application..." + cf restage bookshop-mt-srv > /dev/null 2>&1 + echo "✅ Switched to versioned repository!" + + versioned-integration-test: + runs-on: ubuntu-latest + needs: versioned-repo-setup + if: "!cancelled() && needs.versioned-repo-setup.result == 'success'" + strategy: + fail-fast: false + matrix: + tokenFlow: [namedUser, technicalUser] + tenant: [TENANT1, TENANT2] + testClass: + - IntegrationTest_SingleFacet_VersionedRepository + - IntegrationTest_MultipleFacet_VersionedRepository + - IntegrationTest_Chapters_MultipleFacet_VersionedRepository + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + + - name: Fetch and Escape Client Details for multi tenant 🔍 + id: fetch_credentials_mt + run: | + service_instance_guid=$(cf service bookshop-mt-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret_mt=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret_mt" ] || [ "$clientSecret_mt" == "null" ]; then + echo "❌ Error: clientSecret_mt is not set or is null"; exit 1; + fi + escapedClientSecret_mt=$(echo "$clientSecret_mt" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret_mt" + clientID_mt=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID_mt" ] || [ "$clientID_mt" == "null" ]; then + echo "❌ Error: clientID_mt is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID_mt" + echo "CLIENT_SECRET_MT=$escapedClientSecret_mt" >> $GITHUB_OUTPUT + echo "CLIENT_ID_MT=$clientID_mt" >> $GITHUB_OUTPUT + + - name: Run versioned integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.tenant }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CLIENT_SECRET_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_SECRET_MT }} + CLIENT_ID_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_ID_MT }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + appUrlMT="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-bookshop-mt-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + authUrlMT1="${{ secrets.AUTHURLMT1 }}" + authUrlMT2="${{ secrets.AUTHURLMT2 }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + clientIDMT="${{ env.CLIENT_ID_MT }}" + clientSecretMT="${{ env.CLIENT_SECRET_MT }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + defaultRepositoryIDMT="${{ secrets.DEFAULTREPOSITORYIDMT }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Switch to Virus Scan Repository 🔄 + run: | + echo "🔄 Switching REPOSITORY_ID to virus scan repository..." + cf set-env bookshop-mt-srv REPOSITORY_ID "${{ secrets.VIRUSSCANREPOSITORYID }}" + echo "🔄 Restaging application..." + cf restage bookshop-mt-srv > /dev/null 2>&1 + echo "✅ Switched to virus scan repository!" + + virusscan-integration-test: + runs-on: ubuntu-latest + needs: virusscan-repo-setup + if: "!cancelled() && needs.virusscan-repo-setup.result == 'success'" + strategy: + fail-fast: false + matrix: + tokenFlow: [namedUser, technicalUser] + tenant: [TENANT1, TENANT2] + testClass: + - IntegrationTest_SingleFacet_Virus + - IntegrationTest_MultipleFacet_Virus + - IntegrationTest_Chapters_MultipleFacet_Virus + env: + FILE_URL: ${{ 'http://www.eicar.org/download/eicar.com.txt' }} + DOWNLOAD_PATH: ${{ 'sdm/eicar.com.txt' }} + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + + - name: Fetch and Escape Client Details for multi tenant 🔍 + id: fetch_credentials_mt + run: | + service_instance_guid=$(cf service bookshop-mt-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret_mt=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret_mt" ] || [ "$clientSecret_mt" == "null" ]; then + echo "❌ Error: clientSecret_mt is not set or is null"; exit 1; + fi + escapedClientSecret_mt=$(echo "$clientSecret_mt" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret_mt" + clientID_mt=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID_mt" ] || [ "$clientID_mt" == "null" ]; then + echo "❌ Error: clientID_mt is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID_mt" + echo "CLIENT_SECRET_MT=$escapedClientSecret_mt" >> $GITHUB_OUTPUT + echo "CLIENT_ID_MT=$clientID_mt" >> $GITHUB_OUTPUT + + - name: Download virus test file 📥 + run: | + curl -fSL "$FILE_URL" -o "$DOWNLOAD_PATH" + sleep 5 + if [ -f "$DOWNLOAD_PATH" ]; then + FILE_NAME=$(basename "$DOWNLOAD_PATH") + FILE_SIZE=$(stat -c '%s' "$DOWNLOAD_PATH") + echo "File exists — Name: $FILE_NAME, Size: $FILE_SIZE bytes" + else + echo "❌ File NOT found at path: $DOWNLOAD_PATH" + exit 1 + fi + + - name: Run virus scan integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.tenant }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CLIENT_SECRET_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_SECRET_MT }} + CLIENT_ID_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_ID_MT }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + appUrlMT="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-bookshop-mt-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + authUrlMT1="${{ secrets.AUTHURLMT1 }}" + authUrlMT2="${{ secrets.AUTHURLMT2 }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + clientIDMT="${{ env.CLIENT_ID_MT }}" + clientSecretMT="${{ env.CLIENT_SECRET_MT }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + defaultRepositoryIDMT="${{ secrets.DEFAULTREPOSITORYIDMT }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Revert to Default Repository 🔄 + run: | + echo "🔄 Reverting REPOSITORY_ID to default repository..." + cf set-env bookshop-mt-srv REPOSITORY_ID "${{ secrets.DEFAULTREPOSITORYIDMT }}" + echo "🔄 Restaging application..." + cf restage bookshop-mt-srv > /dev/null 2>&1 + echo "✅ Reverted to default repository!" + + repospecific-integration-test: + runs-on: ubuntu-latest + needs: virusscan-repo-cleanup + if: "!cancelled()" + strategy: + fail-fast: false + max-parallel: 1 + matrix: + tokenFlow: [namedUser, technicalUser] + tenant: [TENANT1, TENANT2] + testClass: + - IntegrationTest_SingleFacet_RepoSpecific + - IntegrationTest_MultipleFacet_RepoSpecific + - IntegrationTest_Chapters_MultipleFacet_RepoSpecific + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + + - name: Fetch and Escape Client Details for multi tenant 🔍 + id: fetch_credentials_mt + run: | + service_instance_guid=$(cf service bookshop-mt-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret_mt=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret_mt" ] || [ "$clientSecret_mt" == "null" ]; then + echo "❌ Error: clientSecret_mt is not set or is null"; exit 1; + fi + escapedClientSecret_mt=$(echo "$clientSecret_mt" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret_mt" + clientID_mt=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID_mt" ] || [ "$clientID_mt" == "null" ]; then + echo "❌ Error: clientID_mt is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID_mt" + echo "CLIENT_SECRET_MT=$escapedClientSecret_mt" >> $GITHUB_OUTPUT + echo "CLIENT_ID_MT=$clientID_mt" >> $GITHUB_OUTPUT + + - name: Run repo-specific integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.tenant }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CLIENT_SECRET_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_SECRET_MT }} + CLIENT_ID_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_ID_MT }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + appUrlMT="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-bookshop-mt-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + authUrlMT1="${{ secrets.AUTHURLMT1 }}" + authUrlMT2="${{ secrets.AUTHURLMT2 }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + clientIDMT="${{ env.CLIENT_ID_MT }}" + clientSecretMT="${{ env.CLIENT_SECRET_MT }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + defaultRepositoryIDMT="${{ secrets.DEFAULTREPOSITORYIDMT }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + cat > "$PROPERTIES_FILE" < /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Install BTP CLI 🔧 + run: | + echo "🔄 Installing SAP BTP CLI..." + curl -fsSL https://cli.btp.cloud.sap/btpcli-install.sh | bash + # The install script places the binary in ~/bin by default — make it system-wide + BTP_BIN=$(find "$HOME/bin" /usr/local/bin -maxdepth 1 -name 'btp' -type f 2>/dev/null | head -1) + if [ -z "$BTP_BIN" ]; then + echo "❌ btp binary not found after install script." + exit 1 + fi + if [ "$BTP_BIN" != "/usr/local/bin/btp" ]; then + sudo install -m 755 "$BTP_BIN" /usr/local/bin/btp + fi + btp --version + echo "✅ BTP CLI installed successfully!" + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + + - name: Fetch and Escape Client Details for multi tenant 🔍 + id: fetch_credentials_mt + run: | + service_instance_guid=$(cf service bookshop-mt-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret_mt=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret_mt" ] || [ "$clientSecret_mt" == "null" ]; then + echo "❌ Error: clientSecret_mt is not set or is null"; exit 1; + fi + escapedClientSecret_mt=$(echo "$clientSecret_mt" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret_mt" + clientID_mt=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID_mt" ] || [ "$clientID_mt" == "null" ]; then + echo "❌ Error: clientID_mt is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID_mt" + echo "CLIENT_SECRET_MT=$escapedClientSecret_mt" >> $GITHUB_OUTPUT + echo "CLIENT_ID_MT=$clientID_mt" >> $GITHUB_OUTPUT + + - name: Run subscription integration tests 🎯 (${{ matrix.tenant }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CLIENT_SECRET_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_SECRET_MT }} + CLIENT_ID_MT: ${{ steps.fetch_credentials_mt.outputs.CLIENT_ID_MT }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + appUrlMT="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-bookshop-mt-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + authUrlMT1="${{ secrets.AUTHURLMT1 }}" + authUrlMT2="${{ secrets.AUTHURLMT2 }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + clientIDMT="${{ env.CLIENT_ID_MT }}" + clientSecretMT="${{ env.CLIENT_SECRET_MT }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + defaultRepositoryIDMT="${{ secrets.DEFAULTREPOSITORYIDMT }}" + consumerSubaccountIdMT1="${{ secrets.CONSUMERSUBACCOUNTIDMT1 }}" + consumerSubdomainMT1="${{ secrets.CONSUMERSUBDOMAINMT1 }}" + consumerSubaccountIdMT2="${{ secrets.CONSUMERSUBACCOUNTIDMT2 }}" + consumerSubdomainMT2="${{ secrets.CONSUMERSUBDOMAINMT2 }}" + consumerSubdomainMT="${{ secrets.CONSUMERSUBDOMAINMT }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + SAAS_APP_NAME="bookshop-mt-sdmgoogleworkspacedev-${{ steps.determine_space.outputs.space }}" + ROLE_COLLECTION_NAME="ak-test" + APP_ROLE_FILTER="bookshop-mt-sdmgoogleworkspacedev-${{ steps.determine_space.outputs.space }}" + BTP_CLI_URL="${{ secrets.BTP_CLI_URL }}" + BTP_GLOBAL_ACCOUNT_SUBDOMAIN="${{ secrets.BTP_GLOBAL_ACCOUNT_SUBDOMAIN }}" + cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT echo "✅ Client details fetched successfully!" - + - name: Download virus test file 📥 + run: | + curl -fSL "$FILE_URL" -o "$DOWNLOAD_PATH" + sleep 5 + if [ -f "$DOWNLOAD_PATH" ]; then + FILE_NAME=$(basename "$DOWNLOAD_PATH") + FILE_SIZE=$(stat -c '%s' "$DOWNLOAD_PATH") + echo "File exists — Name: $FILE_NAME, Size: $FILE_SIZE bytes" + else + echo "❌ File NOT found at path: $DOWNLOAD_PATH" + exit 1 + fi - name: Run integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.testClass }}) env: CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + CMIS_URL: ${{ secrets.CMIS_URL }} CF_ORG: ${{ secrets.CF_ORG }} CAPAUTH_URL: ${{ secrets.CAPAUTH_URL }} CF_USER: ${{ secrets.CF_USER }} CF_PASSWORD: ${{ secrets.CF_PASSWORD }} NOSDMROLEUSERNAME: ${{ secrets.NOSDMROLEUSERNAME }} NOSDMROLEUSERPASSWORD: ${{ secrets.NOSDMROLEUSERPASSWORD }} + VERSIONEDREPOSITORYID: ${{ secrets.VERSIONEDREPOSITORYID }} + VIRUSSCANREPOSITORYID: ${{ secrets.VIRUSSCANREPOSITORYID }} + DEFAULTREPOSITORYID: ${{ secrets.DEFAULTREPOSITORYID }} run: | set +x echo "🚀 Starting integration tests for ${{ matrix.tokenFlow }} - ${{ matrix.testClass }}..." @@ -146,12 +165,23 @@ jobs: password="$CF_PASSWORD" noSDMRoleUsername="$NOSDMROLEUSERNAME" noSDMRoleUserPassword="$NOSDMROLEUSERPASSWORD" + versionedRepositoryID="$VERSIONEDREPOSITORYID" + virusScanRepositoryID="$VIRUSSCANREPOSITORYID" + defaultRepositoryID="$DEFAULTREPOSITORYID" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" echo "::add-mask::$clientSecret" echo "::add-mask::$clientID" echo "::add-mask::$username" echo "::add-mask::$password" echo "::add-mask::$noSDMRoleUsername" echo "::add-mask::$noSDMRoleUserPassword" + echo "::add-mask::$versionedRepositoryID" + echo "::add-mask::$virusScanRepositoryID" + echo "::add-mask::$defaultRepositoryID" + echo "::add-mask::$CMIS_URL" + echo "::add-mask::$cmisClientID" + echo "::add-mask::$cmisClientSecret" if [ -z "$appUrl" ]; then echo "❌ Error: appUrl is not set"; exit 1; fi if [ -z "$authUrl" ]; then echo "❌ Error: authUrl is not set"; exit 1; fi if [ -z "$clientID" ]; then echo "❌ Error: clientID is not set"; exit 1; fi @@ -160,6 +190,12 @@ jobs: if [ -z "$password" ]; then echo "❌ Error: password is not set"; exit 1; fi if [ -z "$noSDMRoleUsername" ]; then echo "❌ Error: noSDMRoleUsername is not set"; exit 1; fi if [ -z "$noSDMRoleUserPassword" ]; then echo "❌ Error: noSDMRoleUserPassword is not set"; exit 1; fi + if [ -z "$versionedRepositoryID" ]; then echo "❌ Error: versionedRepositoryID is not set"; exit 1; fi + if [ -z "$virusScanRepositoryID" ]; then echo "❌ Error: virusScanRepositoryID is not set"; exit 1; fi + if [ -z "$defaultRepositoryID" ]; then echo "❌ Error: defaultRepositoryID is not set"; exit 1; fi + if [ -z "$CMIS_URL" ]; then echo "❌ Error: CMIS_URL is not set"; exit 1; fi + if [ -z "$cmisClientID" ]; then echo "❌ Error: cmisClientID is not set"; exit 1; fi + if [ -z "$cmisClientSecret" ]; then echo "❌ Error: cmisClientSecret is not set"; exit 1; fi cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Switch to Versioned Repository 🔄 + run: | + echo "🔄 Switching REPOSITORY_ID to versioned repository..." + cf set-env demoappjava-srv REPOSITORY_ID "${{ secrets.VERSIONEDREPOSITORYID }}" + echo "🔄 Restaging application..." + cf restage demoappjava-srv > /dev/null 2>&1 + echo "✅ Switched to versioned repository!" + + versioned-integration-test: + runs-on: ubuntu-latest + needs: versioned-repo-setup + if: "!cancelled() && needs.versioned-repo-setup.result == 'success'" + strategy: + fail-fast: false + matrix: + tokenFlow: [namedUser, technicalUser] + testClass: + - IntegrationTest_SingleFacet_VersionedRepository + - IntegrationTest_MultipleFacet_VersionedRepository + - IntegrationTest_Chapters_MultipleFacet_VersionedRepository + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + echo "🔄 Installing Cloud Foundry CLI..." + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + echo "🔄 Fetching client details for single tenant..." + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + echo "✅ Client details fetched successfully!" + - name: Run versioned integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + echo "🚀 Starting versioned integration tests for ${{ matrix.tokenFlow }} - ${{ matrix.testClass }}..." + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + echo "::add-mask::$clientSecret" + echo "::add-mask::$clientID" + echo "::add-mask::$username" + echo "::add-mask::$password" + echo "::add-mask::$noSDMRoleUsername" + echo "::add-mask::$noSDMRoleUserPassword" + echo "::add-mask::$versionedRepositoryID" + echo "::add-mask::$virusScanRepositoryID" + echo "::add-mask::$defaultRepositoryID" + echo "::add-mask::$CMIS_URL" + echo "::add-mask::$cmisClientID" + echo "::add-mask::$cmisClientSecret" + if [ -z "$appUrl" ]; then echo "❌ Error: appUrl is not set"; exit 1; fi + if [ -z "$authUrl" ]; then echo "❌ Error: authUrl is not set"; exit 1; fi + if [ -z "$clientID" ]; then echo "❌ Error: clientID is not set"; exit 1; fi + if [ -z "$clientSecret" ]; then echo "❌ Error: clientSecret is not set"; exit 1; fi + if [ -z "$username" ]; then echo "❌ Error: username is not set"; exit 1; fi + if [ -z "$password" ]; then echo "❌ Error: password is not set"; exit 1; fi + if [ -z "$noSDMRoleUsername" ]; then echo "❌ Error: noSDMRoleUsername is not set"; exit 1; fi + if [ -z "$noSDMRoleUserPassword" ]; then echo "❌ Error: noSDMRoleUserPassword is not set"; exit 1; fi + if [ -z "$versionedRepositoryID" ]; then echo "❌ Error: versionedRepositoryID is not set"; exit 1; fi + if [ -z "$virusScanRepositoryID" ]; then echo "❌ Error: virusScanRepositoryID is not set"; exit 1; fi + if [ -z "$defaultRepositoryID" ]; then echo "❌ Error: defaultRepositoryID is not set"; exit 1; fi + if [ -z "$CMIS_URL" ]; then echo "❌ Error: CMIS_URL is not set"; exit 1; fi + if [ -z "$cmisClientID" ]; then echo "❌ Error: cmisClientID is not set"; exit 1; fi + if [ -z "$cmisClientSecret" ]; then echo "❌ Error: cmisClientSecret is not set"; exit 1; fi + cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Switch to Virus Scan Repository 🔄 + run: | + echo "🔄 Switching REPOSITORY_ID to virus scan repository..." + cf set-env demoappjava-srv REPOSITORY_ID "${{ secrets.VIRUSSCANREPOSITORYID }}" + echo "🔄 Restaging application..." + cf restage demoappjava-srv > /dev/null 2>&1 + echo "✅ Switched to virus scan repository!" + + virusscan-integration-test: + runs-on: ubuntu-latest + needs: virusscan-repo-setup + if: "!cancelled() && needs.virusscan-repo-setup.result == 'success'" + strategy: + fail-fast: false + matrix: + tokenFlow: [namedUser, technicalUser] + testClass: + - IntegrationTest_SingleFacet_Virus + - IntegrationTest_MultipleFacet_Virus + - IntegrationTest_Chapters_MultipleFacet_Virus + env: + FILE_URL: ${{ 'http://www.eicar.org/download/eicar.com.txt' }} + DOWNLOAD_PATH: ${{ 'sdm/eicar.com.txt' }} + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + echo "🔄 Installing Cloud Foundry CLI..." + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + echo "🔄 Fetching client details for single tenant..." + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + echo "✅ Client details fetched successfully!" + - name: Download virus test file 📥 + run: | + curl -fSL "$FILE_URL" -o "$DOWNLOAD_PATH" + sleep 5 + if [ -f "$DOWNLOAD_PATH" ]; then + FILE_NAME=$(basename "$DOWNLOAD_PATH") + FILE_SIZE=$(stat -c '%s' "$DOWNLOAD_PATH") + echo "File exists — Name: $FILE_NAME, Size: $FILE_SIZE bytes" + else + echo "❌ File NOT found at path: $DOWNLOAD_PATH" + exit 1 + fi + - name: Run virus scan integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + echo "🚀 Starting virus scan integration tests for ${{ matrix.tokenFlow }} - ${{ matrix.testClass }}..." + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + echo "::add-mask::$clientSecret" + echo "::add-mask::$clientID" + echo "::add-mask::$username" + echo "::add-mask::$password" + echo "::add-mask::$noSDMRoleUsername" + echo "::add-mask::$noSDMRoleUserPassword" + echo "::add-mask::$versionedRepositoryID" + echo "::add-mask::$virusScanRepositoryID" + echo "::add-mask::$defaultRepositoryID" + echo "::add-mask::$CMIS_URL" + echo "::add-mask::$cmisClientID" + echo "::add-mask::$cmisClientSecret" + if [ -z "$appUrl" ]; then echo "❌ Error: appUrl is not set"; exit 1; fi + if [ -z "$authUrl" ]; then echo "❌ Error: authUrl is not set"; exit 1; fi + if [ -z "$clientID" ]; then echo "❌ Error: clientID is not set"; exit 1; fi + if [ -z "$clientSecret" ]; then echo "❌ Error: clientSecret is not set"; exit 1; fi + if [ -z "$username" ]; then echo "❌ Error: username is not set"; exit 1; fi + if [ -z "$password" ]; then echo "❌ Error: password is not set"; exit 1; fi + if [ -z "$noSDMRoleUsername" ]; then echo "❌ Error: noSDMRoleUsername is not set"; exit 1; fi + if [ -z "$noSDMRoleUserPassword" ]; then echo "❌ Error: noSDMRoleUserPassword is not set"; exit 1; fi + if [ -z "$versionedRepositoryID" ]; then echo "❌ Error: versionedRepositoryID is not set"; exit 1; fi + if [ -z "$virusScanRepositoryID" ]; then echo "❌ Error: virusScanRepositoryID is not set"; exit 1; fi + if [ -z "$defaultRepositoryID" ]; then echo "❌ Error: defaultRepositoryID is not set"; exit 1; fi + if [ -z "$CMIS_URL" ]; then echo "❌ Error: CMIS_URL is not set"; exit 1; fi + if [ -z "$cmisClientID" ]; then echo "❌ Error: cmisClientID is not set"; exit 1; fi + if [ -z "$cmisClientSecret" ]; then echo "❌ Error: cmisClientSecret is not set"; exit 1; fi + cat > "$PROPERTIES_FILE" <> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Revert to Default Repository 🔄 + run: | + echo "🔄 Reverting REPOSITORY_ID to default repository..." + cf set-env demoappjava-srv REPOSITORY_ID "${{ secrets.DEFAULTREPOSITORYID }}" + echo "🔄 Restaging application..." + cf restage demoappjava-srv > /dev/null 2>&1 + echo "✅ Reverted to default repository!" + + repospecific-integration-test: + runs-on: ubuntu-latest + needs: virusscan-repo-cleanup + if: "!cancelled()" + strategy: + fail-fast: false + max-parallel: 1 + matrix: + tokenFlow: [namedUser, technicalUser] + testClass: + - IntegrationTest_SingleFacet_RepoSpecific + - IntegrationTest_MultipleFacet_RepoSpecific + - IntegrationTest_Chapters_MultipleFacet_RepoSpecific + steps: + - name: Checkout repository 📁 + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.branch_name }} + + - name: Set up Java 17 ☕ + uses: actions/setup-java@v3 + with: + java-version: 17 + distribution: 'temurin' + cache: 'maven' + + - name: Cache CF CLI 📦 + id: cache-cf-cli + uses: actions/cache@v4 + with: + path: /usr/bin/cf8 + key: cf-cli-v8-${{ runner.os }} + + - name: Install Cloud Foundry CLI 🔧 + if: steps.cache-cf-cli.outputs.cache-hit != 'true' + run: | + echo "🔄 Installing Cloud Foundry CLI..." + wget -q -O - https://packages.cloudfoundry.org/debian/cli.cloudfoundry.org.key | sudo apt-key add - + echo "deb https://packages.cloudfoundry.org/debian stable main" | sudo tee /etc/apt/sources.list.d/cloudfoundry-cli.list + sudo apt-get update + sudo apt-get install cf8-cli + + - name: Install jq 📦 + run: | + if ! command -v jq &> /dev/null; then + sudo apt-get update && sudo apt-get install -y jq + fi + + - name: Determine Cloud Foundry Space 🌌 + id: determine_space + run: | + if [ "${{ github.event.inputs.cf_space }}" == "developcap" ]; then + space="${{ secrets.CF_SPACE }}" + else + space="${{ github.event.inputs.cf_space }}" + fi + echo "space=$space" >> $GITHUB_OUTPUT + + - name: Login to Cloud Foundry 🔑 + run: | + cf login -a ${{ secrets.CF_API }} \ + -u ${{ secrets.CF_USER }} \ + -p ${{ secrets.CF_PASSWORD }} \ + -o ${{ secrets.CF_ORG }} \ + -s ${{ steps.determine_space.outputs.space }} + + - name: Fetch and Escape Client Details for single tenant 🔍 + id: fetch_credentials + run: | + echo "🔄 Fetching client details for single tenant..." + service_instance_guid=$(cf service demoappjava-public-uaa --guid) + if [ -z "$service_instance_guid" ]; then + echo "❌ Error: Unable to retrieve service instance GUID"; exit 1; + fi + bindings_response=$(cf curl "/v3/service_credential_bindings?service_instance_guids=${service_instance_guid}") + binding_guid=$(echo "$bindings_response" | jq -r '.resources[0].guid') + if [ -z "$binding_guid" ]; then + echo "❌ Error: Unable to retrieve binding GUID"; exit 1; + fi + binding_details=$(cf curl "/v3/service_credential_bindings/${binding_guid}/details") + clientSecret=$(echo "$binding_details" | jq -r '.credentials.clientsecret') + if [ -z "$clientSecret" ] || [ "$clientSecret" == "null" ]; then + echo "❌ Error: clientSecret is not set or is null"; exit 1; + fi + escapedClientSecret=$(echo "$clientSecret" | sed 's/\$/\\$/g') + echo "::add-mask::$escapedClientSecret" + clientID=$(echo "$binding_details" | jq -r '.credentials.clientid') + if [ -z "$clientID" ] || [ "$clientID" == "null" ]; then + echo "❌ Error: clientID is not set or is null"; exit 1; + fi + echo "::add-mask::$clientID" + echo "CLIENT_SECRET=$escapedClientSecret" >> $GITHUB_OUTPUT + echo "CLIENT_ID=$clientID" >> $GITHUB_OUTPUT + echo "✅ Client details fetched successfully!" + - name: Run repo-specific integration tests 🎯 (${{ matrix.tokenFlow }} - ${{ matrix.testClass }}) + env: + CLIENT_SECRET: ${{ steps.fetch_credentials.outputs.CLIENT_SECRET }} + CLIENT_ID: ${{ steps.fetch_credentials.outputs.CLIENT_ID }} + CMIS_CLIENT_ID: ${{ secrets.CMISCLIENTID }} + CMIS_CLIENT_SECRET: ${{ secrets.CMISCLIENTSECRET }} + run: | + echo "🚀 Starting repo-specific integration tests for ${{ matrix.tokenFlow }} - ${{ matrix.testClass }}..." + set -e + PROPERTIES_FILE="sdm/src/test/resources/credentials.properties" + appUrl="${{ secrets.CF_ORG }}-${{ steps.determine_space.outputs.space }}-demoappjava-srv.cfapps.eu12.hana.ondemand.com" + authUrl="${{ secrets.CAPAUTH_URL }}" + clientID="${{ env.CLIENT_ID }}" + clientSecret="${{ env.CLIENT_SECRET }}" + username="${{ secrets.CF_USER }}" + password="${{ secrets.CF_PASSWORD }}" + noSDMRoleUsername="${{ secrets.NOSDMROLEUSERNAME }}" + noSDMRoleUserPassword="${{ secrets.NOSDMROLEUSERPASSWORD }}" + versionedRepositoryID="${{ secrets.VERSIONEDREPOSITORYID }}" + virusScanRepositoryID="${{ secrets.VIRUSSCANREPOSITORYID }}" + defaultRepositoryID="${{ secrets.DEFAULTREPOSITORYID }}" + CMIS_URL="${{ secrets.CMIS_URL }}" + cmisClientID="$CMIS_CLIENT_ID" + cmisClientSecret="$CMIS_CLIENT_SECRET" + echo "::add-mask::$clientSecret" + echo "::add-mask::$clientID" + echo "::add-mask::$username" + echo "::add-mask::$password" + echo "::add-mask::$noSDMRoleUsername" + echo "::add-mask::$noSDMRoleUserPassword" + echo "::add-mask::$versionedRepositoryID" + echo "::add-mask::$virusScanRepositoryID" + echo "::add-mask::$defaultRepositoryID" + echo "::add-mask::$CMIS_URL" + echo "::add-mask::$cmisClientID" + echo "::add-mask::$cmisClientSecret" + if [ -z "$appUrl" ]; then echo "❌ Error: appUrl is not set"; exit 1; fi + if [ -z "$authUrl" ]; then echo "❌ Error: authUrl is not set"; exit 1; fi + if [ -z "$clientID" ]; then echo "❌ Error: clientID is not set"; exit 1; fi + if [ -z "$clientSecret" ]; then echo "❌ Error: clientSecret is not set"; exit 1; fi + if [ -z "$username" ]; then echo "❌ Error: username is not set"; exit 1; fi + if [ -z "$password" ]; then echo "❌ Error: password is not set"; exit 1; fi + if [ -z "$noSDMRoleUsername" ]; then echo "❌ Error: noSDMRoleUsername is not set"; exit 1; fi + if [ -z "$noSDMRoleUserPassword" ]; then echo "❌ Error: noSDMRoleUserPassword is not set"; exit 1; fi + if [ -z "$versionedRepositoryID" ]; then echo "❌ Error: versionedRepositoryID is not set"; exit 1; fi + if [ -z "$virusScanRepositoryID" ]; then echo "❌ Error: virusScanRepositoryID is not set"; exit 1; fi + if [ -z "$defaultRepositoryID" ]; then echo "❌ Error: defaultRepositoryID is not set"; exit 1; fi + if [ -z "$CMIS_URL" ]; then echo "❌ Error: CMIS_URL is not set"; exit 1; fi + if [ -z "$cmisClientID" ]; then echo "❌ Error: cmisClientID is not set"; exit 1; fi + if [ -z "$cmisClientSecret" ]; then echo "❌ Error: cmisClientSecret is not set"; exit 1; fi + cat > "$PROPERTIES_FILE" < attachments = new ArrayList<>(); @@ -2550,7 +2551,7 @@ void testCreateLinkSuccessInChapter() throws IOException { } @Test - @Order(43) + @Order(31) void testCreateLinkDifferentChapter() throws IOException { System.out.println("Test (43): Create link with same name in different chapter"); @@ -2590,7 +2591,7 @@ void testCreateLinkDifferentChapter() throws IOException { } @Test - @Order(44) + @Order(32) void testCreateLinkFailureInChapter() throws IOException { System.out.println("Test (44): Create link fails due to invalid URL and name in chapter"); @@ -2700,7 +2701,7 @@ void testCreateLinkFailureInChapter() throws IOException { } @Test - @Order(45) + @Order(33) void testCreateLinkNoSDMRolesInChapter() throws IOException { System.out.println("Test (45): Create link fails due to no SDM roles assigned in chapter"); @@ -2751,7 +2752,7 @@ void testCreateLinkNoSDMRolesInChapter() throws IOException { } @Test - @Order(46) + @Order(34) void testDeleteLinkInChapter() throws IOException { System.out.println("Test (46): Delete link in chapter"); List> attachments = new ArrayList<>(); @@ -3961,7 +3962,7 @@ void testCopyAttachmentsToExistingChapter() throws IOException { // // ============= LINK RENAME TESTS (47-49) ============= @Test - @Order(47) + @Order(42) void testRenameLinkSuccess() throws IOException { System.out.println("Test (47): Rename link in chapter"); @@ -4024,7 +4025,7 @@ void testRenameLinkSuccess() throws IOException { } @Test - @Order(48) + @Order(43) void testRenameLinkDuplicate() throws IOException { System.out.println("Test (48): Rename link in chapter fails due to duplicate error"); @@ -4112,7 +4113,7 @@ void testRenameLinkDuplicate() throws IOException { } @Test - @Order(49) + @Order(44) void testRenameLinkUnsupportedCharacters() throws IOException { System.out.println("Test (49): Rename link in chapter fails due to unsupported characters"); @@ -4178,7 +4179,7 @@ void testRenameLinkUnsupportedCharacters() throws IOException { // // ============= LINK EDIT TESTS (50-53) ============= @Test - @Order(50) + @Order(45) void testEditLinkSuccess() throws IOException { System.out.println("Test (50): Edit existing link URL in chapter"); @@ -4264,7 +4265,7 @@ void testEditLinkSuccess() throws IOException { } @Test - @Order(51) + @Order(46) void testEditLinkFailureInvalidURL() throws IOException { System.out.println("Test (51): Edit link with invalid URL fails in chapter"); @@ -4326,7 +4327,7 @@ void testEditLinkFailureInvalidURL() throws IOException { } @Test - @Order(52) + @Order(47) void testEditLinkFailureEmptyURL() throws IOException { System.out.println("Test (52): Edit link with empty URL fails in chapter"); @@ -4386,7 +4387,7 @@ void testEditLinkFailureEmptyURL() throws IOException { } @Test - @Order(53) + @Order(48) void testEditLinkNoSDMRoles() throws IOException { System.out.println("Test (53): Edit link fails due to no SDM roles assigned in chapter"); @@ -4449,7 +4450,7 @@ void testEditLinkNoSDMRoles() throws IOException { // // ============= COPY LINK TESTS (54-58) ============= @Test - @Order(54) + @Order(49) void testCopyLinkSuccessNewChapter() throws IOException { System.out.println("Test (54): Copy link from one chapter to another new chapter"); @@ -4539,7 +4540,7 @@ void testCopyLinkSuccessNewChapter() throws IOException { } @Test - @Order(55) + @Order(50) void testCopyLinkUnsuccessfulInvalidObjectId() throws IOException { System.out.println("Test (55): Copy invalid link object ID to chapter fails"); @@ -4576,7 +4577,7 @@ void testCopyLinkUnsuccessfulInvalidObjectId() throws IOException { } @Test - @Order(56) + @Order(51) void testCopyLinkToExistingChapter() throws IOException { System.out.println("Test (56): Copy link to existing chapter that has attachments"); @@ -4677,7 +4678,7 @@ void testCopyLinkToExistingChapter() throws IOException { } @Test - @Order(57) + @Order(52) void testCopyLinkNoSDMRoles() throws IOException { System.out.println("Test (57): Copy link fails due to no SDM roles"); @@ -4749,7 +4750,7 @@ void testCopyLinkNoSDMRoles() throws IOException { } @Test - @Order(58) + @Order(53) void testCopyLinkFromDraftChapter() throws IOException { System.out.println("Test (58): Copy link from draft chapter to another chapter"); @@ -4837,7 +4838,7 @@ void testCopyLinkFromDraftChapter() throws IOException { // // ============= COPY ATTACHMENTS DRAFT MODE (59) ============= @Test - @Order(59) + @Order(54) void testCopyAttachmentsSuccessNewChapterDraft() throws IOException { System.out.println("Test (59): Copy attachments from one chapter to another in draft mode"); @@ -4966,7 +4967,7 @@ void testCopyAttachmentsSuccessNewChapterDraft() throws IOException { // // ============= CHANGELOG TESTS (60-64) ============= @Test - @Order(60) + @Order(55) void testViewChangelogForNewlyCreatedAttachment() throws IOException { System.out.println("Test (60): View changelog for newly created attachment in chapter"); @@ -5035,7 +5036,7 @@ void testViewChangelogForNewlyCreatedAttachment() throws IOException { } @Test - @Order(61) + @Order(56) void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { System.out.println("Test (61): Changelog after modifying note and custom property in chapter"); @@ -5121,7 +5122,7 @@ void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { } @Test - @Order(62) + @Order(57) void testChangelogAfterRenamingAttachment() throws IOException { System.out.println("Test (62): Changelog after renaming attachment in chapter"); @@ -5206,7 +5207,7 @@ void testChangelogAfterRenamingAttachment() throws IOException { } @Test - @Order(63) + @Order(58) void testChangelogForCopiedAttachment() throws IOException { System.out.println("Test (63): Changelog for copied attachment in chapter"); @@ -5297,7 +5298,7 @@ void testChangelogForCopiedAttachment() throws IOException { } @Test - @Order(64) + @Order(59) void testChangelogForNewChapter() throws IOException { System.out.println("Test (64): Changelog for attachment in newly created chapter"); @@ -5358,7 +5359,7 @@ void testChangelogForNewChapter() throws IOException { // // ============= MOVE ATTACHMENT TESTS (65-75) ============= @Test - @Order(65) + @Order(60) void testMoveAttachmentsWithSourceFacet() throws IOException { System.out.println("Test (65): Move attachments from source chapter to target chapter"); @@ -5488,7 +5489,7 @@ void testMoveAttachmentsWithSourceFacet() throws IOException { } @Test - @Order(66) + @Order(61) void testMoveAttachmentsToChapterWithDuplicate() throws IOException { System.out.println("Test (66): Move attachments to chapter with duplicate attachment"); @@ -5575,7 +5576,7 @@ void testMoveAttachmentsToChapterWithDuplicate() throws IOException { } @Test - @Order(67) + @Order(62) void testMoveAttachmentsWithNotesAndSecondaryProperties() throws IOException { System.out.println("Test (67): Move attachments with notes and secondary properties"); @@ -5684,7 +5685,7 @@ void testMoveAttachmentsWithNotesAndSecondaryProperties() throws IOException { } @Test - @Order(68) + @Order(63) void testMoveAttachmentsPartialFailure() throws IOException { System.out.println("Test (68): Move attachments with partial failure (invalid object ID)"); @@ -5762,7 +5763,7 @@ void testMoveAttachmentsPartialFailure() throws IOException { } @Test - @Order(69) + @Order(64) void testMoveAttachmentsEmptyList() throws IOException { System.out.println("Test (69): Move attachments with empty object ID list"); @@ -5808,7 +5809,7 @@ void testMoveAttachmentsEmptyList() throws IOException { } @Test - @Order(70) + @Order(65) void testMoveAttachmentsToSameChapter() throws IOException { System.out.println("Test (70): Move attachments to same chapter (should handle gracefully)"); @@ -5881,7 +5882,7 @@ void testMoveAttachmentsToSameChapter() throws IOException { } @Test - @Order(71) + @Order(66) void testMoveAttachmentsBetweenFacets() throws IOException { System.out.println("Test (71): Move attachments between different facets in chapters"); @@ -5955,7 +5956,7 @@ void testMoveAttachmentsBetweenFacets() throws IOException { } @Test - @Order(72) + @Order(67) void testMoveMultipleAttachments() throws IOException { System.out.println("Test (72): Move multiple attachments at once between chapters"); @@ -6058,7 +6059,7 @@ void testMoveMultipleAttachments() throws IOException { } @Test - @Order(73) + @Order(68) void testMoveAttachmentsAllFacets() throws IOException { System.out.println("Test (73): Move attachments from all facets between chapters"); @@ -6149,7 +6150,7 @@ void testMoveAttachmentsAllFacets() throws IOException { } @Test - @Order(74) + @Order(69) void testChainMoveAttachments() throws IOException { System.out.println("Test (74): Chain move attachments: Source -> Target1 -> Target2"); @@ -6266,7 +6267,7 @@ void testChainMoveAttachments() throws IOException { } @Test - @Order(75) + @Order(70) void testMoveAttachmentsWithoutSDMRole() throws IOException { System.out.println("Test (75): Move attachments fails without SDM role"); @@ -6366,7 +6367,7 @@ void testMoveAttachmentsWithoutSDMRole() throws IOException { } @Test - @Order(76) + @Order(71) void testRenameChapterAttachmentWithExtensionChange() throws IOException { System.out.println( "Test (76) : Rename chapter attachment changing extension from .pdf to .txt across all facets - should return extension change warning"); @@ -6485,7 +6486,7 @@ void testRenameChapterAttachmentWithExtensionChange() throws IOException { } @Test - @Order(77) + @Order(72) void testRenameChapterAttachmentWithExtensionChange_BeforeSave() throws IOException { System.out.println( "Test (77) : Upload chapter attachment in draft, rename changing extension before save across all facets - should return extension change warning"); @@ -6577,7 +6578,7 @@ void testRenameChapterAttachmentWithExtensionChange_BeforeSave() throws IOExcept } @Test - @Order(78) + @Order(73) void testDownloadMultipleAttachmentsInDraftState() throws IOException { System.out.println( "Test (76): Create book+chapter, upload pdf/txt/exe per facet in draft state, download" @@ -6691,7 +6692,7 @@ void testDownloadMultipleAttachmentsInDraftState() throws IOException { } @Test - @Order(79) + @Order(74) void testDownloadButtonDisabledWithLinkInDraftState() throws IOException { System.out.println( "Test (77): Upload pdf and link per facet to chapter, save book, edit (draft state)," @@ -6820,7 +6821,7 @@ void testDownloadButtonDisabledWithLinkInDraftState() throws IOException { } @Test - @Order(80) + @Order(75) void testDownloadMultipleAttachmentsInActiveState() throws IOException { System.out.println( "Test (78): Create book+chapter, upload pdf/txt/exe per facet, save, download in active" @@ -6930,7 +6931,7 @@ void testDownloadMultipleAttachmentsInActiveState() throws IOException { } @Test - @Order(81) + @Order(76) void testDownloadButtonDisabledWithLinkInActiveState() throws IOException { System.out.println( "Test (79): Upload pdf and link per facet to chapter, save book, pdf download enabled," @@ -7052,4 +7053,84 @@ void testDownloadButtonDisabledWithLinkInActiveState() throws IOException { api.deleteEntity(appUrl, bookEntityName, testBookID); } + + @Test + @Order(77) + void testReadCmisMetadataCreatedBy() { + System.out.println("Test (76) : Read CMIS metadata and verify createdBy field"); + String createdBy = + CmisDocumentHelper.getCmisProperty(chapterID, "sample.pdf", "cmis:createdBy"); + System.out.println("cmis:createdBy value: " + createdBy); + String tokenFlowFlag = System.getProperty("tokenFlow"); + if ("namedUser".equals(tokenFlowFlag)) { + assertEquals(username, createdBy, "cmis:createdBy should match username from credentials"); + } else { + assertNotNull(createdBy, "cmis:createdBy should not be null for technical user"); + assertFalse(createdBy.isEmpty(), "cmis:createdBy should not be empty for technical user"); + } + } + + @Test + @Order(78) + void testUploadVirusFileInScanDisabledRepo() throws IOException { + System.out.println( + "Test (77) : Upload EICAR virus file in virus scan disabled repo — expect upload to succeed"); + + for (int i = 0; i < facet.length; i++) { + boolean testStatus = false; + + // Create book and chapter + String testBookID = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + if (testBookID.equals("Could not create entity")) { + fail("Could not create book for facet: " + facet[i]); + } + + String testChapterID = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, testBookID); + if (testChapterID.equals("Could not create entity")) { + fail("Could not create chapter for facet: " + facet[i]); + } + + // Use EICAR test virus file + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } + + Map postData = new HashMap<>(); + postData.put("up__ID", testChapterID); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], testChapterID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.equals("Attachment created")) { + String testAttachmentID = createResponse.get(1); + String response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, testBookID); + if (response.equals("Saved")) { + // Verify attachment is readable (upload succeeded despite being a virus file) + response = + api.readAttachment( + appUrl, chapterEntityName, facet[i], testChapterID, testAttachmentID); + if (response.equals("OK")) { + testStatus = true; + } + } + } + + // Clean up + api.deleteEntity(appUrl, bookEntityName, testBookID); + + if (!testStatus) { + fail( + "Virus file upload should succeed in a virus scan disabled repository for facet: " + + facet[i]); + } + } + } } diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_RepoSpecific.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_RepoSpecific.java new file mode 100644 index 000000000..ced018452 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_RepoSpecific.java @@ -0,0 +1,407 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.utils.ShellScriptRunner; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +/** + * Integration tests for "Displaying Attachments Specific To Repository" with chapter-level multiple + * facets. Verifies that attachments created under one repository are not visible when the + * application switches to a different repository, and that duplicate file names across repositories + * are allowed for all facets (attachments, references, footnotes) on chapter entities. + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_Chapters_MultipleFacet_RepoSpecific { + + private static final String UPDATE_ENV_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh"; + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String bookEntityName = "Books"; + private static String chapterEntityName = "Chapters"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String tenancyModel; + private static String defaultRepositoryID; + private static String virusScanRepositoryID; + private static ApiInterface api; + + // Entity IDs used across tests + private static String bookID1; + private static String chapterID1; + private static String[] attachmentID1 = new String[3]; + private static String bookID_rename; + private static String chapterID_rename; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryID"); + virusScanRepositoryID = credentialsProperties.getProperty("virusScanRepositoryID"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryIDMT"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + private static int runUpdateEnv(String value) throws Exception { + if (tenancyModel.equals("multi")) { + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--app", "bookshop-mt-srv", "--value", value); + } + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--value", value); + } + + @Test + @Order(1) + void testSetupRepo1AndCreateAttachments() throws Exception { + System.out.println( + "Test (1) : Setup — switch to defaultRepositoryID (" + + defaultRepositoryID + + "), create book+chapter with attachments in all facets"); + + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create book + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID1 = response; + + // Create chapter inside the book + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookID1); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + chapterID1 = chapterResponse; + + // Upload attachment in each facet on the chapter + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Attachment creation should succeed for " + facet[i]); + attachmentID1[i] = createResponse.get(1); + } + + // Save via book + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Saved", response, "Book save should succeed"); + + // Verify attachments are readable + for (int i = 0; i < facet.length; i++) { + response = + api.readAttachment(appUrl, chapterEntityName, facet[i], chapterID1, attachmentID1[i]); + assertEquals( + "OK", + response, + "Attachment should be readable under defaultRepositoryID for " + facet[i]); + + List> attachments = + api.fetchEntityMetadata(appUrl, chapterEntityName, facet[i], chapterID1); + assertEquals( + 1, + attachments.size(), + "Chapter should have 1 attachment under defaultRepositoryID for " + facet[i]); + } + } + + @Test + @Order(2) + void testSwitchToRepo2AttachmentsNotVisible() throws Exception { + System.out.println( + "Test (2) : Switch to virusScanRepositoryID, verify chapter attachments from defaultRepositoryID are not visible"); + + int exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + String response = api.checkEntity(appUrl, chapterEntityName, chapterID1); + assertEquals("Entity exists", response, "Chapter should still be visible after repo switch"); + + for (int i = 0; i < facet.length; i++) { + List> attachments = + api.fetchEntityMetadata(appUrl, chapterEntityName, facet[i], chapterID1); + assertEquals( + 0, + attachments.size(), + "Chapter should have 0 attachments after switching to virusScanRepositoryID for " + + facet[i]); + } + } + + @Test + @Order(3) + void testDuplicateAttachmentCreateAcrossRepos() throws Exception { + System.out.println( + "Test (3) : Create attachment with same name on chapter under virusScanRepositoryID in all facets — should succeed"); + + // Still on virusScanRepositoryID + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Entity in draft mode", response, "Edit book should succeed"); + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Duplicate chapter attachment across repos should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Saved", response, "Book save should succeed"); + } + + @Test + @Order(4) + void testDuplicateAttachmentRenameAcrossRepos() throws Exception { + System.out.println( + "Test (4) : Create new book+chapter with sample.pdf in defaultRepositoryID, switch to virusScanRepositoryID, upload" + + " sample1.pdf on chapter, rename to sample.pdf in all facets — should succeed"); + + // Switch to defaultRepositoryID + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create new book + chapter + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID_rename = response; + + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookID_rename); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + chapterID_rename = chapterResponse; + + // Upload sample.pdf to chapter under defaultRepositoryID in all facets + ClassLoader classLoader = getClass().getClassLoader(); + File pdfFile = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID_rename, srvpath, postData, pdfFile); + assertEquals( + "Attachment created", + createResponse.get(0), + "Attachment creation should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Saved", response, "Book save should succeed under defaultRepositoryID"); + + // Switch to virusScanRepositoryID + exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + // Edit book, upload sample1.pdf (same extension, different name) to chapter, rename to + // sample.pdf + response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Entity in draft mode", response, "Edit book should succeed"); + + for (int i = 0; i < facet.length; i++) { + File pdfFile2 = new File(classLoader.getResource("sample1.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID_rename, srvpath, postData, pdfFile2); + assertEquals( + "Attachment created", + createResponse.get(0), + "Upload sample1.pdf to chapter should succeed for " + facet[i]); + String attachmentID2 = createResponse.get(1); + + response = + api.renameAttachment( + appUrl, chapterEntityName, facet[i], chapterID_rename, attachmentID2, "sample.pdf"); + assertEquals( + "Renamed", + response, + "Renaming to duplicate name on chapter across repos should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Saved", response, "Book save after chapter rename should succeed"); + } + + @Test + @Order(5) + void testCreateAttachment_NonExistentRepo_FailsWithRepoInfoError() throws Exception { + String fakeRepoId = "non-existent-repo-" + UUID.randomUUID(); + System.out.println( + "Test (5) : Switch to non-existent repo (" + + fakeRepoId + + ") and attempt attachment creation — expect failure"); + + // Switch to a random non-existent repository ID + int exitCode = runUpdateEnv(fakeRepoId); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + + // Create a book entity (draft creation should still succeed) + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + String bookId = response; + + // Create a chapter inside the book + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookId); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + String chapterId = chapterResponse; + + // Upload an attachment to the chapter + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.txt").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", chapterId); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[0], chapterId, srvpath, postData, file); + + // Attachment content upload should fail because the repo doesn't exist + String status = createResponse.get(0); + assertNotEquals( + "Attachment created", status, "Attachment should fail with non-existent repository"); + assertTrue( + status.toLowerCase().contains("repository") + || status.toLowerCase().contains("error") + || status.toLowerCase().contains("not found") + || status.toLowerCase().contains("failed"), + "Error should indicate repository issue. Got: " + status); + System.out.println("Expected error received: " + status); + } + + @Test + @Order(6) + void testRevertToDefaultRepository() throws Exception { + System.out.println("Test (6) : Revert REPOSITORY_ID to default repository"); + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_VersionedRepository.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_VersionedRepository.java new file mode 100644 index 000000000..bb7a1fd2e --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_VersionedRepository.java @@ -0,0 +1,158 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +class IntegrationTest_Chapters_MultipleFacet_VersionedRepository { + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String bookEntityName = "Books"; + private static String chapterEntityName = "Chapters"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String tenancyModel; + private static ApiInterface api; + private static String bookID; + private static String chapterID; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + @Test + void testCreateBookChapterAndUploadAttachmentShouldFail() throws IOException { + System.out.println( + "Test (2) : Create book+chapter and upload attachments on versioned repository in all facets — expect error"); + + // Create book + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID = response; + + // Create chapter + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookID); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + chapterID = chapterResponse; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID, srvpath, postData, file); + String check = createResponse.get(0); + + if (check.equals("Attachment created")) { + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID); + assertNotEquals( + "Saved", response, "Save should fail on versioned repository for " + facet[i]); + System.out.println("Save failed as expected for " + facet[i] + ": " + response); + } else { + System.out.println("Operation failed as expected for " + facet[i] + ": " + check); + assertTrue( + check.contains("error") || check.contains("Error"), + "Response should contain an error message for " + facet[i]); + } + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_Virus.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_Virus.java new file mode 100644 index 000000000..dd9402ae6 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Chapters_MultipleFacet_Virus.java @@ -0,0 +1,307 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_Chapters_MultipleFacet_Virus { + private static String token; + private static String bookID; + private static String chapterID; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String bookEntityName = "Books"; + private static String chapterEntityName = "Chapters"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static ApiInterface api; + private static String[] attachmentID1 = new String[3]; + private static String[] attachmentID2 = new String[3]; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + String tenancyModel = System.getProperty("tenancyModel"); + String tenant = System.getProperty("tenant"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + if (tenancyModel.equals("single")) { + System.out.println("Running integration tests | Single tenant Scenario"); + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + if (tenant.equals("TENANT1")) { + System.out.println("Running integration tests | Multitenant Scenario | SDM DEV Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else if (tenant.equals("TENANT2")) { + System.out.println( + "Running integration tests | Multitenant Scenario | Googleworkspace Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT2"); + } else { + throw new IllegalArgumentException("Invalid tenant specified: " + tenant); + } + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request; + + String tokenFlowFlag = System.getProperty("tokenFlow"); + if (tokenFlowFlag.equals("namedUser")) { + System.out.println("Named user token flow"); + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + System.out.println("Technical user token flow"); + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + String errorBody = response.body().string(); + System.out.println("Error body: " + errorBody); + } + token = new ObjectMapper().readTree(response.body().string()).get("access_token").asText(); + response.close(); + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else if (tenancyModel.equals("single")) { + config.put("serviceName", serviceName); + api = new Api(config); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + } + + /** + * Helper method to wait for attachment upload completion. + * + * @param chapterId The ID of the chapter containing the attachment + * @param attachmentId The ID of the attachment to check + * @param facetName The facet name for the attachment + * @param timeoutSeconds Maximum time to wait in seconds + * @return true if upload completed successfully, false if failed or timed out + */ + private boolean waitForUploadCompletion( + String chapterId, String attachmentId, String facetName, int timeoutSeconds) { + int maxIterations = timeoutSeconds / 2; + for (int i = 0; i < maxIterations; i++) { + try { + Map metadata = + api.fetchMetadataDraft(appUrl, chapterEntityName, facetName, chapterId, attachmentId); + String uploadStatus = (String) metadata.get("uploadStatus"); + + if ("Success".equals(uploadStatus)) { + return true; + } else if ("Failed".equals(uploadStatus)) { + System.err.println("Upload failed for attachment: " + attachmentId); + return false; + } + + Thread.sleep(2000); + } catch (Exception e) { + System.err.println( + "Error checking upload status for attachment " + attachmentId + ": " + e.getMessage()); + return false; + } + } + + System.err.println("Upload timed out for attachment: " + attachmentId); + return false; + } + + @Test + @Order(1) + void testCreateBookChapterAndCheck() { + System.out.println("Test (1) : Create book+chapter and check if they exist"); + boolean testStatus = false; + + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + if (!response.equals("Could not create entity")) { + bookID = response; + + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookID); + if (!chapterResponse.equals("Could not create entity")) { + chapterID = chapterResponse; + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID); + if (response.equals("Saved")) { + response = api.checkEntity(appUrl, bookEntityName, bookID); + if (response.equals("Entity exists")) { + response = api.checkEntity(appUrl, chapterEntityName, chapterID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + } + } + if (!testStatus) { + fail("Could not create book+chapter"); + } + } + + @Test + @Order(2) + void testUpdateEmptyBookChapter() { + System.out.println("Test (2) : Update an existing book+chapter"); + boolean testStatus = false; + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID); + if (response.equals("Entity in draft mode")) { + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID); + if (response.equals("Saved")) { + response = api.checkEntity(appUrl, chapterEntityName, chapterID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + if (!testStatus) { + fail("Could not update book+chapter"); + } + } + + @Test + @Order(3) + void testUploadSingleAttachmentPDF() throws IOException { + System.out.println("Test (3) : Upload pdf in all facets on chapter"); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID); + assertEquals("Entity in draft mode", response, "Book should be in draft mode"); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID, srvpath, postData, file); + assertEquals( + "Attachment created", createResponse.get(0), "Upload should succeed for " + facet[i]); + attachmentID1[i] = createResponse.get(1); + + response = + api.readAttachmentDraft(appUrl, chapterEntityName, facet[i], chapterID, attachmentID1[i]); + assertEquals("OK", response, "Attachment should be readable in draft for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID); + assertEquals("Saved", response, "Book save should succeed"); + + for (int i = 0; i < facet.length; i++) { + response = + api.readAttachment(appUrl, chapterEntityName, facet[i], chapterID, attachmentID1[i]); + assertEquals("OK", response, "Attachment should be readable after save for " + facet[i]); + } + } + + @Test + @Order(4) + void testUploadVirusFileInScannedRepo() throws IOException { + System.out.println( + "Test (4) : Upload EICAR virus file in all facets on chapter — expect virus scan to reject"); + + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } + + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID); + assertEquals("Entity in draft mode", response, "Book should be in draft mode"); + + for (int i = 0; i < facet.length; i++) { + boolean testStatus = false; + + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facet[i], chapterID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.contains("malware") || check.contains("potential malware")) { + testStatus = true; + } else if (check.equals("Attachment created")) { + attachmentID2[i] = createResponse.get(1); + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID); + if (response.equals("Saved")) { + boolean uploadSucceeded = + waitForUploadCompletion(chapterID, attachmentID2[i], facet[i], 120); + if (!uploadSucceeded) { + testStatus = true; + } else { + fail( + "Virus file should have been rejected by the virus scanner but upload succeeded for " + + facet[i]); + } + } + } + + if (!testStatus) { + fail("Could not verify virus file rejection for " + facet[i]); + } + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet.java index fd0e0d7bf..f67ddc437 100644 --- a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet.java +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet.java @@ -4,16 +4,14 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.utils.CmisDocumentHelper; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardCopyOption; -import java.time.LocalDateTime; import java.util.*; -import java.util.stream.Collectors; import okhttp3.*; -import okio.ByteString; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.*; @@ -358,6510 +356,6784 @@ void testUploadSinglePDF() throws IOException { } } - @Test - @Order(4) - void testUploadSingleTXT() throws IOException { - System.out.println("Test (4) : Upload attachment, reference, and footnote TXT"); - Boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.txt").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "text/plain"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Entity in draft mode")) { - // Creation of attachment, reference and footnote - for (int i = 0; i < facet.length; i++) { - ID2[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID, postData, file); - } - testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID, ID2); - } - if (!testStatus) { - fail("Could not upload sample.txt " + response); - } - } - - @Test - @Order(5) - void testUploadSingleEXE() throws IOException { - System.out.println("Test (5) : Upload attachment, reference, and footnote EXE"); - Boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.exe").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/octet-stream"); // Common mime-type for executables - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Entity in draft mode")) { - // Creation of attachment, reference and footnote - for (int i = 0; i < facet.length; i++) { - ID3[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID, postData, file); - } - testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID, ID3); - } - if (!testStatus) { - fail("Could not upload sample.exe " + response); - } - } - - @Test - @Order(6) - void testUploadPDFDuplicate() throws IOException { - System.out.println("Test (6) : Upload duplicate PDF as attachment, reference, and footnote"); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if ("Entity in draft mode".equals(response)) { - Boolean allFacetsFailedCorrectly = true; - for (int i = 0; i < facet.length; i++) { - List facetResponse = - api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, file); - allFacetsFailedCorrectly &= checkDuplicateCreation(facet[i], facetResponse); - } - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (!allFacetsFailedCorrectly) { - fail("One or more facets were incorrectly accepted as new."); - } - } else { - fail("Entity could not be edited to draft mode."); - } - } - - @Test - @Order(7) - void testUploadSinglePDFWithAttachmentReferenceFootnote() throws IOException { - System.out.println( - "Test (7) : Upload duplicate PDF in different entity with attachment, reference, and footnote"); - Boolean testStatus = false; - // Create a new entity draft - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!"Could not create entity".equals(response)) { - entityID2 = response; - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - - if ("Saved".equals(response)) { - response = api.checkEntity(appUrl, entityName, entityID2); - if ("Entity exists".equals(response)) { - testStatus = true; - } - } - } - if (!testStatus) { - fail("Could not create entity"); - } - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID2); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - // Edit entity to draft mode - response = api.editEntityDraft(appUrl, entityName, srvpath, entityID2); - if ("Entity in draft mode".equals(response)) { - // Create attachment, reference, and footnote - for (int i = 0; i < facet.length; i++) { - ID4[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID2, postData, file); - } - // Verify and save - testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID2, ID4); - } - if (!testStatus) { - fail("Could not upload sample.pdf as an attachment, reference, or footnote: " + response); - } - } - - @Test - @Order(8) - void testRenameEntities() { - System.out.println("Test (8) : Rename single attachment, reference, and footnote"); - Boolean testStatus = true; - - try { - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - - if ("Entity in draft mode".equals(response)) { - String[] name = {"sample123", "reference123", "footnote123"}; - for (int i = 0; i < facet.length; i++) { - // Read the facet to ensure it exists - response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID[i], name[i]); - if (!"Renamed".equals(response)) { - testStatus = false; - System.out.println(facet[i] + " was not renamed: " + response); - } - } - // Save entity draft if everything is renamed - if (testStatus) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (!"Saved".equals(response)) { - testStatus = false; - System.out.println("Entity draft was not saved: " + response); - } - } else { - // Attempt save despite potential rename failures - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } else { - testStatus = false; - System.out.println("Entity was not put into draft mode: " + response); - } - } catch (Exception e) { - testStatus = false; - System.out.println("Exception during renaming entities: " + e.getMessage()); - } - - if (!testStatus) { - fail("There was an error during the rename test process."); - } - } - - @Test - @Order(9) - void testCreateEntitiesWithUnsupportedCharacter() throws IOException { - System.out.println("Test (9): Create attachments with unsupported characters"); - boolean testStatus = false; - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (!"Entity in draft mode".equals(response)) { - fail("Entity not in draft mode: " + response); - return; - } - - for (int i = 0; i < facet.length; i++) { - postData.put("up__ID", entityID); - List createResponse = - api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, tempFile); - - String check = createResponse.get(0); - if (!"Attachment created".equals(check)) { - System.out.println("Failed to create attachment for facet: " + facet[i]); - continue; - } - - String restrictedName = "a/\\bc.pdf"; - response = - api.renameAttachment(appUrl, entityName, facet[i], entityID, ID4[i], restrictedName); - } - - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - if (response.equals(expected)) { - api.deleteEntityDraft(appUrl, entityName, entityID); - testStatus = true; - } - - if (!testStatus) { - fail("Facets renamed with restricted characters were not correctly rejected."); - } - } - - @Test - @Order(10) - void testRenameEntitiesWithUnsupportedCharacter() { - System.out.println("Test (10) : Rename attachments with unsupported characters"); - Boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String[] name = {"sample/1234", "reference1/234", "footnote1/234"}; - if (response.equals("Entity in draft mode")) { - for (int i = 0; i < facet.length; i++) { - response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name[i]); - if (response.equals("Renamed")) counter++; - } - if (counter >= 2) { - counter = -1; // Reset counter for the next check - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"reference1/234\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"sample/1234\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"footnote1/234\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - if (response.equals(expected)) { - for (int i = 0; i < facet.length; i++) { - response = - api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], "sample.pdf"); - } - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment was renamed with unsupported characters"); - } - } - - @Test - @Order(11) - void testRenameMultipleEntityComponents() { - System.out.println("Test (11) : Rename multiple attachments, references, and footnotes"); - boolean testStatus = true; - - String draftResponse = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (!"Entity in draft mode".equals(draftResponse)) { - fail("Entity is not in draft mode."); - return; - } - String[] name = {"sample1234", "reference1234", "footnote1234"}; - String[] name2 = {"sample12345", "reference12345", "footnote12345"}; - for (int i = 0; i < facet.length; i++) { - // Read the facet to ensure it exists - testStatus &= renameAndCheck(facet[i], ID2[i], entityID, name[i]); - testStatus &= renameAndCheck(facet[i], ID3[i], entityID, name2[i]); - } - // Save the draft if all renames succeeded - if (testStatus) { - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (!"Saved".equals(saveResponse)) { - fail("Entity draft was not saved after renaming."); - } - } else { - // Save draft even if renaming failed to preserve state - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - fail("One or more components were not renamed."); - } - } - - @Test - @Order(12) - void testRenameSingleDuplicate() { - System.out.println("Test (12) : Rename duplicates for attachment, reference, and footnote"); - Boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String[] name = {"sample1234", "reference1234", "footnote1234"}; - String[] name2 = {"sample123456", "reference123456", "footnote123456"}; - if (response.equals("Entity in draft mode")) { - for (int i = 0; i < facet.length; i++) { - response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name[i]); - if (response.equals("Renamed")) counter++; - } - if (counter >= 2) { - counter = -1; // Reset counter for the next check - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - String.format( - "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"%s\\\" already exists. Rename the object and try again.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"An object named \\\"%s\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"%s\\\" already exists. Rename the object and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}", - name[1], name[0], name[2]); - if (response.equals(expected)) { - for (int i = 0; i < facet.length; i++) { - // Attempt to rename again with a different name - response = - api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name2[i]); - if (response.equals("Renamed")) counter++; - } - } - if (counter >= 2) { - // If all renames were successful, save the draft - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - testStatus = true; - } - } else { - testStatus = false; - fail("Attachment was renamed"); - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - } - - @Test - @Order(13) - void testRenameMultipleEntitiesWithOneUnsupportedCharacter() { - System.out.println( - "Test (13) : Rename multiple files out of which one file name contains unsupported characters"); - boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String[] names = {"summary_1234", "reference_4567", "note/invalid"}; - - if (response.equals("Entity in draft mode")) { - int successCount = 0; - for (int i = 0; i < facet.length; i++) { - response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], names[i]); - if (response.equals("Renamed")) successCount++; - } - - if (successCount >= 2) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"note/invalid\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\"}}"; - if (response.equals(expected)) { - response = - api.renameAttachment(appUrl, entityName, facet[2], entityID, ID3[2], "note_valid"); - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) testStatus = true; - } - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - - if (!testStatus) { - fail("Attachment was renamed with unsupported characters"); - } - } - - @Test - @Order(14) - void testRenameToValidateNames() throws IOException { - System.out.println("Test (14) : Rename attachments to validate names"); - String[] generatedIDs = new String[3]; - String[] duplicateIDs = new String[1]; - boolean testStatus = false, allRenamedSuccessfully = true; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID3 = response; - - String[] invalidNames = {"Restricted/Character", " ", "duplicateName.pdf"}; - String duplicateName = "duplicateName.pdf"; - - ClassLoader classLoader = getClass().getClassLoader(); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - // Creation of attachment, reference and footnote - for (int i = 0; i < facet.length; i++) { - File file = new File(classLoader.getResource("sample2.pdf").getFile()); - generatedIDs[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - response = - api.renameAttachment( - appUrl, entityName, facet[i], entityID3, generatedIDs[i], invalidNames[i]); - allRenamedSuccessfully &= "Renamed".equals(response); - } - File file = new File(classLoader.getResource("sample.pdf").getFile()); - // Creating duplicate name for last facet - duplicateIDs[0] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[2], entityID3, postData, file); - String response2 = - api.renameAttachment( - appUrl, entityName, facet[2], entityID3, duplicateIDs[0], duplicateName); - - if (allRenamedSuccessfully && "Renamed".equals(response2)) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"The object name cannot be empty or consist entirely of space characters. Enter a value.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"Restricted/Character\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"duplicateName.pdf\\\" already exists. Rename the object and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - if (response.equals(expected)) { - response = api.deleteEntityDraft(appUrl, entityName, entityID3); - if (response.equals("Entity Draft Deleted")) testStatus = true; - } - } - if (!testStatus) fail("Could not create entity"); - } else { - fail("Could not create entity"); - return; - } - } - - @Test - @Order(15) - void testRenameEntitiesWithoutSDMRole() throws IOException { - System.out.println("Test (15) : Rename attachments where user don't have SDM-Roles"); - boolean testStatus = true; - try { - String apiResponse = apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, entityID); - if ("Entity in draft mode".equals(apiResponse)) { - String[] name = {"sample456", "reference456", "footnote456"}; - for (int i = 0; i < facet.length; i++) { - apiResponse = - apiNoRoles.renameAttachment(appUrl, entityName, facet[i], entityID, ID[i], name[i]); - if (!"Renamed".equals(apiResponse)) { - testStatus = false; - } - } - if (testStatus) { - apiResponse = apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "[{\"code\":\"\",\"message\":\"Could not update the following files. \\n\\n\\t\\u2022 reference123\\n\\nYou do not have the required permissions to update attachments. Kindly contact the admin\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"Could not update the following files. \\n\\n\\t\\u2022 sample123\\n\\nYou do not have the required permissions to update attachments. Kindly contact the admin\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"Could not update the following files. \\n\\n\\t\\u2022 footnote123\\n\\nYou do not have the required permissions to update attachments. Kindly contact the admin\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (!apiResponse.equals(expected)) { - testStatus = false; - } - } else { - apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - } catch (Exception e) { - testStatus = false; - } - if (!testStatus) { - fail("Attachment got renamed without SDM roles."); - } - } - - @Test - @Order(16) - void testDeleteSingleAttachment() throws IOException { - System.out.println("Test (16) : Delete single attachment, reference, and footnote"); - Boolean testStatus = false; - counter = -1; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Entity in draft mode")) { - for (int i = 0; i < facet.length; i++) { - response = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID[i]); - if (response.equals("Deleted")) counter++; - } - if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - counter = -1; // Reset counter for the next check - if (response.equals("Saved")) { - for (int i = 0; i < facet.length; i++) { - response = api.readAttachment(appUrl, entityName, facet[i], entityID, ID[i]); - if (response.equals("Could not read Attachment")) counter++; - } - if (counter >= 2) testStatus = true; - else fail("Could not read deleted facets"); - } else { - fail("Could not save entity after deletion"); - } - } - } - - @Test - @Order(17) - void testDeleteMultipleAttachmentsReferencesFootnotes() throws IOException { - System.out.println("Test (17) : Delete multiple attachments, references, and footnotes"); - Boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Entity in draft mode")) { - for (int i = 0; i < facet.length; i++) { - String response1 = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID2[i]); - String response2 = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID3[i]); - if (response1.equals("Deleted") && response2.equals("Deleted")) counter++; - } - } - if (counter >= 2) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - if (response.equals("Saved")) { - for (int i = 0; i < facet.length; i++) { - String response1 = api.readAttachment(appUrl, entityName, facet[i], entityID, ID2[i]); - String response2 = api.readAttachment(appUrl, entityName, facet[i], entityID, ID3[i]); - if (response1.equals("Could not read " + facet[i]) - && response2.equals("Could not read " + facet[i])) { - counter++; - } - } - if (counter >= 2) testStatus = true; - else fail("Could not read deleted facets"); - } else fail("Could not save entity after deletion"); - } - - @Test - @Order(18) - void testUploadBlockedMimeType() throws IOException { - System.out.println("Test (18) : Upload blocked mimeType .rtf"); - Boolean testStatus = false; - - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!"Could not create entity".equals(response)) { - entityID2 = response; - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.rtf")).getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID2); - postData.put("mimeType", "application/rtf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - boolean allBlocked = true; - for (int i = 0; i < facet.length; i++) { - List createResponse = - api.createAttachment(appUrl, entityName, facet[i], entityID2, srvpath, postData, file); - - String actualResponse = createResponse.get(0); - String expectedJson = - "{\"error\":{\"code\":\"500\",\"message\":\"This file type is not allowed in this repository. Contact your administrator for assistance.\"}}"; - - if (!expectedJson.equals(actualResponse)) { - allBlocked = false; - System.out.println( - "Facet " + facet[i] + " incorrectly accepted blocked mimeType: " + actualResponse); - } - } - - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - if ("Saved".equals(response) && allBlocked) { - testStatus = true; - } - } - - if (!testStatus) { - fail("Attachment got uploaded with blocked .rtf MIME type"); - } - } - - @Test - @Order(19) - void testDeleteEntity() { - System.out.println("Test (19) : Delete entity"); - Boolean testStatus = false; - String response = api.deleteEntity(appUrl, entityName, entityID); - String response2 = api.deleteEntity(appUrl, entityName, entityID2); - if (response.equals("Entity Deleted") && response2.equals("Entity Deleted")) testStatus = true; - if (!testStatus) fail("Could not delete entity"); - } - - @Test - @Order(20) - void testUpdateValidSecondaryProperty_beforeEntityIsSaved_single() throws IOException { - System.out.println("Test (20) : Rename & Update secondary property before entity is saved"); - System.out.println("Creating entity"); - - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - - if (!response.equals("Could not create entity")) { - entityID3 = response; - - System.out.println("Creating attachment, reference, and footnote"); - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - for (int i = 0; i < facet.length; i++) { - ID[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } - - System.out.println("Attachments, References, and Footnotes created"); - - // Use valid dropdown value for customProperty1 - Integer secondaryPropertyInt = 1234; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - - String[] name = {"sample1234.pdf", "reference1234.pdf", "footnote1234.pdf"}; - - for (int i = 0; i < facet.length; i++) { - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name[i]); - - // Update customProperty1 (String - dropdown value) - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - - // Update customProperty2 (Integer) - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - - // Update customProperty5 (DateTime) - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - - // Update customProperty6 (Boolean) - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) { - counter++; - } - } - - if (counter >= 2) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - } - if (response.equals("Saved")) { - testStatus = true; - } - } - - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(21) - void testUpdateValidSecondaryProperty_afterEntityIsSaved_single() { - System.out.println("Test (21): Rename & Update secondary property after entity is saved"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - System.out.println("Editing entity"); - - if (response.equals("Entity in draft mode")) { - // Sample secondary properties - String name[] = {"sample.pdf", "reference_sample.pdf", "footnote_sample.pdf"}; - Integer secondaryPropertyInt = 42; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - - System.out.println("Renaming and updating secondary properties for attachment"); - for (int i = 0; i < facet.length; i++) { - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name[i]); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) counter++; - } - if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachment"); - } - // Clean up - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (!deleteEntityResponse.equals("Entity Deleted")) fail("Could not delete entity"); - } - if (!testStatus) fail("Could not update secondary properties after entity is saved"); - } - - @Test - @Order(22) - void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_single() throws IOException { - System.out.println( - "Test (22): Rename & Update invalid secondary property before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID3 = response; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - for (int i = 0; i < facet.length; i++) { - ID[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } - // Prepare test data - String name1 = "sample1234.pdf"; - Integer secondaryPropertyInt = 1234; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - String invalidProperty = "testid"; - - for (int i = 0; i < facet.length; i++) { - // Rename and update secondary properties - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for invalid ID - String updateSecondaryPropertyResponse4 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], invalidProperty); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) counter++; - } - if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - for (int i = 0; i < facet.length; i++) { - Map FacetMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); - assertEquals("sample.pdf", FacetMetadata.get("fileName")); - assertNull(FacetMetadata.get("customProperty3")); - assertNull(FacetMetadata.get("customProperty4")); - assertNull(FacetMetadata.get("customProperty1_code")); - assertNull(FacetMetadata.get("customProperty2")); - assertNull(FacetMetadata.get("customProperty6")); - assertNull(FacetMetadata.get("customProperty5")); - } - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Rename & update secondary properties for attachment is unsuccessfull"); - } - } - if (!testStatus) - fail( - "Could not update secondary property before entity is saved for attachment, reference, or footnote"); - } - - @Test - @Order(23) - void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_single() throws IOException { - System.out.println( - "Test (23): Rename & Update invalid secondary property after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Entity in draft mode")) { - String name1 = "sample.pdf"; - Integer secondaryPropertyInt = 12; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - String invalidProperty = "testidinvalid"; - - for (int i = 0; i < facet.length; i++) { - // Rename and update secondary properties - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - // Update secondary properties for Drop down - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for invalid ID - String updateSecondaryPropertyResponse4 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], invalidProperty); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) counter++; - } - if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - for (int i = 0; i < facet.length; i++) { - Map FacetMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); - assertEquals("sample.pdf", FacetMetadata.get("fileName")); - assertNull(FacetMetadata.get("customProperty3")); - assertNull(FacetMetadata.get("customProperty4")); - assertNull(FacetMetadata.get("customProperty1_code")); - assertNull(FacetMetadata.get("customProperty2")); - assertNull(FacetMetadata.get("customProperty6")); - assertNull(FacetMetadata.get("customProperty5")); - } - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update secondary properties for attachment, reference, footnote is unsuccessfull"); - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (!deleteEntityResponse.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } - if (!testStatus) - fail( - "Could not update secondary property after entity is saved for attachment, reference, or footnote"); - } - - @Test - @Order(24) - void testUpdateValidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (24): Rename & Update valid secondary properties for multiple facets before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID3 = response; - - System.out.println("Entity created"); - ClassLoader classLoader = getClass().getClassLoader(); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - System.out.println("Creating attachment, reference, and footnote PDF"); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - for (int i = 0; i < facet.length; i++) { - ID[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } - - System.out.println("Creating attachment, reference, and footnote TXT"); - file = new File(classLoader.getResource("sample.txt").getFile()); - postData.put("mimeType", "application/txt"); - for (int i = 0; i < facet.length; i++) { - ID2[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } - - System.out.println("Creating attachment, reference, and footnote EXE"); - file = new File(classLoader.getResource("sample.exe").getFile()); - postData.put("mimeType", "application/exe"); - for (int i = 0; i < facet.length; i++) { - ID3[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } - Boolean Updated1[] = new Boolean[3]; - Boolean Updated2[] = new Boolean[3]; - Boolean Updated3[] = new Boolean[3]; - String name1 = "sample1234.pdf"; - Integer secondaryPropertyInt1 = 1234; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - // PDF - System.out.println("Renaming and updating secondary properties for PDF"); - for (int i = 0; i < facet.length; i++) { - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) { - Updated1[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); - } - } - - // TXT - System.out.println("Renaming and updating secondary properties for TXT"); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], bodyBool); - if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { - Updated2[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); - } - } - - // EXE - System.out.println("Renaming and updating secondary properties for EXE"); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponseEXE3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], bodyDate); - - if (updateSecondaryPropertyResponseEXE1.equals("Updated") - && updateSecondaryPropertyResponseEXE2.equals("Updated") - && updateSecondaryPropertyResponseEXE3.equals("Updated")) { - Updated3[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); - } - } - if (Updated1[0] - && Updated1[1] - && Updated1[2] - && Updated2[0] - && Updated2[1] - && Updated2[2] - && Updated3[0] - && Updated3[1] - && Updated3[2]) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties"); - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(25) - void testUpdateValidSecondaryProperty_afterEntityIsSaved_multipleAttachments() { - System.out.println( - "Test (25): Rename & Update valid secondary properties for multiple facets after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Entity in draft mode")) { - Boolean Updated1[] = new Boolean[3]; - Boolean Updated2[] = new Boolean[3]; - Boolean Updated3[] = new Boolean[3]; - - String name1 = "sample1.pdf"; - Integer secondaryPropertyInt1 = 12; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - System.out.println("Renaming and updating secondary properties for PDF"); - for (int i = 0; i < facet.length; i++) { - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - // Update secondary properties for Drop down - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated")) { - Updated1[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); - } - } - - // TXT - System.out.println("Renaming and updating secondary properties for TXT"); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], bodyBool); - if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { - Updated2[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); - } - } - - // EXE - System.out.println("Renaming and updating secondary properties for EXE"); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for Drop down - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponseEXE3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], bodyDate); - - if (updateSecondaryPropertyResponseEXE1.equals("Updated") - && updateSecondaryPropertyResponseEXE2.equals("Updated") - && updateSecondaryPropertyResponseEXE3.equals("Updated")) { - Updated3[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); - } - } - - if (Updated1[0] - && Updated1[1] - && Updated1[2] - && Updated2[0] - && Updated2[1] - && Updated2[2] - && Updated3[0] - && Updated3[1] - && Updated3[2]) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachments"); - } - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - if (!testStatus) { - fail("Could not update secondary property after entity is saved"); - } - } - - @Test - @Order(26) - void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (26): Rename & Update invalid and valid secondary properties for multiple facets before entity is saved"); - System.out.println("Creating entity"); + // @Test + // @Order(4) + // void testUploadSingleTXT() throws IOException { + // System.out.println("Test (4) : Upload attachment, reference, and footnote TXT"); + // Boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.txt").getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "text/plain"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Entity in draft mode")) { + // // Creation of attachment, reference and footnote + // for (int i = 0; i < facet.length; i++) { + // ID2[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID, postData, file); + // } + // testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID, ID2); + // } + // if (!testStatus) { + // fail("Could not upload sample.txt " + response); + // } + // } - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // @Test + // @Order(5) + // void testUploadSingleEXE() throws IOException { + // System.out.println("Test (5) : Upload attachment, reference, and footnote EXE"); + // Boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.exe").getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/octet-stream"); // Common mime-type for executables + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Entity in draft mode")) { + // // Creation of attachment, reference and footnote + // for (int i = 0; i < facet.length; i++) { + // ID3[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID, postData, file); + // } + // testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID, ID3); + // } + // if (!testStatus) { + // fail("Could not upload sample.exe " + response); + // } + // } - if (!"Could not create entity".equals(response)) { - entityID3 = response; - System.out.println("Entity created"); + // @Test + // @Order(6) + // void testUploadPDFDuplicate() throws IOException { + // System.out.println("Test (6) : Upload duplicate PDF as attachment, reference, and footnote"); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if ("Entity in draft mode".equals(response)) { + // Boolean allFacetsFailedCorrectly = true; + // for (int i = 0; i < facet.length; i++) { + // List facetResponse = + // api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, + // file); + // allFacetsFailedCorrectly &= checkDuplicateCreation(facet[i], facetResponse); + // } + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (!allFacetsFailedCorrectly) { + // fail("One or more facets were incorrectly accepted as new."); + // } + // } else { + // fail("Entity could not be edited to draft mode."); + // } + // } - ClassLoader classLoader = getClass().getClassLoader(); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // @Test + // @Order(7) + // void testUploadSinglePDFWithAttachmentReferenceFootnote() throws IOException { + // System.out.println( + // "Test (7) : Upload duplicate PDF in different entity with attachment, reference, and + // footnote"); + // Boolean testStatus = false; + // // Create a new entity draft + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!"Could not create entity".equals(response)) { + // entityID2 = response; + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + + // if ("Saved".equals(response)) { + // response = api.checkEntity(appUrl, entityName, entityID2); + // if ("Entity exists".equals(response)) { + // testStatus = true; + // } + // } + // } + // if (!testStatus) { + // fail("Could not create entity"); + // } - // Create PDF attachments - postData.put("mimeType", "application/pdf"); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - for (int i = 0; i < facet.length; i++) { - ID[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID2); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // // Edit entity to draft mode + // response = api.editEntityDraft(appUrl, entityName, srvpath, entityID2); + // if ("Entity in draft mode".equals(response)) { + // // Create attachment, reference, and footnote + // for (int i = 0; i < facet.length; i++) { + // ID4[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID2, postData, file); + // } + // // Verify and save + // testStatus = verifyDraftAndSave(appUrl, serviceName, entityName, entityID2, ID4); + // } + // if (!testStatus) { + // fail("Could not upload sample.pdf as an attachment, reference, or footnote: " + response); + // } + // } - // Create TXT attachments - postData.put("mimeType", "application/txt"); - file = new File(classLoader.getResource("sample.txt").getFile()); - for (int i = 0; i < facet.length; i++) { - ID2[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } + // @Test + // @Order(8) + // void testRenameEntities() { + // System.out.println("Test (8) : Rename single attachment, reference, and footnote"); + // Boolean testStatus = true; + + // try { + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + + // if ("Entity in draft mode".equals(response)) { + // String[] name = {"sample123", "reference123", "footnote123"}; + // for (int i = 0; i < facet.length; i++) { + // // Read the facet to ensure it exists + // response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID[i], + // name[i]); + // if (!"Renamed".equals(response)) { + // testStatus = false; + // System.out.println(facet[i] + " was not renamed: " + response); + // } + // } + // // Save entity draft if everything is renamed + // if (testStatus) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (!"Saved".equals(response)) { + // testStatus = false; + // System.out.println("Entity draft was not saved: " + response); + // } + // } else { + // // Attempt save despite potential rename failures + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } else { + // testStatus = false; + // System.out.println("Entity was not put into draft mode: " + response); + // } + // } catch (Exception e) { + // testStatus = false; + // System.out.println("Exception during renaming entities: " + e.getMessage()); + // } - // Create EXE attachments - postData.put("mimeType", "application/exe"); - file = new File(classLoader.getResource("sample.exe").getFile()); - for (int i = 0; i < facet.length; i++) { - ID3[i] = - CreateandReturnFacetID( - appUrl, serviceName, entityName, facet[i], entityID3, postData, file); - } + // if (!testStatus) { + // fail("There was an error during the rename test process."); + // } + // } - Boolean[] Updated1 = new Boolean[3]; - Boolean[] Updated2 = new Boolean[3]; - Boolean[] Updated3 = new Boolean[3]; + // @Test + // @Order(9) + // void testCreateEntitiesWithUnsupportedCharacter() throws IOException { + // System.out.println("Test (9): Create attachments with unsupported characters"); + // boolean testStatus = false; - String name1 = "sample1234.pdf"; - String dropdownValue = - integrationTestUtils.getDropDownValue(); // returns a plain string like "option-123" - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - Integer secondaryPropertyInt1 = 1234; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - String invalidPropertyPDF = "testidinvalidPDF"; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + // Map postData = new HashMap<>(); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (!"Entity in draft mode".equals(response)) { + // fail("Entity not in draft mode: " + response); + // return; + // } - // Update PDF properties - System.out.println("Renaming and updating secondary properties for PDF"); - for (int i = 0; i < facet.length; i++) { - String renameResp = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - "{ \"customProperty2\" : " + secondaryPropertyInt1 + " }"); - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - "{ \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\" }"); - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), "{ \"customProperty6\" : true }"); - - String upd1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - String upd2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - String upd3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - String upd4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - String updInvalid = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], invalidPropertyPDF); - - if ("Renamed".equals(renameResp) - && "Updated".equals(upd1) - && "Updated".equals(upd2) - && "Updated".equals(upd3) - && "Updated".equals(upd4) - && "Updated".equals(updInvalid)) { - Updated1[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); - } - } + // for (int i = 0; i < facet.length; i++) { + // postData.put("up__ID", entityID); + // List createResponse = + // api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, + // tempFile); - // Update TXT properties - System.out.println("Renaming and updating secondary properties for TXT"); - for (int i = 0; i < facet.length; i++) { - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), "{ \"customProperty6\" : true }"); - String upd = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], bodyBool); - if ("Updated".equals(upd)) { - Updated2[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); - } - } + // String check = createResponse.get(0); + // if (!"Attachment created".equals(check)) { + // System.out.println("Failed to create attachment for facet: " + facet[i]); + // continue; + // } - // Update EXE properties - System.out.println("Renaming and updating secondary properties for EXE"); - String dropdownValueExe = integrationTestUtils.getDropDownValue(); - String jsonDropdownExe = "{ \"customProperty1_code\" : \"" + dropdownValueExe + "\" }"; + // String restrictedName = "a/\\bc.pdf"; + // response = + // api.renameAttachment(appUrl, entityName, facet[i], entityID, ID4[i], restrictedName); + // } - for (int i = 0; i < facet.length; i++) { - RequestBody bodyDropdownExe = - RequestBody.create(MediaType.parse("application/json"), jsonDropdownExe); - RequestBody bodyIntExe = - RequestBody.create( - MediaType.parse("application/json"), "{ \"customProperty2\" : 1234 }"); - - String upd1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdownExe); - String upd2 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID3[i], bodyIntExe); - - if ("Updated".equals(upd1) && "Updated".equals(upd2)) { - Updated3[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); - } - } + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"a/\\bc.pdf\\\" + // contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: + // attachments\\nPage: + // IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // if (response.equals(expected)) { + // api.deleteEntityDraft(appUrl, entityName, entityID); + // testStatus = true; + // } - if (Arrays.stream(Updated1).allMatch(Boolean.TRUE::equals) - && Arrays.stream(Updated2).allMatch(Boolean.TRUE::equals) - && Arrays.stream(Updated3).allMatch(Boolean.TRUE::equals)) { + // if (!testStatus) { + // fail("Facets renamed with restricted characters were not correctly rejected."); + // } + // } - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - String[] expectedNames = {"sample.pdf", "sample.txt", "sample.exe"}; + // @Test + // @Order(10) + // void testRenameEntitiesWithUnsupportedCharacter() { + // System.out.println("Test (10) : Rename attachments with unsupported characters"); + // Boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String[] name = {"sample/1234", "reference1/234", "footnote1/234"}; + // if (response.equals("Entity in draft mode")) { + // for (int i = 0; i < facet.length; i++) { + // response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name[i]); + // if (response.equals("Renamed")) counter++; + // } + // if (counter >= 2) { + // counter = -1; // Reset counter for the next check + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"reference1/234\\\" contains + // unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"sample/1234\\\" + // contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: + // attachments\\nPage: + // IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"footnote1/234\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // if (response.equals(expected)) { + // for (int i = 0; i < facet.length; i++) { + // response = + // api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], + // "sample.pdf"); + // } + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment was renamed with unsupported characters"); + // } + // } - // Verify PDF metadata - for (int i = 0; i < facet.length; i++) { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); - assertEquals(expectedNames[0], metadata.get("fileName")); - assertNull(metadata.get("customProperty3")); - assertNull(metadata.get("customProperty4")); - assertNull(metadata.get("customProperty1_code")); - assertNull(metadata.get("customProperty2")); - assertNull(metadata.get("customProperty6")); - assertNull(metadata.get("customProperty5")); - } + // @Test + // @Order(11) + // void testRenameMultipleEntityComponents() { + // System.out.println("Test (11) : Rename multiple attachments, references, and footnotes"); + // boolean testStatus = true; + + // String draftResponse = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (!"Entity in draft mode".equals(draftResponse)) { + // fail("Entity is not in draft mode."); + // return; + // } + // String[] name = {"sample1234", "reference1234", "footnote1234"}; + // String[] name2 = {"sample12345", "reference12345", "footnote12345"}; + // for (int i = 0; i < facet.length; i++) { + // // Read the facet to ensure it exists + // testStatus &= renameAndCheck(facet[i], ID2[i], entityID, name[i]); + // testStatus &= renameAndCheck(facet[i], ID3[i], entityID, name2[i]); + // } + // // Save the draft if all renames succeeded + // if (testStatus) { + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (!"Saved".equals(saveResponse)) { + // fail("Entity draft was not saved after renaming."); + // } + // } else { + // // Save draft even if renaming failed to preserve state + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // fail("One or more components were not renamed."); + // } + // } - // Verify TXT metadata - for (int i = 0; i < facet.length; i++) { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID2[i]); - assertEquals(expectedNames[1], metadata.get("fileName")); - assertNull(metadata.get("customProperty3")); - assertNull(metadata.get("customProperty4")); - assertNull(metadata.get("customProperty1_code")); - assertNull(metadata.get("customProperty2")); - assertTrue((Boolean) metadata.get("customProperty6")); - assertNull(metadata.get("customProperty5")); - } + // @Test + // @Order(12) + // void testRenameSingleDuplicate() { + // System.out.println("Test (12) : Rename duplicates for attachment, reference, and footnote"); + // Boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String[] name = {"sample1234", "reference1234", "footnote1234"}; + // String[] name2 = {"sample123456", "reference123456", "footnote123456"}; + // if (response.equals("Entity in draft mode")) { + // for (int i = 0; i < facet.length; i++) { + // response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name[i]); + // if (response.equals("Renamed")) counter++; + // } + // if (counter >= 2) { + // counter = -1; // Reset counter for the next check + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // String.format( + // "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"%s\\\" already + // exists. Rename the object and try again.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"An object named + // \\\"%s\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An + // object named \\\"%s\\\" already exists. Rename the object and try again.\\n\\nTable: + // footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}", + // name[1], name[0], name[2]); + // if (response.equals(expected)) { + // for (int i = 0; i < facet.length; i++) { + // // Attempt to rename again with a different name + // response = + // api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], name2[i]); + // if (response.equals("Renamed")) counter++; + // } + // } + // if (counter >= 2) { + // // If all renames were successful, save the draft + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } else { + // testStatus = false; + // fail("Attachment was renamed"); + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // } - // Verify EXE metadata - for (int i = 0; i < facet.length; i++) { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID3[i]); - assertEquals(expectedNames[2], metadata.get("fileName")); - assertNull(metadata.get("customProperty3")); - assertNull(metadata.get("customProperty4")); - assertEquals( - dropdownValueExe, - metadata.get("customProperty1_code")); // Adjust expected value if needed - assertEquals(1234, metadata.get("customProperty2")); - } + // @Test + // @Order(13) + // void testRenameMultipleEntitiesWithOneUnsupportedCharacter() { + // System.out.println( + // "Test (13) : Rename multiple files out of which one file name contains unsupported + // characters"); + // boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String[] names = {"summary_1234", "reference_4567", "note/invalid"}; + + // if (response.equals("Entity in draft mode")) { + // int successCount = 0; + // for (int i = 0; i < facet.length; i++) { + // response = api.renameAttachment(appUrl, entityName, facet[i], entityID, ID3[i], + // names[i]); + // if (response.equals("Renamed")) successCount++; + // } - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update unsuccessful for invalid properties and successful for valid attachments"); - } - } - } + // if (successCount >= 2) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"note/invalid\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: + // IntegrationTestEntity\"}}"; + // if (response.equals(expected)) { + // response = + // api.renameAttachment(appUrl, entityName, facet[2], entityID, ID3[2], "note_valid"); + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) testStatus = true; + // } + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } + // if (!testStatus) { + // fail("Attachment was renamed with unsupported characters"); + // } + // } - @Test - @Order(27) - void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (27): Rename & Update invalid and valid secondary properties for multiple attachments after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Entity in draft mode")) { - Boolean Updated1[] = new Boolean[3]; - Boolean Updated2[] = new Boolean[3]; - Boolean Updated3[] = new Boolean[3]; - String name1 = "sample.pdf"; - Integer secondaryPropertyInt1 = 12; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - String invalidPropertyPDF = "testidinvalidPDF"; - String dropdownValue = integrationTestUtils.getDropDownValue(); - System.out.println("drop down value is: " + dropdownValue); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - - // PDF - System.out.println("Renaming and updating secondary properties for PDF"); - for (int i = 0; i < facet.length; i++) { - String response1 = - api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); - // Update secondary properties for String - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); - // Update secondary properties for LocalDateTime - RequestBody bodyDate = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyDate); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyBool); - // Update invalid secondary property - String updateSecondaryPropertyResponse5 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID[i], invalidPropertyPDF); - - if (response1.equals("Renamed") - && updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponse2.equals("Updated") - && updateSecondaryPropertyResponse3.equals("Updated") - && updateSecondaryPropertyResponse4.equals("Updated") - && updateSecondaryPropertyResponse5.equals("Updated")) { - Updated1[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); - } - } - // TXT - System.out.println("Renaming and updating secondary properties for TXT"); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + false + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], bodyBool); - if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { - Updated2[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); - } - } + // @Test + // @Order(14) + // void testRenameToValidateNames() throws IOException { + // System.out.println("Test (14) : Rename attachments to validate names"); + // String[] generatedIDs = new String[3]; + // String[] duplicateIDs = new String[1]; + // boolean testStatus = false, allRenamedSuccessfully = true; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID3 = response; - Integer secondaryPropertyInt3 = 12; - // EXE - System.out.println("Renaming and updating secondary properties for EXE"); - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - for (int i = 0; i < facet.length; i++) { - // Update secondary properties for String - System.out.println("drop down value is: " + dropdownValue1); - String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown1); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], bodyInt); - - if (updateSecondaryPropertyResponse1.equals("Updated") - && updateSecondaryPropertyResponseEXE2.equals("Updated")) { - Updated3[i] = true; - System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); - } - } + // String[] invalidNames = {"Restricted/Character", " ", "duplicateName.pdf"}; + // String duplicateName = "duplicateName.pdf"; - if (Updated1[0] - && Updated1[1] - && Updated1[2] - && Updated2[0] - && Updated2[1] - && Updated2[2] - && Updated3[0] - && Updated3[1] - && Updated3[2]) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - String name[] = {"sample.pdf", "sample.txt", "sample.exe"}; - // for PDF - for (int i = 0; i < facet.length; i++) { - Map FacetMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); - assertEquals(name[0], FacetMetadata.get("fileName")); - assertNull(FacetMetadata.get("customProperty3")); - assertNull(FacetMetadata.get("customProperty4")); - assertNull(FacetMetadata.get("customProperty1_code")); - assertNull(FacetMetadata.get("customProperty2")); - assertNull(FacetMetadata.get("customProperty6")); - assertNull(FacetMetadata.get("customProperty5")); - } - // for TXT - for (int i = 0; i < facet.length; i++) { - Map FacetMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID2[i]); - assertEquals(name[1], FacetMetadata.get("fileName")); - assertNull(FacetMetadata.get("customProperty3")); - assertNull(FacetMetadata.get("customProperty4")); - assertNull(FacetMetadata.get("customProperty1_code")); - assertNull(FacetMetadata.get("customProperty2")); - assertFalse((Boolean) FacetMetadata.get("customProperty6")); - assertNull(FacetMetadata.get("customProperty5")); - } - // for EXE - for (int i = 0; i < facet.length; i++) { - Map FacetMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID3[i]); - assertEquals(name[2], FacetMetadata.get("fileName")); - assertNull(FacetMetadata.get("customProperty3")); - assertNull(FacetMetadata.get("customProperty4")); - assertEquals(dropdownValue1, FacetMetadata.get("customProperty1_code")); - assertEquals(12, FacetMetadata.get("customProperty2")); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update unsuccessfull for invalid Secondary properties and successfull for valid property attachments"); - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } + // // Creation of attachment, reference and footnote + // for (int i = 0; i < facet.length; i++) { + // File file = new File(classLoader.getResource("sample2.pdf").getFile()); + // generatedIDs[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // response = + // api.renameAttachment( + // appUrl, entityName, facet[i], entityID3, generatedIDs[i], invalidNames[i]); + // allRenamedSuccessfully &= "Renamed".equals(response); + // } + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // // Creating duplicate name for last facet + // duplicateIDs[0] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[2], entityID3, postData, file); + // String response2 = + // api.renameAttachment( + // appUrl, entityName, facet[2], entityID3, duplicateIDs[0], duplicateName); + + // if (allRenamedSuccessfully && "Renamed".equals(response2)) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"The object name cannot be empty or + // consist entirely of space characters. Enter a value.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"Restricted/Character\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"duplicateName.pdf\\\" already exists. Rename the object and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // if (response.equals(expected)) { + // response = api.deleteEntityDraft(appUrl, entityName, entityID3); + // if (response.equals("Entity Draft Deleted")) testStatus = true; + // } + // } + // if (!testStatus) fail("Could not create entity"); + // } else { + // fail("Could not create entity"); + // return; + // } + // } - @Test - @Order(28) - void testNAttachments_NewEntity() throws IOException { - System.out.println( - "Test (28): Creating new entity and checking only max 4 attachments are allowed to be uploaded"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID4 = response; + // @Test + // @Order(15) + // void testRenameEntitiesWithoutSDMRole() throws IOException { + // System.out.println("Test (15) : Rename attachments where user don't have SDM-Roles"); + // boolean testStatus = true; + // try { + // String apiResponse = apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if ("Entity in draft mode".equals(apiResponse)) { + // String[] name = {"sample456", "reference456", "footnote456"}; + // for (int i = 0; i < facet.length; i++) { + // apiResponse = + // apiNoRoles.renameAttachment(appUrl, entityName, facet[i], entityID, ID[i], + // name[i]); + // if (!"Renamed".equals(apiResponse)) { + // testStatus = false; + // } + // } + // if (testStatus) { + // apiResponse = apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "[{\"code\":\"\",\"message\":\"Could not update the following files. + // \\n\\n\\t\\u2022 reference123\\n\\nYou do not have the required permissions to update + // attachments. Kindly contact the admin\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"Could not + // update the following files. \\n\\n\\t\\u2022 sample123\\n\\nYou do not have the required + // permissions to update attachments. Kindly contact the admin\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"Could not + // update the following files. \\n\\n\\t\\u2022 footnote123\\n\\nYou do not have the required + // permissions to update attachments. Kindly contact the admin\\n\\nTable: footnotes\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (!apiResponse.equals(expected)) { + // testStatus = false; + // } + // } else { + // apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // } catch (Exception e) { + // testStatus = false; + // } + // if (!testStatus) { + // fail("Attachment got renamed without SDM roles."); + // } + // } - System.out.println("Entity created"); + // @Test + // @Order(16) + // void testDeleteSingleAttachment() throws IOException { + // System.out.println("Test (16) : Delete single attachment, reference, and footnote"); + // Boolean testStatus = false; + // counter = -1; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Entity in draft mode")) { + // for (int i = 0; i < facet.length; i++) { + // response = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID[i]); + // if (response.equals("Deleted")) counter++; + // } + // if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // counter = -1; // Reset counter for the next check + // if (response.equals("Saved")) { + // for (int i = 0; i < facet.length; i++) { + // response = api.readAttachment(appUrl, entityName, facet[i], entityID, ID[i]); + // if (response.equals("Could not read Attachment")) counter++; + // } + // if (counter >= 2) testStatus = true; + // else fail("Could not read deleted facets"); + // } else { + // fail("Could not save entity after deletion"); + // } + // } + // } - System.out.println("Creating attachment PDF"); - ClassLoader classLoader = getClass().getClassLoader(); + // @Test + // @Order(17) + // void testDeleteMultipleAttachmentsReferencesFootnotes() throws IOException { + // System.out.println("Test (17) : Delete multiple attachments, references, and footnotes"); + // Boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Entity in draft mode")) { + // for (int i = 0; i < facet.length; i++) { + // String response1 = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID2[i]); + // String response2 = api.deleteAttachment(appUrl, entityName, facet[i], entityID, ID3[i]); + // if (response1.equals("Deleted") && response2.equals("Deleted")) counter++; + // } + // } + // if (counter >= 2) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // if (response.equals("Saved")) { + // for (int i = 0; i < facet.length; i++) { + // String response1 = api.readAttachment(appUrl, entityName, facet[i], entityID, ID2[i]); + // String response2 = api.readAttachment(appUrl, entityName, facet[i], entityID, ID3[i]); + // if (response1.equals("Could not read " + facet[i]) + // && response2.equals("Could not read " + facet[i])) { + // counter++; + // } + // } + // if (counter >= 2) testStatus = true; + // else fail("Could not read deleted facets"); + // } else fail("Could not save entity after deletion"); + // } - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID4); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - List createResponse1 = - api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData1, file); - if (createResponse1.get(0).equals("Attachment created")) { - ID[0] = createResponse1.get(1); - System.out.println("Attachment created"); - } + // @Test + // @Order(18) + // void testUploadBlockedMimeType() throws IOException { + // System.out.println("Test (18) : Upload blocked mimeType .rtf"); + // Boolean testStatus = false; - System.out.println("Creating attachment TXT"); - file = new File(classLoader.getResource("sample.txt").getFile()); - Map postData2 = new HashMap<>(); - postData2.put("up__ID", entityID4); - postData2.put("mimeType", "application/txt"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - List createResponse2 = - api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData2, file); - if (createResponse2.get(0).equals("Attachment created")) { - ID2[0] = createResponse2.get(1); - System.out.println("Attachment created"); - } + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!"Could not create entity".equals(response)) { + // entityID2 = response; - System.out.println("Creating attachment EXE"); - file = new File(classLoader.getResource("sample.exe").getFile()); - Map postData3 = new HashMap<>(); - postData3.put("up__ID", entityID4); - postData3.put("mimeType", "application/exe"); - postData3.put("createdAt", new Date().toString()); - postData3.put("createdBy", "test@test.com"); - postData3.put("modifiedBy", "test@test.com"); - - List createResponse3 = - api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, file); - if (createResponse3.get(0).equals("Attachment created")) { - ID[0] = createResponse3.get(1); - System.out.println("Attachment created"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.rtf")).getFile()); - System.out.println("Creating second attachment pdf"); - file = new File(classLoader.getResource("sample1.pdf").getFile()); - Map postData4 = new HashMap<>(); - postData4.put("up__ID", entityID4); - postData4.put("mimeType", "application/pdf"); - postData4.put("createdAt", new Date().toString()); - postData4.put("createdBy", "test@test.com"); - postData4.put("modifiedBy", "test@test.com"); - - List createResponse4 = - api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, file); - if (createResponse4.get(0).equals("Attachment created")) { - ID4[0] = createResponse4.get(1); - System.out.println("Attachment created"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID2); + // postData.put("mimeType", "application/rtf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - System.out.println("Creating third attachment pdf"); - file = new File(classLoader.getResource("sample2.pdf").getFile()); - Map postData5 = new HashMap<>(); - postData5.put("up__ID", entityID4); - postData5.put("mimeType", "application/pdf"); - postData5.put("createdAt", new Date().toString()); - postData5.put("createdBy", "test@test.com"); - postData5.put("modifiedBy", "test@test.com"); - - List createResponse5 = - api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, file); - if (createResponse5.get(0).equals("Only 4 attachments allowed.")) { - testStatus = true; - ID5[0] = createResponse5.get(1); - System.out.println("Expected error received: Only 4 attachments allowed."); - } - String check = createResponse5.get(0); - if (check.equals("Attachment created")) { - testStatus = false; - } else { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID4); - if (response.equals("Saved")) { - String expectedJson = - "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 attachments.\"}}"; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode actualJsonNode = objectMapper.readTree(check); - JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); - if (expectedJsonNode.equals(actualJsonNode)) { - testStatus = true; - } - } - } - } - if (!testStatus) { - fail("Attachment was created"); - } - } + // boolean allBlocked = true; + // for (int i = 0; i < facet.length; i++) { + // List createResponse = + // api.createAttachment(appUrl, entityName, facet[i], entityID2, srvpath, postData, + // file); - @Test - @Order(29) - void testUploadNAttachments() throws IOException { - System.out.println("Test (29): Upload maximum 4 attachments in an exsisting entity"); + // String actualResponse = createResponse.get(0); + // String expectedJson = + // "{\"error\":{\"code\":\"500\",\"message\":\"This file type is not allowed in this + // repository. Contact your administrator for assistance.\"}}"; - ClassLoader classLoader = getClass().getClassLoader(); - File originalFile = new File(classLoader.getResource("sample.exe").getFile()); - - boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID4); - System.out.println("response: " + response); - - if ("Entity in draft mode".equals(response)) { - for (int i = 1; i <= 5; i++) { - // Ensure only one file is uploaded at a time and complete before next - File tempFile = File.createTempFile("sample_" + i + "_", ".exe"); - Files.copy(originalFile.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID4); - postData.put("mimeType", "application/exe"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - api.createAttachment( - appUrl, entityName, facet[0], entityID4, srvpath, postData, tempFile); - - String resultMessage = createResponse.get(0); - System.out.println("Result message for attachment " + i + ": " + resultMessage); - - String expectedResponse = - "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 attachments.\"}}"; - if (resultMessage.equals(expectedResponse)) { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode actualJsonNode = objectMapper.readTree(resultMessage); - JsonNode expectedJsonNode = objectMapper.readTree(expectedResponse); - if (expectedJsonNode.equals(actualJsonNode)) { - testStatus = true; - } - } else { - testStatus = false; - } - tempFile.delete(); - } - if (!testStatus) { - fail("5th attachment did not trigger the expected error."); - } - // Delete the newly created entity - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID4); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } else { - System.out.println("Successfully deleted the test entity4"); - } - } - } + // if (!expectedJson.equals(actualResponse)) { + // allBlocked = false; + // System.out.println( + // "Facet " + facet[i] + " incorrectly accepted blocked mimeType: " + actualResponse); + // } + // } - @Test - @Order(30) - void testDiscardDraftWithoutAttachments() { - System.out.println("Test (30) : Discard draft without adding attachments"); - Boolean testStatus = false; + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + // if ("Saved".equals(response) && allBlocked) { + // testStatus = true; + // } + // } - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID6 = response; - response = api.deleteEntityDraft(appUrl, entityName, entityID6); - if (response.equals("Entity Draft Deleted")) { - testStatus = true; - } - } - if (!testStatus) { - fail("Draft was not discarded properly"); - } - } + // if (!testStatus) { + // fail("Attachment got uploaded with blocked .rtf MIME type"); + // } + // } - @Test - @Order(31) - void testDiscardDraftWithAttachments() throws IOException { - System.out.println("Test (31): Discard draft with attachments, references, and footnotes"); - boolean testStatus = false; + // @Test + // @Order(19) + // void testDeleteEntity() { + // System.out.println("Test (19) : Delete entity"); + // Boolean testStatus = false; + // String response = api.deleteEntity(appUrl, entityName, entityID); + // String response2 = api.deleteEntity(appUrl, entityName, entityID2); + // if (response.equals("Entity Deleted") && response2.equals("Entity Deleted")) testStatus = + // true; + // if (!testStatus) fail("Could not delete entity"); + // } - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!"Could not create entity".equals(response)) { - entityID6 = response; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + // @Test + // @Order(20) + // void testUpdateValidSecondaryProperty_beforeEntityIsSaved_single() throws IOException { + // System.out.println("Test (20) : Rename & Update secondary property before entity is saved"); + // System.out.println("Creating entity"); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID6); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - for (int i = 0; i < facet.length; i++) { - List createResponse = - api.createAttachment(appUrl, entityName, facet[i], entityID6, srvpath, postData, file); - if ("Attachment created".equals(createResponse.get(0))) { - System.out.println("Attachment created in facet: " + facet[i]); - } else { - System.out.println("Attachment creation failed in facet: " + facet[i]); - } - } - response = api.deleteEntityDraft(appUrl, entityName, entityID6); - if ("Entity Draft Deleted".equals(response)) { - testStatus = true; - } - } - if (!testStatus) { - fail("Draft with attachments was not discarded properly"); - } - } + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - @Test - @Order(32) - void testDraftUpdateUploadTwoDeleteOneAndCreate() throws IOException { - System.out.println("Test (32): Upload to all facets, delete one, and create entity"); + // if (!response.equals("Could not create entity")) { + // entityID3 = response; - boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // System.out.println("Creating attachment, reference, and footnote"); - if (!"Could not create entity".equals(response)) { - entityID5 = response; - ClassLoader classLoader = getClass().getClassLoader(); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); - File file1 = - new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - File file2 = - new File(Objects.requireNonNull(classLoader.getResource("sample.txt")).getFile()); - - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID5); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - Map postData2 = new HashMap<>(postData1); - postData2.put("up__ID", entityID5); - postData2.put("mimeType", "text/plain"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - boolean allCreated = true; - for (int i = 0; i < facet.length; i++) { - List response1 = - api.createAttachment( - appUrl, entityName, facet[i], entityID5, srvpath, postData1, file1); - List response2 = - api.createAttachment( - appUrl, entityName, facet[i], entityID5, srvpath, postData2, file2); - - if (response1.get(0).equals("Attachment created") - && response2.get(0).equals("Attachment created")) { - ID4[i] = response1.get(1); // to keep one - ID5[i] = response2.get(1); // will delete this one - } else { - allCreated = false; - break; - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String deleteResponse = - api.deleteAttachment(appUrl, entityName, facet[i], entityID5, ID5[i]); - if (!"Deleted".equals(deleteResponse)) { - allCreated = false; - break; - } - } + // for (int i = 0; i < facet.length; i++) { + // ID[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - if (allCreated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); - if ("Saved".equals(response)) { - testStatus = true; - } - } - } + // System.out.println("Attachments, References, and Footnotes created"); + + // // Use valid dropdown value for customProperty1 + // Integer secondaryPropertyInt = 1234; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + + // String[] name = {"sample1234.pdf", "reference1234.pdf", "footnote1234.pdf"}; + + // for (int i = 0; i < facet.length; i++) { + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name[i]); + + // // Update customProperty1 (String - dropdown value) + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + + // // Update customProperty2 (Integer) + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + + // // Update customProperty5 (DateTime) + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + + // // Update customProperty6 (Boolean) + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) { + // counter++; + // } + // } - if (!testStatus) { - fail("Failed to upload multiple facet entries, delete one per facet and create entity"); - } - } + // if (counter >= 2) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // } + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } - @Test - @Order(33) - void testUpdateEntityDraft() throws IOException { - System.out.println("Test (33): Update entity draft with new facet content"); - boolean testStatus = false; + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + // @Test + // @Order(21) + // void testUpdateValidSecondaryProperty_afterEntityIsSaved_single() { + // System.out.println("Test (21): Rename & Update secondary property after entity is saved"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // System.out.println("Editing entity"); + + // if (response.equals("Entity in draft mode")) { + // // Sample secondary properties + // String name[] = {"sample.pdf", "reference_sample.pdf", "footnote_sample.pdf"}; + // Integer secondaryPropertyInt = 42; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + + // System.out.println("Renaming and updating secondary properties for attachment"); + // for (int i = 0; i < facet.length; i++) { + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name[i]); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) counter++; + // } + // if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachment"); + // } + // // Clean up + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (!deleteEntityResponse.equals("Entity Deleted")) fail("Could not delete entity"); + // } + // if (!testStatus) fail("Could not update secondary properties after entity is saved"); + // } - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + // @Test + // @Order(22) + // void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_single() throws IOException { + // System.out.println( + // "Test (22): Rename & Update invalid secondary property before entity is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID3 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID5); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID5); - if ("Entity in draft mode".equals(response)) { - boolean allCreated = true; + // for (int i = 0; i < facet.length; i++) { + // ID[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } + // // Prepare test data + // String name1 = "sample1234.pdf"; + // Integer secondaryPropertyInt = 1234; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // String invalidProperty = "testid"; + + // for (int i = 0; i < facet.length; i++) { + // // Rename and update secondary properties + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for invalid ID + // String updateSecondaryPropertyResponse4 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], invalidProperty); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) counter++; + // } + // if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // for (int i = 0; i < facet.length; i++) { + // Map FacetMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); + // assertEquals("sample.pdf", FacetMetadata.get("fileName")); + // assertNull(FacetMetadata.get("customProperty3")); + // assertNull(FacetMetadata.get("customProperty4")); + // assertNull(FacetMetadata.get("customProperty1_code")); + // assertNull(FacetMetadata.get("customProperty2")); + // assertNull(FacetMetadata.get("customProperty6")); + // assertNull(FacetMetadata.get("customProperty5")); + // } + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Rename & update secondary properties for attachment is + // unsuccessfull"); + // } + // } + // if (!testStatus) + // fail( + // "Could not update secondary property before entity is saved for attachment, reference, + // or footnote"); + // } - for (int i = 0; i < facet.length; i++) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], entityID5, srvpath, postData, tempFile); - if (!"Attachment created".equals(createResponse.get(0))) { - allCreated = false; - } - } + // @Test + // @Order(23) + // void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_single() throws IOException { + // System.out.println( + // "Test (23): Rename & Update invalid secondary property after entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Entity in draft mode")) { + // String name1 = "sample.pdf"; + // Integer secondaryPropertyInt = 12; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // String invalidProperty = "testidinvalid"; + + // for (int i = 0; i < facet.length; i++) { + // // Rename and update secondary properties + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + // // Update secondary properties for Drop down + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for invalid ID + // String updateSecondaryPropertyResponse4 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], invalidProperty); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) counter++; + // } + // if (counter >= 2) response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // for (int i = 0; i < facet.length; i++) { + // Map FacetMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); + // assertEquals("sample.pdf", FacetMetadata.get("fileName")); + // assertNull(FacetMetadata.get("customProperty3")); + // assertNull(FacetMetadata.get("customProperty4")); + // assertNull(FacetMetadata.get("customProperty1_code")); + // assertNull(FacetMetadata.get("customProperty2")); + // assertNull(FacetMetadata.get("customProperty6")); + // assertNull(FacetMetadata.get("customProperty5")); + // } + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update secondary properties for attachment, reference, footnote is + // unsuccessfull"); + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (!deleteEntityResponse.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } + // if (!testStatus) + // fail( + // "Could not update secondary property after entity is saved for attachment, reference, + // or footnote"); + // } - if (allCreated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); - if ("Saved".equals(response)) { - testStatus = true; - } - } - } - api.deleteEntity(appUrl, entityName, entityID5); - if (!testStatus) { - fail("Failed to update draft with new attachments for all facets"); - } - } + // @Test + // @Order(24) + // void testUpdateValidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (24): Rename & Update valid secondary properties for multiple facets before entity + // is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID3 = response; - @Test - @Order(34) - void testUploadAttachmentWithoutSDMRole() throws IOException { - System.out.println("Test (34): Upload attachment across facets without SDM role"); - boolean testStatus = true; - - String response = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID7 = response; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + // System.out.println("Entity created"); + // ClassLoader classLoader = getClass().getClassLoader(); - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // System.out.println("Creating attachment, reference, and footnote PDF"); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // for (int i = 0; i < facet.length; i++) { + // ID[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - for (int i = 0; i < facet.length; i++) { - List createResponse = - apiNoRoles.createAttachment( - appUrl, entityName, facet[i], entityID7, srvpath, postData, tempFile); - String check = createResponse.get(0); - String expectedError = - "{\"error\":{\"code\":\"500\",\"message\":\"You do not have the required permissions to upload attachments. Please contact your administrator for access.\"}}"; - if (!expectedError.equals(check)) { - testStatus = false; - } - } - } - api.deleteEntityDraft(appUrl, entityName, entityID7); - if (!testStatus) { - fail("Attachment uploaded without SDM role for one or more facets"); - } - } + // System.out.println("Creating attachment, reference, and footnote TXT"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // postData.put("mimeType", "application/txt"); + // for (int i = 0; i < facet.length; i++) { + // ID2[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - @Test - @Order(35) - void testCopyAttachmentsSuccessNewEntity() throws IOException { - System.out.println("Test (35): Copy attachments from one entity to another new entity"); - List> attachments = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - attachments.add(new ArrayList<>()); - } - copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!copyAttachmentSourceEntity.equals("Could not create entity") - && !copyAttachmentTargetEntity.equals("Could not create entity")) { - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample1.pdf").getFile())); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // System.out.println("Creating attachment, reference, and footnote EXE"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // postData.put("mimeType", "application/exe"); + // for (int i = 0; i < facet.length; i++) { + // ID3[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } + // Boolean Updated1[] = new Boolean[3]; + // Boolean Updated2[] = new Boolean[3]; + // Boolean Updated3[] = new Boolean[3]; + // String name1 = "sample1234.pdf"; + // Integer secondaryPropertyInt1 = 1234; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // // PDF + // System.out.println("Renaming and updating secondary properties for PDF"); + // for (int i = 0; i < facet.length; i++) { + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) { + // Updated1[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); + // } + // } - for (int i = 0; i < facet.length; i++) { - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, - entityName, - facet[i], - copyAttachmentSourceEntity, - srvpath, - postData, - file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.get(i).add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } - } - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (int i = 0; i < attachments.size(); i++) { - for (String attachment : attachments.get(i)) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadataDraft( - appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } - } - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - - if (sourceObjectIds.size() == 6) { - String copyResponse; - int i = 0; - for (String facetName : facet) { - if (i != 0) { - String editResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } - } - copyResponse = - api.copyAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size()))); - i += 2; - if (copyResponse.equals("Attachments copied successfully")) { - // Fetch copied attachment IDs from target draft - List> copiedMetadataResponse = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyAttachmentTargetEntity); - List copiedAttachmentIds = - copiedMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadata( - appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not create entities"); - } - } + // // TXT + // System.out.println("Renaming and updating secondary properties for TXT"); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], + // bodyBool); + // if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { + // Updated2[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); + // } + // } - @Test - @Order(36) - void testCopyAttachmentsUnsuccessfulNewEntity() throws IOException { - System.out.println( - "Test (36): Copy incorrect attachments from one entity to another new entity"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - copyAttachmentTargetEntityEmpty = - api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (editResponse1.equals("Entity in draft mode") - && !copyAttachmentTargetEntityEmpty.equals("Could not create entity")) { - if (sourceObjectIds.size() == 6) { - int i = 0; - for (String facet : facet) { - try { - List currentFacetObjectIds = - sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); - currentFacetObjectIds.add("incorrectObjectId"); - if (currentFacetObjectIds.size() != 3) { - fail("Not enough object IDs to copy attachments for facet: " + facet); - } - api.copyAttachment( - appUrl, entityName, facet, copyAttachmentTargetEntityEmpty, currentFacetObjectIds); - fail("Copy attachments did not throw an error"); - } catch (IOException e) { - i += 2; - } - } - String saveEntityResponse1 = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String saveEntityResponse2 = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntityEmpty); - String deleteResponse = - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntityEmpty); - if (!saveEntityResponse1.equals("Saved") - || !saveEntityResponse2.equals("Saved") - || !deleteResponse.equals("Entity Deleted")) { - fail("Could not save entities"); - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // // EXE + // System.out.println("Renaming and updating secondary properties for EXE"); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], + // bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponseEXE3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], + // bodyDate); + + // if (updateSecondaryPropertyResponseEXE1.equals("Updated") + // && updateSecondaryPropertyResponseEXE2.equals("Updated") + // && updateSecondaryPropertyResponseEXE3.equals("Updated")) { + // Updated3[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); + // } + // } + // if (Updated1[0] + // && Updated1[1] + // && Updated1[2] + // && Updated2[0] + // && Updated2[1] + // && Updated2[2] + // && Updated3[0] + // && Updated3[1] + // && Updated3[2]) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties"); + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - @Test - @Order(37) - void testCopyAttachmentWithNotesField() throws IOException { - System.out.println( - "Test (37): Create entity with attachments containing notes in multiple facets, copy to new entity and verify notes field"); - Boolean testStatus = false; + // @Test + // @Order(25) + // void testUpdateValidSecondaryProperty_afterEntityIsSaved_multipleAttachments() { + // System.out.println( + // "Test (25): Rename & Update valid secondary properties for multiple facets after entity + // is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Entity in draft mode")) { + // Boolean Updated1[] = new Boolean[3]; + // Boolean Updated2[] = new Boolean[3]; + // Boolean Updated3[] = new Boolean[3]; + + // String name1 = "sample1.pdf"; + // Integer secondaryPropertyInt1 = 12; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // System.out.println("Renaming and updating secondary properties for PDF"); + // for (int i = 0; i < facet.length; i++) { + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + // // Update secondary properties for Drop down + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated")) { + // Updated1[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); + // } + // } - copyCustomSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyCustomSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // TXT + // System.out.println("Renaming and updating secondary properties for TXT"); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], + // bodyBool); + // if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { + // Updated2[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); + // } + // } - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - String notesValue = "This is a test note for copy attachment verification"; - MediaType mediaType = MediaType.parse("application/json"); + // // EXE + // System.out.println("Renaming and updating secondary properties for EXE"); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for Drop down + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], + // bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponseEXE3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], + // bodyDate); + + // if (updateSecondaryPropertyResponseEXE1.equals("Updated") + // && updateSecondaryPropertyResponseEXE2.equals("Updated") + // && updateSecondaryPropertyResponseEXE3.equals("Updated")) { + // Updated3[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); + // } + // } - for (String facetName : facet) { - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // if (Updated1[0] + // && Updated1[1] + // && Updated1[2] + // && Updated2[0] + // && Updated2[1] + // && Updated2[2] + // && Updated3[0] + // && Updated3[1] + // && Updated3[2]) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachments"); + // } + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property after entity is saved"); + // } + // } - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // @Test + // @Order(26) + // void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (26): Rename & Update invalid and valid secondary properties for multiple facets + // before entity is saved"); + // System.out.println("Creating entity"); - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment in facet: " + facetName); - } + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - String sourceAttachmentId = createResponse.get(1); + // if (!"Could not create entity".equals(response)) { + // entityID3 = response; + // System.out.println("Entity created"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateBody = RequestBody.create(jsonPayload, mediaType); + // ClassLoader classLoader = getClass().getClassLoader(); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String updateResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - copyCustomSourceEntity, - sourceAttachmentId, - updateBody); + // // Create PDF attachments + // postData.put("mimeType", "application/pdf"); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // for (int i = 0; i < facet.length; i++) { + // ID[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - if (!updateResponse.equals("Updated")) { - fail("Could not update attachment notes field in facet: " + facetName); - } - } + // // Create TXT attachments + // postData.put("mimeType", "application/txt"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // for (int i = 0; i < facet.length; i++) { + // ID2[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - List objectIdsToStore = new ArrayList<>(); - for (String facetName : facet) { - List> sourceAttachmentsMetadata = - api.fetchEntityMetadataDraft(appUrl, entityName, facetName, copyCustomSourceEntity); + // // Create EXE attachments + // postData.put("mimeType", "application/exe"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // for (int i = 0; i < facet.length; i++) { + // ID3[i] = + // CreateandReturnFacetID( + // appUrl, serviceName, entityName, facet[i], entityID3, postData, file); + // } - if (sourceAttachmentsMetadata.isEmpty()) { - fail("No attachments found in source entity for facet: " + facetName); - } + // Boolean[] Updated1 = new Boolean[3]; + // Boolean[] Updated2 = new Boolean[3]; + // Boolean[] Updated3 = new Boolean[3]; + + // String name1 = "sample1234.pdf"; + // String dropdownValue = + // integrationTestUtils.getDropDownValue(); // returns a plain string like "option-123" + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // Integer secondaryPropertyInt1 = 1234; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // String invalidPropertyPDF = "testidinvalidPDF"; + + // // Update PDF properties + // System.out.println("Renaming and updating secondary properties for PDF"); + // for (int i = 0; i < facet.length; i++) { + // String renameResp = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // "{ \"customProperty2\" : " + secondaryPropertyInt1 + " }"); + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // "{ \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\" }"); + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), "{ \"customProperty6\" : true }"); + + // String upd1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // String upd2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // String upd3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // String upd4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + // String updInvalid = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], invalidPropertyPDF); + + // if ("Renamed".equals(renameResp) + // && "Updated".equals(upd1) + // && "Updated".equals(upd2) + // && "Updated".equals(upd3) + // && "Updated".equals(upd4) + // && "Updated".equals(updInvalid)) { + // Updated1[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); + // } + // } - Map sourceAttachmentMetadata = sourceAttachmentsMetadata.get(0); + // // Update TXT properties + // System.out.println("Renaming and updating secondary properties for TXT"); + // for (int i = 0; i < facet.length; i++) { + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), "{ \"customProperty6\" : true }"); + // String upd = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], + // bodyBool); + // if ("Updated".equals(upd)) { + // Updated2[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); + // } + // } - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId for facet: " + facetName); - } + // // Update EXE properties + // System.out.println("Renaming and updating secondary properties for EXE"); + // String dropdownValueExe = integrationTestUtils.getDropDownValue(); + // String jsonDropdownExe = "{ \"customProperty1_code\" : \"" + dropdownValueExe + "\" }"; + + // for (int i = 0; i < facet.length; i++) { + // RequestBody bodyDropdownExe = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdownExe); + // RequestBody bodyIntExe = + // RequestBody.create( + // MediaType.parse("application/json"), "{ \"customProperty2\" : 1234 }"); + + // String upd1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdownExe); + // String upd2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID3[i], bodyIntExe); + + // if ("Updated".equals(upd1) && "Updated".equals(upd2)) { + // Updated3[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); + // } + // } - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - objectIdsToStore.add(sourceObjectId); + // if (Arrays.stream(Updated1).allMatch(Boolean.TRUE::equals) + // && Arrays.stream(Updated2).allMatch(Boolean.TRUE::equals) + // && Arrays.stream(Updated3).allMatch(Boolean.TRUE::equals)) { + + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // String[] expectedNames = {"sample.pdf", "sample.txt", "sample.exe"}; + + // // Verify PDF metadata + // for (int i = 0; i < facet.length; i++) { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); + // assertEquals(expectedNames[0], metadata.get("fileName")); + // assertNull(metadata.get("customProperty3")); + // assertNull(metadata.get("customProperty4")); + // assertNull(metadata.get("customProperty1_code")); + // assertNull(metadata.get("customProperty2")); + // assertNull(metadata.get("customProperty6")); + // assertNull(metadata.get("customProperty5")); + // } - String sourceNoteValue = - sourceAttachmentMetadata.get("note") != null - ? sourceAttachmentMetadata.get("note").toString() - : null; + // // Verify TXT metadata + // for (int i = 0; i < facet.length; i++) { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID2[i]); + // assertEquals(expectedNames[1], metadata.get("fileName")); + // assertNull(metadata.get("customProperty3")); + // assertNull(metadata.get("customProperty4")); + // assertNull(metadata.get("customProperty1_code")); + // assertNull(metadata.get("customProperty2")); + // assertTrue((Boolean) metadata.get("customProperty6")); + // assertNull(metadata.get("customProperty5")); + // } - if (!notesValue.equals(sourceNoteValue)) { - fail( - "Notes field was not properly set in source attachment for facet " - + facetName - + ". Expected: " - + notesValue - + ", Got: " - + sourceNoteValue); - } - } + // // Verify EXE metadata + // for (int i = 0; i < facet.length; i++) { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID3[i]); + // assertEquals(expectedNames[2], metadata.get("fileName")); + // assertNull(metadata.get("customProperty3")); + // assertNull(metadata.get("customProperty4")); + // assertEquals( + // dropdownValueExe, + // metadata.get("customProperty1_code")); // Adjust expected value if needed + // assertEquals(1234, metadata.get("customProperty2")); + // } - int startIndex = sourceObjectIds.size(); - sourceObjectIds.addAll(objectIdsToStore); + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update unsuccessful for invalid properties and successful for valid + // attachments"); + // } + // } + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity"); - } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - copyCustomTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyCustomTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // @Test + // @Order(27) + // void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (27): Rename & Update invalid and valid secondary properties for multiple + // attachments after entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Entity in draft mode")) { + // Boolean Updated1[] = new Boolean[3]; + // Boolean Updated2[] = new Boolean[3]; + // Boolean Updated3[] = new Boolean[3]; + // String name1 = "sample.pdf"; + // Integer secondaryPropertyInt1 = 12; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // String invalidPropertyPDF = "testidinvalidPDF"; + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // System.out.println("drop down value is: " + dropdownValue); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + + // // PDF + // System.out.println("Renaming and updating secondary properties for PDF"); + // for (int i = 0; i < facet.length; i++) { + // String response1 = + // api.renameAttachment(appUrl, entityName, facet[i], entityID3, ID[i], name1); + // // Update secondary properties for String + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], bodyInt); + // // Update secondary properties for LocalDateTime + // RequestBody bodyDate = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyDate); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID[i], + // bodyBool); + // // Update invalid secondary property + // String updateSecondaryPropertyResponse5 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID[i], invalidPropertyPDF); + + // if (response1.equals("Renamed") + // && updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponse2.equals("Updated") + // && updateSecondaryPropertyResponse3.equals("Updated") + // && updateSecondaryPropertyResponse4.equals("Updated") + // && updateSecondaryPropertyResponse5.equals("Updated")) { + // Updated1[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " PDF"); + // } + // } + // // TXT + // System.out.println("Renaming and updating secondary properties for TXT"); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + false + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID2[i], + // bodyBool); + // if (updateSecondaryPropertyResponseTXT1.equals("Updated")) { + // Updated2[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " TXT"); + // } + // } - int facetIndex = 0; - for (String facetName : facet) { - if (facetIndex > 0) { - String editResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } - } + // Integer secondaryPropertyInt3 = 12; + // // EXE + // System.out.println("Renaming and updating secondary properties for EXE"); + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // for (int i = 0; i < facet.length; i++) { + // // Update secondary properties for String + // System.out.println("drop down value is: " + dropdownValue1); + // String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], entityID3, ID3[i], bodyDropdown1); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty(appUrl, entityName, facet[i], entityID3, ID3[i], + // bodyInt); + + // if (updateSecondaryPropertyResponse1.equals("Updated") + // && updateSecondaryPropertyResponseEXE2.equals("Updated")) { + // Updated3[i] = true; + // System.out.println("Renamed & updated Secondary properties for " + facet[i] + " EXE"); + // } + // } - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); + // if (Updated1[0] + // && Updated1[1] + // && Updated1[2] + // && Updated2[0] + // && Updated2[1] + // && Updated2[2] + // && Updated3[0] + // && Updated3[1] + // && Updated3[2]) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // String name[] = {"sample.pdf", "sample.txt", "sample.exe"}; + // // for PDF + // for (int i = 0; i < facet.length; i++) { + // Map FacetMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID[i]); + // assertEquals(name[0], FacetMetadata.get("fileName")); + // assertNull(FacetMetadata.get("customProperty3")); + // assertNull(FacetMetadata.get("customProperty4")); + // assertNull(FacetMetadata.get("customProperty1_code")); + // assertNull(FacetMetadata.get("customProperty2")); + // assertNull(FacetMetadata.get("customProperty6")); + // assertNull(FacetMetadata.get("customProperty5")); + // } + // // for TXT + // for (int i = 0; i < facet.length; i++) { + // Map FacetMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID2[i]); + // assertEquals(name[1], FacetMetadata.get("fileName")); + // assertNull(FacetMetadata.get("customProperty3")); + // assertNull(FacetMetadata.get("customProperty4")); + // assertNull(FacetMetadata.get("customProperty1_code")); + // assertNull(FacetMetadata.get("customProperty2")); + // assertFalse((Boolean) FacetMetadata.get("customProperty6")); + // assertNull(FacetMetadata.get("customProperty5")); + // } + // // for EXE + // for (int i = 0; i < facet.length; i++) { + // Map FacetMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], entityID3, ID3[i]); + // assertEquals(name[2], FacetMetadata.get("fileName")); + // assertNull(FacetMetadata.get("customProperty3")); + // assertNull(FacetMetadata.get("customProperty4")); + // assertEquals(dropdownValue1, FacetMetadata.get("customProperty1_code")); + // assertEquals(12, FacetMetadata.get("customProperty2")); + // } - String copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"numericSeverity\":3},{\"code\":\"\",\"message\":\"The following + // secondary properties are not supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update unsuccessfull for invalid Secondary properties and successfull for + // valid property attachments"); + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity for facet: " + facetName); - } + // @Test + // @Order(28) + // void testNAttachments_NewEntity() throws IOException { + // System.out.println( + // "Test (28): Creating new entity and checking only max 4 attachments are allowed to be + // uploaded"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID4 = response; - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity for facet: " + facetName); - } + // System.out.println("Entity created"); - facetIndex++; - } + // System.out.println("Creating attachment PDF"); + // ClassLoader classLoader = getClass().getClassLoader(); - for (String facetName : facet) { - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID4); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); - if (targetAttachmentsMetadata.isEmpty()) { - fail("No attachments found in target entity for facet: " + facetName); - } + // List createResponse1 = + // api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData1, + // file); + // if (createResponse1.get(0).equals("Attachment created")) { + // ID[0] = createResponse1.get(1); + // System.out.println("Attachment created"); + // } - Map copiedAttachmentMetadata = targetAttachmentsMetadata.get(0); - String copiedNoteValue = - copiedAttachmentMetadata.get("note") != null - ? copiedAttachmentMetadata.get("note").toString() - : null; + // System.out.println("Creating attachment TXT"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // Map postData2 = new HashMap<>(); + // postData2.put("up__ID", entityID4); + // postData2.put("mimeType", "application/txt"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // List createResponse2 = + // api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData2, + // file); + // if (createResponse2.get(0).equals("Attachment created")) { + // ID2[0] = createResponse2.get(1); + // System.out.println("Attachment created"); + // } - if (!notesValue.equals(copiedNoteValue)) { - fail( - "Notes field was not properly copied for facet " - + facetName - + ". Expected: " - + notesValue - + ", Got: " - + copiedNoteValue); - } + // System.out.println("Creating attachment EXE"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // Map postData3 = new HashMap<>(); + // postData3.put("up__ID", entityID4); + // postData3.put("mimeType", "application/exe"); + // postData3.put("createdAt", new Date().toString()); + // postData3.put("createdBy", "test@test.com"); + // postData3.put("modifiedBy", "test@test.com"); + + // List createResponse3 = + // api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, + // file); + // if (createResponse3.get(0).equals("Attachment created")) { + // ID[0] = createResponse3.get(1); + // System.out.println("Attachment created"); + // } - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // System.out.println("Creating second attachment pdf"); + // file = new File(classLoader.getResource("sample1.pdf").getFile()); + // Map postData4 = new HashMap<>(); + // postData4.put("up__ID", entityID4); + // postData4.put("mimeType", "application/pdf"); + // postData4.put("createdAt", new Date().toString()); + // postData4.put("createdBy", "test@test.com"); + // postData4.put("modifiedBy", "test@test.com"); + + // List createResponse4 = + // api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, + // file); + // if (createResponse4.get(0).equals("Attachment created")) { + // ID4[0] = createResponse4.get(1); + // System.out.println("Attachment created"); + // } - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment from target entity for facet: " + facetName); - } else { - testStatus = true; - } - } + // System.out.println("Creating third attachment pdf"); + // file = new File(classLoader.getResource("sample2.pdf").getFile()); + // Map postData5 = new HashMap<>(); + // postData5.put("up__ID", entityID4); + // postData5.put("mimeType", "application/pdf"); + // postData5.put("createdAt", new Date().toString()); + // postData5.put("createdBy", "test@test.com"); + // postData5.put("modifiedBy", "test@test.com"); + + // List createResponse5 = + // api.createAttachment(appUrl, entityName, facet[0], entityID4, srvpath, postData3, + // file); + // if (createResponse5.get(0).equals("Only 4 attachments allowed.")) { + // testStatus = true; + // ID5[0] = createResponse5.get(1); + // System.out.println("Expected error received: Only 4 attachments allowed."); + // } + // String check = createResponse5.get(0); + // if (check.equals("Attachment created")) { + // testStatus = false; + // } else { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID4); + // if (response.equals("Saved")) { + // String expectedJson = + // "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 + // attachments.\"}}"; + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode actualJsonNode = objectMapper.readTree(check); + // JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); + // if (expectedJsonNode.equals(actualJsonNode)) { + // testStatus = true; + // } + // } + // } + // } + // if (!testStatus) { + // fail("Attachment was created"); + // } + // } - if (!testStatus) { - fail( - "Could not verify that notes field was copied from source to target attachment for all facets"); - } - } + // @Test + // @Order(29) + // void testUploadNAttachments() throws IOException { + // System.out.println("Test (29): Upload maximum 4 attachments in an exsisting entity"); - @Test - @Order(38) - void testCopyAttachmentWithSecondaryPropertiesField() throws IOException { - System.out.println( - "Test (38): Verify that secondary properties are preserved when copying attachments between entities across multiple facets"); - Boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File originalFile = new File(classLoader.getResource("sample.exe").getFile()); + + // boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID4); + // System.out.println("response: " + response); + + // if ("Entity in draft mode".equals(response)) { + // for (int i = 1; i <= 5; i++) { + // // Ensure only one file is uploaded at a time and complete before next + // File tempFile = File.createTempFile("sample_" + i + "_", ".exe"); + // Files.copy(originalFile.toPath(), tempFile.toPath(), + // StandardCopyOption.REPLACE_EXISTING); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID4); + // postData.put("mimeType", "application/exe"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[0], entityID4, srvpath, postData, tempFile); + + // String resultMessage = createResponse.get(0); + // System.out.println("Result message for attachment " + i + ": " + resultMessage); + + // String expectedResponse = + // "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 + // attachments.\"}}"; + // if (resultMessage.equals(expectedResponse)) { + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode actualJsonNode = objectMapper.readTree(resultMessage); + // JsonNode expectedJsonNode = objectMapper.readTree(expectedResponse); + // if (expectedJsonNode.equals(actualJsonNode)) { + // testStatus = true; + // } + // } else { + // testStatus = false; + // } + // tempFile.delete(); + // } + // if (!testStatus) { + // fail("5th attachment did not trigger the expected error."); + // } + // // Delete the newly created entity + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID4); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } else { + // System.out.println("Successfully deleted the test entity4"); + // } + // } + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity"); - } + // @Test + // @Order(30) + // void testDiscardDraftWithoutAttachments() { + // System.out.println("Test (30) : Discard draft without adding attachments"); + // Boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample1.pdf").getFile()); + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID6 = response; + // response = api.deleteEntityDraft(appUrl, entityName, entityID6); + // if (response.equals("Entity Draft Deleted")) { + // testStatus = true; + // } + // } + // if (!testStatus) { + // fail("Draft was not discarded properly"); + // } + // } - List objectIdsToStore = new ArrayList<>(); + // @Test + // @Order(31) + // void testDiscardDraftWithAttachments() throws IOException { + // System.out.println("Test (31): Discard draft with attachments, references, and footnotes"); + // boolean testStatus = false; - for (String facetName : facet) { - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!"Could not create entity".equals(response)) { + // entityID6 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID6); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + // for (int i = 0; i < facet.length; i++) { + // List createResponse = + // api.createAttachment(appUrl, entityName, facet[i], entityID6, srvpath, postData, + // file); + // if ("Attachment created".equals(createResponse.get(0))) { + // System.out.println("Attachment created in facet: " + facet[i]); + // } else { + // System.out.println("Attachment creation failed in facet: " + facet[i]); + // } + // } + // response = api.deleteEntityDraft(appUrl, entityName, entityID6); + // if ("Entity Draft Deleted".equals(response)) { + // testStatus = true; + // } + // } + // if (!testStatus) { + // fail("Draft with attachments was not discarded properly"); + // } + // } - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment in facet: " + facetName); - } + // @Test + // @Order(32) + // void testDraftUpdateUploadTwoDeleteOneAndCreate() throws IOException { + // System.out.println("Test (32): Upload to all facets, delete one, and create entity"); - String sourceAttachmentId = createResponse.get(1); + // boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - copyCustomSourceEntity, - sourceAttachmentId, - bodyBoolean); + // if (!"Could not create entity".equals(response)) { + // entityID5 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + + // File file1 = + // new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + // File file2 = + // new File(Objects.requireNonNull(classLoader.getResource("sample.txt")).getFile()); + + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID5); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // Map postData2 = new HashMap<>(postData1); + // postData2.put("up__ID", entityID5); + // postData2.put("mimeType", "text/plain"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // boolean allCreated = true; + // for (int i = 0; i < facet.length; i++) { + // List response1 = + // api.createAttachment( + // appUrl, entityName, facet[i], entityID5, srvpath, postData1, file1); + // List response2 = + // api.createAttachment( + // appUrl, entityName, facet[i], entityID5, srvpath, postData2, file2); + + // if (response1.get(0).equals("Attachment created") + // && response2.get(0).equals("Attachment created")) { + // ID4[i] = response1.get(1); // to keep one + // ID5[i] = response2.get(1); // will delete this one + // } else { + // allCreated = false; + // break; + // } - if (!updateSecondaryPropertyResponse1.equals("Updated")) { - fail("Could not update attachment DocumentInfoRecordBoolean field for facet: " + facetName); - } + // String deleteResponse = + // api.deleteAttachment(appUrl, entityName, facet[i], entityID5, ID5[i]); + // if (!"Deleted".equals(deleteResponse)) { + // allCreated = false; + // break; + // } + // } - Integer customProperty2Value = 12345; - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); - - if (!updateSecondaryPropertyResponse2.equals("Updated")) { - fail("Could not update attachment customProperty2 field for facet: " + facetName); - } - } + // if (allCreated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); + // if ("Saved".equals(response)) { + // testStatus = true; + // } + // } + // } - // Save source entity to persist attachments before fetching metadata - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity after creating attachments"); - } + // if (!testStatus) { + // fail("Failed to upload multiple facet entries, delete one per facet and create entity"); + // } + // } - Integer customProperty2Value = 12345; - for (String facetName : facet) { - List> sourceAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomSourceEntity); + // @Test + // @Order(33) + // void testUpdateEntityDraft() throws IOException { + // System.out.println("Test (33): Update entity draft with new facet content"); + // boolean testStatus = false; - Map sourceAttachmentMetadata = - sourceAttachmentsMetadata.stream() - .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); + + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID5); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID5); + // if ("Entity in draft mode".equals(response)) { + // boolean allCreated = true; + + // for (int i = 0; i < facet.length; i++) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], entityID5, srvpath, postData, tempFile); + // if (!"Attachment created".equals(createResponse.get(0))) { + // allCreated = false; + // } + // } - if (sourceAttachmentMetadata == null) { - fail("Could not find attachment with filename 'sample1.pdf' in facet: " + facetName); - } + // if (allCreated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); + // if ("Saved".equals(response)) { + // testStatus = true; + // } + // } + // } + // api.deleteEntity(appUrl, entityName, entityID5); + // if (!testStatus) { + // fail("Failed to update draft with new attachments for all facets"); + // } + // } - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId for facet: " + facetName); - } + // @Test + // @Order(34) + // void testUploadAttachmentWithoutSDMRole() throws IOException { + // System.out.println("Test (34): Upload attachment across facets without SDM role"); + // boolean testStatus = true; - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - objectIdsToStore.add(sourceObjectId); + // String response = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID7 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - Boolean sourceCustomProperty6 = - sourceAttachmentMetadata.get("customProperty6") != null - ? (Boolean) sourceAttachmentMetadata.get("customProperty6") - : null; - Integer sourceCustomProperty2 = - sourceAttachmentMetadata.get("customProperty2") != null - ? (Integer) sourceAttachmentMetadata.get("customProperty2") - : null; + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - if (sourceCustomProperty6 == null || !sourceCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly set in source attachment for facet " - + facetName - + ". Expected: true, Got: " - + sourceCustomProperty6); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - if (!customProperty2Value.equals(sourceCustomProperty2)) { - fail( - "customProperty2 was not properly set in source attachment for facet " - + facetName - + ". Expected: " - + customProperty2Value - + ", Got: " - + sourceCustomProperty2); - } - } + // for (int i = 0; i < facet.length; i++) { + // List createResponse = + // apiNoRoles.createAttachment( + // appUrl, entityName, facet[i], entityID7, srvpath, postData, tempFile); + // String check = createResponse.get(0); + // String expectedError = + // "{\"error\":{\"code\":\"500\",\"message\":\"You do not have the required permissions + // to upload attachments. Please contact your administrator for access.\"}}"; + // if (!expectedError.equals(check)) { + // testStatus = false; + // } + // } + // } + // api.deleteEntityDraft(appUrl, entityName, entityID7); + // if (!testStatus) { + // fail("Attachment uploaded without SDM role for one or more facets"); + // } + // } - int startIndex = sourceObjectIds.size(); - sourceObjectIds.addAll(objectIdsToStore); + // @Test + // @Order(35) + // void testCopyAttachmentsSuccessNewEntity() throws IOException { + // System.out.println("Test (35): Copy attachments from one entity to another new entity"); + // List> attachments = new ArrayList<>(); + // for (int i = 0; i < 3; i++) { + // attachments.add(new ArrayList<>()); + // } + // copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!copyAttachmentSourceEntity.equals("Could not create entity") + // && !copyAttachmentTargetEntity.equals("Could not create entity")) { + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample1.pdf").getFile())); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - int facetIndex = 0; - for (String facetName : facet) { - String editTargetResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!editTargetResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity"); - } + // for (int i = 0; i < facet.length; i++) { + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facet[i], + // copyAttachmentSourceEntity, + // srvpath, + // postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.get(i).add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } + // } + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (int i = 0; i < attachments.size(); i++) { + // for (String attachment : attachments.get(i)) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadataDraft( + // appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } + // } + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + + // if (sourceObjectIds.size() == 6) { + // String copyResponse; + // int i = 0; + // for (String facetName : facet) { + // if (i != 0) { + // String editResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } + // } + // copyResponse = + // api.copyAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size()))); + // i += 2; + // if (copyResponse.equals("Attachments copied successfully")) { + // // Fetch copied attachment IDs from target draft + // List> copiedMetadataResponse = + // api.fetchEntityMetadata(appUrl, entityName, facetName, + // copyAttachmentTargetEntity); + // List copiedAttachmentIds = + // copiedMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadata( + // appUrl, entityName, facetName, copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not create entities"); + // } + // } - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); + // @Test + // @Order(36) + // void testCopyAttachmentsUnsuccessfulNewEntity() throws IOException { + // System.out.println( + // "Test (36): Copy incorrect attachments from one entity to another new entity"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // copyAttachmentTargetEntityEmpty = + // api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (editResponse1.equals("Entity in draft mode") + // && !copyAttachmentTargetEntityEmpty.equals("Could not create entity")) { + // if (sourceObjectIds.size() == 6) { + // int i = 0; + // for (String facet : facet) { + // try { + // List currentFacetObjectIds = + // sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); + // currentFacetObjectIds.add("incorrectObjectId"); + // if (currentFacetObjectIds.size() != 3) { + // fail("Not enough object IDs to copy attachments for facet: " + facet); + // } + // api.copyAttachment( + // appUrl, entityName, facet, copyAttachmentTargetEntityEmpty, + // currentFacetObjectIds); + // fail("Copy attachments did not throw an error"); + // } catch (IOException e) { + // i += 2; + // } + // } + // String saveEntityResponse1 = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String saveEntityResponse2 = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntityEmpty); + // String deleteResponse = + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntityEmpty); + // if (!saveEntityResponse1.equals("Saved") + // || !saveEntityResponse2.equals("Saved") + // || !deleteResponse.equals("Entity Deleted")) { + // fail("Could not save entities"); + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - String copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // @Test + // @Order(37) + // void testCopyAttachmentWithNotesField() throws IOException { + // System.out.println( + // "Test (37): Create entity with attachments containing notes in multiple facets, copy to + // new entity and verify notes field"); + // Boolean testStatus = false; - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity for facet: " + facetName); - } + // copyCustomSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyCustomSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Fetch copied attachment IDs from target draft - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity for facet: " + facetName); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // String notesValue = "This is a test note for copy attachment verification"; + // MediaType mediaType = MediaType.parse("application/json"); - facetIndex++; - } + // for (String facetName : facet) { + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - for (String facetName : facet) { - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - Map copiedAttachmentMetadata = - targetAttachmentsMetadata.stream() - .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment in facet: " + facetName); + // } - if (copiedAttachmentMetadata == null) { - fail( - "Could not find the copied attachment with file in target entity for facet: " - + facetName); - } + // String sourceAttachmentId = createResponse.get(1); - Boolean copiedCustomProperty6 = - copiedAttachmentMetadata.get("customProperty6") != null - ? (Boolean) copiedAttachmentMetadata.get("customProperty6") - : null; - Integer copiedCustomProperty2 = - copiedAttachmentMetadata.get("customProperty2") != null - ? (Integer) copiedAttachmentMetadata.get("customProperty2") - : null; + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateBody = RequestBody.create(jsonPayload, mediaType); - if (copiedCustomProperty6 == null || !copiedCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly copied for facet " - + facetName - + ". Expected: true, Got: " - + copiedCustomProperty6); - } + // String updateResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // copyCustomSourceEntity, + // sourceAttachmentId, + // updateBody); - if (!customProperty2Value.equals(copiedCustomProperty2)) { - fail( - "customProperty2 was not properly copied for facet " - + facetName - + ". Expected: " - + customProperty2Value - + ", Got: " - + copiedCustomProperty2); - } + // if (!updateResponse.equals("Updated")) { + // fail("Could not update attachment notes field in facet: " + facetName); + // } + // } - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // List objectIdsToStore = new ArrayList<>(); + // for (String facetName : facet) { + // List> sourceAttachmentsMetadata = + // api.fetchEntityMetadataDraft(appUrl, entityName, facetName, copyCustomSourceEntity); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment from target entity for facet: " + facetName); - } else { - testStatus = true; - } - } + // if (sourceAttachmentsMetadata.isEmpty()) { + // fail("No attachments found in source entity for facet: " + facetName); + // } - if (!testStatus) { - fail( - "Could not verify that all secondary properties were copied from source to target attachment for all facets"); - } - } + // Map sourceAttachmentMetadata = sourceAttachmentsMetadata.get(0); - @Test - @Order(39) - void testCopyAttachmentWithNotesAndSecondaryPropertiesField() throws IOException { - System.out.println( - "Test (39): Verify that both notes field and secondary properties are preserved during attachment copy across multiple facets"); - Boolean testStatus = false; + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId for facet: " + facetName); + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity"); - } + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // objectIdsToStore.add(sourceObjectId); + + // String sourceNoteValue = + // sourceAttachmentMetadata.get("note") != null + // ? sourceAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(sourceNoteValue)) { + // fail( + // "Notes field was not properly set in source attachment for facet " + // + facetName + // + ". Expected: " + // + notesValue + // + ", Got: " + // + sourceNoteValue); + // } + // } - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample2.pdf").getFile()); + // int startIndex = sourceObjectIds.size(); + // sourceObjectIds.addAll(objectIdsToStore); - String notesValue = "This attachment has both notes and secondary properties for testing"; - MediaType mediaType = MediaType.parse("application/json"); - Integer customProperty2Value = 99999; - List objectIdsToStore = new ArrayList<>(); + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity"); + // } - for (String facetName : facet) { - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // copyCustomTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyCustomTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // int facetIndex = 0; + // for (String facetName : facet) { + // if (facetIndex > 0) { + // String editResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } + // } - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment in facet: " + facetName); - } + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); - String sourceAttachmentId = createResponse.get(1); + // String copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity for facet: " + facetName); + // } - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - copyCustomSourceEntity, - sourceAttachmentId, - updateNotesBody); + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity for facet: " + facetName); + // } - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update attachment notes field for facet: " + facetName); - } + // facetIndex++; + // } - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - copyCustomSourceEntity, - sourceAttachmentId, - bodyBoolean); + // for (String facetName : facet) { + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - if (!updateSecondaryPropertyResponse1.equals("Updated")) { - fail("Could not update attachment DocumentInfoRecordBoolean field for facet: " + facetName); - } + // if (targetAttachmentsMetadata.isEmpty()) { + // fail("No attachments found in target entity for facet: " + facetName); + // } - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); + // Map copiedAttachmentMetadata = targetAttachmentsMetadata.get(0); + // String copiedNoteValue = + // copiedAttachmentMetadata.get("note") != null + // ? copiedAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(copiedNoteValue)) { + // fail( + // "Notes field was not properly copied for facet " + // + facetName + // + ". Expected: " + // + notesValue + // + ", Got: " + // + copiedNoteValue); + // } - if (!updateSecondaryPropertyResponse2.equals("Updated")) { - fail("Could not update attachment customProperty2 field for facet: " + facetName); - } - } + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - // Save source entity to persist attachments before fetching metadata and copying - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity after creating attachments"); - } + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment from target entity for facet: " + facetName); + // } else { + // testStatus = true; + // } + // } - for (String facetName : facet) { - List> sourceAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomSourceEntity); + // if (!testStatus) { + // fail( + // "Could not verify that notes field was copied from source to target attachment for all + // facets"); + // } + // } - Map sourceAttachmentMetadata = - sourceAttachmentsMetadata.stream() - .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // @Test + // @Order(38) + // void testCopyAttachmentWithSecondaryPropertiesField() throws IOException { + // System.out.println( + // "Test (38): Verify that secondary properties are preserved when copying attachments + // between entities across multiple facets"); + // Boolean testStatus = false; + + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyCustomSourceEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity"); + // } - if (sourceAttachmentMetadata == null) { - fail("Could not find attachment with file in facet: " + facetName); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample1.pdf").getFile()); - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId for facet: " + facetName); - } + // List objectIdsToStore = new ArrayList<>(); - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - objectIdsToStore.add(sourceObjectId); + // for (String facetName : facet) { + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String sourceNoteValue = - sourceAttachmentMetadata.get("note") != null - ? sourceAttachmentMetadata.get("note").toString() - : null; + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - if (!notesValue.equals(sourceNoteValue)) { - fail( - "Notes field was not properly set in source attachment for facet " - + facetName - + ". Expected: " - + notesValue - + ", Got: " - + sourceNoteValue); - } + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment in facet: " + facetName); + // } - Boolean sourceCustomProperty6 = - sourceAttachmentMetadata.get("customProperty6") != null - ? (Boolean) sourceAttachmentMetadata.get("customProperty6") - : null; - Integer sourceCustomProperty2 = - sourceAttachmentMetadata.get("customProperty2") != null - ? (Integer) sourceAttachmentMetadata.get("customProperty2") - : null; + // String sourceAttachmentId = createResponse.get(1); + + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // copyCustomSourceEntity, + // sourceAttachmentId, + // bodyBoolean); + + // if (!updateSecondaryPropertyResponse1.equals("Updated")) { + // fail("Could not update attachment DocumentInfoRecordBoolean field for facet: " + + // facetName); + // } - if (sourceCustomProperty6 == null || !sourceCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly set in source attachment for facet " - + facetName - + ". Expected: true, Got: " - + sourceCustomProperty6); - } + // Integer customProperty2Value = 12345; + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + + // "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, + // bodyInt); + + // if (!updateSecondaryPropertyResponse2.equals("Updated")) { + // fail("Could not update attachment customProperty2 field for facet: " + facetName); + // } + // } - if (!customProperty2Value.equals(sourceCustomProperty2)) { - fail( - "customProperty2 was not properly set in source attachment for facet " - + facetName - + ". Expected: " - + customProperty2Value - + ", Got: " - + sourceCustomProperty2); - } - } + // // Save source entity to persist attachments before fetching metadata + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity after creating attachments"); + // } - int startIndex = sourceObjectIds.size(); - sourceObjectIds.addAll(objectIdsToStore); + // Integer customProperty2Value = 12345; + // for (String facetName : facet) { + // List> sourceAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomSourceEntity); - int facetIndex = 0; - for (String facetName : facet) { - String editTargetResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!editTargetResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity"); - } + // Map sourceAttachmentMetadata = + // sourceAttachmentsMetadata.stream() + // .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); + // if (sourceAttachmentMetadata == null) { + // fail("Could not find attachment with filename 'sample1.pdf' in facet: " + facetName); + // } - String copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId for facet: " + facetName); + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity for facet: " + facetName); - } + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // objectIdsToStore.add(sourceObjectId); + + // Boolean sourceCustomProperty6 = + // sourceAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) sourceAttachmentMetadata.get("customProperty6") + // : null; + // Integer sourceCustomProperty2 = + // sourceAttachmentMetadata.get("customProperty2") != null + // ? (Integer) sourceAttachmentMetadata.get("customProperty2") + // : null; + + // if (sourceCustomProperty6 == null || !sourceCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly set in source attachment for facet " + // + facetName + // + ". Expected: true, Got: " + // + sourceCustomProperty6); + // } - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity for facet: " + facetName); - } + // if (!customProperty2Value.equals(sourceCustomProperty2)) { + // fail( + // "customProperty2 was not properly set in source attachment for facet " + // + facetName + // + ". Expected: " + // + customProperty2Value + // + ", Got: " + // + sourceCustomProperty2); + // } + // } - facetIndex++; - } + // int startIndex = sourceObjectIds.size(); + // sourceObjectIds.addAll(objectIdsToStore); - for (String facetName : facet) { - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // int facetIndex = 0; + // for (String facetName : facet) { + // String editTargetResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!editTargetResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity"); + // } - Map copiedAttachmentMetadata = - targetAttachmentsMetadata.stream() - .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); - if (copiedAttachmentMetadata == null) { - fail( - "Could not find the copied attachment with file in target entity for facet: " - + facetName); - } + // String copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); - String copiedNoteValue = - copiedAttachmentMetadata.get("note") != null - ? copiedAttachmentMetadata.get("note").toString() - : null; + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity for facet: " + facetName); + // } - if (!notesValue.equals(copiedNoteValue)) { - fail( - "Notes field was not properly copied for facet " - + facetName - + ". Expected: " - + notesValue - + ", Got: " - + copiedNoteValue); - } + // // Fetch copied attachment IDs from target draft + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity for facet: " + facetName); + // } - Boolean copiedCustomProperty6 = - copiedAttachmentMetadata.get("customProperty6") != null - ? (Boolean) copiedAttachmentMetadata.get("customProperty6") - : null; - Integer copiedCustomProperty2 = - copiedAttachmentMetadata.get("customProperty2") != null - ? (Integer) copiedAttachmentMetadata.get("customProperty2") - : null; + // facetIndex++; + // } - if (copiedCustomProperty6 == null || !copiedCustomProperty6) { - fail( - "DocumentInfoRecordBoolean (customProperty6) was not properly copied for facet " - + facetName - + ". Expected: true, Got: " - + copiedCustomProperty6); - } - if (!customProperty2Value.equals(copiedCustomProperty2)) { - fail( - "customProperty2 was not properly copied for facet " - + facetName - + ". Expected: " - + customProperty2Value - + ", Got: " - + copiedCustomProperty2); - } - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // for (String facetName : facet) { + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment from target entity for facet: " + facetName); - } else { - testStatus = true; - } - } - api.deleteEntity(appUrl, entityName, copyCustomSourceEntity); - api.deleteEntity(appUrl, entityName, copyCustomTargetEntity); - if (!testStatus) { - fail( - "Could not verify that notes field and all secondary properties were copied from source to target attachment for all facets"); - } - } + // Map copiedAttachmentMetadata = + // targetAttachmentsMetadata.stream() + // .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - @Test - @Order(40) - void testCopyAttachmentsSuccessExistingEntity() throws IOException { - System.out.println("Test (40): Copy attachments from one entity to another existing entity"); - List> attachments = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - attachments.add(new ArrayList<>()); - } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - File file1 = new File(classLoader.getResource("sample.pdf").getFile()); - File file2 = new File(classLoader.getResource("sample1.pdf").getFile()); - File tempFile1 = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file1.toPath(), tempFile1.toPath(), StandardCopyOption.REPLACE_EXISTING); - File tempFile2 = new File(System.getProperty("java.io.tmpdir"), "sample4.pdf"); - Files.copy(file2.toPath(), tempFile2.toPath(), StandardCopyOption.REPLACE_EXISTING); - files.add(tempFile1); - files.add(tempFile2); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String editResponse2 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (editResponse1.equals("Entity in draft mode") - && editResponse2.equals("Entity in draft mode")) { - for (int i = 0; i < facet.length; i++) { - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, - entityName, - facet[i], - copyAttachmentSourceEntity, - srvpath, - postData, - file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.get(i).add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } - } - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (int i = 0; i < attachments.size(); i++) { - for (String attachment : attachments.get(i)) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadataDraft( - appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } - } + // if (copiedAttachmentMetadata == null) { + // fail( + // "Could not find the copied attachment with file in target entity for facet: " + // + facetName); + // } - sourceObjectIds.clear(); - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - - if (sourceObjectIds.size() == 6) { - String copyResponse; - int i = 0; - for (String facetName : facet) { - if (i != 0) { - String editResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } - } - List currentFacetObjectIds = - sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); - if (currentFacetObjectIds.size() != 2) { - fail("Not enough object IDs to copy attachments for facet: " + facet); - } - copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, currentFacetObjectIds); - i += 2; - if (copyResponse.equals("Attachments copied successfully")) { - // Fetch copied attachment IDs from target draft - List> copiedMetadataResponse = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyAttachmentTargetEntity); - List copiedAttachmentIds = - copiedMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadata( - appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - if (targetAttachmentIds.size() == 4) { - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // Boolean copiedCustomProperty6 = + // copiedAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) copiedAttachmentMetadata.get("customProperty6") + // : null; + // Integer copiedCustomProperty2 = + // copiedAttachmentMetadata.get("customProperty2") != null + // ? (Integer) copiedAttachmentMetadata.get("customProperty2") + // : null; + + // if (copiedCustomProperty6 == null || !copiedCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly copied for facet " + // + facetName + // + ". Expected: true, Got: " + // + copiedCustomProperty6); + // } - @Test - @Order(41) - void testCopyAttachmentsUnsuccessfulExistingEntity() throws IOException { - System.out.println("Test (41): Copy attachments from one entity to another new entity"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String editResponse2 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (editResponse1.equals("Entity in draft mode") - && editResponse2.equals("Entity in draft mode")) { - if (sourceObjectIds.size() == 6) { - int i = 0; - for (String facetName : facet) { - List currentFacetObjectIds = - sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); - currentFacetObjectIds.add("incorrectObjectId"); - if (currentFacetObjectIds.size() != 3) { - fail("Not enough object IDs to copy attachments for facet: " + facet); - } - try { - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); - fail("Copy attachments did not throw an error"); - } catch (IOException e) { - i += 2; - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // if (!customProperty2Value.equals(copiedCustomProperty2)) { + // fail( + // "customProperty2 was not properly copied for facet " + // + facetName + // + ". Expected: " + // + customProperty2Value + // + ", Got: " + // + copiedCustomProperty2); + // } - @Test - @Order(42) - void testCreateLinkSuccess() throws IOException { - System.out.println("Test (42): Create link in entity"); - List attachments = new ArrayList<>(); + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment from target entity for facet: " + facetName); + // } else { + // testStatus = true; + // } + // } - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - for (String facetName : facet) { - String createLinkResponse1 = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - String createLinkResponse2 = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName + "1", linkUrl); - if (!createLinkResponse1.equals("Link created successfully") - || !createLinkResponse2.equals("Link created successfully")) { - fail("Could not create links for facet : " + facetName + createLinkResponse1); - } - } + // if (!testStatus) { + // fail( + // "Could not verify that all secondary properties were copied from source to target + // attachment for all facets"); + // } + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // @Test + // @Order(39) + // void testCopyAttachmentWithNotesAndSecondaryPropertiesField() throws IOException { + // System.out.println( + // "Test (39): Verify that both notes field and secondary properties are preserved during + // attachment copy across multiple facets"); + // Boolean testStatus = false; + + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyCustomSourceEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity"); + // } - for (String facetName : facet) { - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String openAttachmentResponse; - for (String attachment : attachments) { - openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, createLinkEntity, attachment); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open created link in facet : " + facetName); - } - } - } - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample2.pdf").getFile()); - @Test - @Order(43) - void testCreateLinkDifferentEntity() throws IOException { - System.out.println("Test (43): Create link with same name in different entity"); + // String notesValue = "This attachment has both notes and secondary properties for testing"; + // MediaType mediaType = MediaType.parse("application/json"); + // Integer customProperty2Value = 99999; + // List objectIdsToStore = new ArrayList<>(); - String createLinkDifferentEntity = - api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkDifferentEntity.equals("Could not edit entity")) { - fail("Could not create entity"); - } + // for (String facetName : facet) { + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String linkName = "sample"; - String linkUrl = "https://example.com"; - for (String facetName : facet) { - String createResponse = - api.createLink( - appUrl, entityName, facetName, createLinkDifferentEntity, linkName, linkUrl); - if (!createResponse.equals("Link created successfully")) { - fail("Could not create link in different entity with same name"); - } - } + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkDifferentEntity); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment in facet: " + facetName); + // } - response = api.deleteEntity(appUrl, entityName, createLinkDifferentEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } + // String sourceAttachmentId = createResponse.get(1); - @Test - @Order(44) - void testCreateLinkFailure() throws IOException { - System.out.println("Test (41): Create link fails due to invalid URL and name"); - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (editEntityResponse.equals("Could not edit entity")) { - fail("Could not edit entity"); - } - for (String facetName : facet) { - String linkName = "sample"; - String linkUrl = "example.com"; - try { - String response = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - fail("Create link did not throw an error for invalid url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("400018", errorCode); - assertTrue( - errorMessage.equals("Enter a value that is within the expected pattern.") - || errorMessage.equals("Enter a value that matches the expected pattern."), - "Unexpected error message: " + errorMessage); - } - try { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName + "//", "https://" + linkUrl); - fail("Create link did not throw an error for invalid name"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = - "\"sample//\" contains unsupported characters (‘/’ or ‘\\’). Rename and try again."; - assertEquals("500", errorCode); - assertEquals( - expected.replaceAll("\\s+", " ").trim(), errorMessage.replaceAll("\\s+", " ").trim()); - } - try { - api.createLink(appUrl, entityName, facetName, createLinkEntity, "", ""); - fail("Create link did not throw an error for empty name and url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = "Provide the missing value."; - assertEquals("409008", errorCode); - assertEquals(expected, errorMessage); - } - try { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName, "https://" + linkUrl); - fail("Create link did not throw an error for duplicate name"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals( - "An object named \"sample\" already exists. Rename the object and try again.", - errorMessage); - } - try { - for (int i = 2; i < 6; i++) { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName + i, "https://" + linkUrl); - } - System.out.println("Created 5 links in facet: " + facetName); - if (!facetName.equals("footnotes")) { - fail("More than 5 links were created in the same entity"); - } - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - if (facetName.equals("references")) { - assertEquals("Cannot upload more than 5 attachments.", errorMessage); - } else if (facetName.equals("attachments")) { - assertEquals("Cannot upload more than 4 attachments.", errorMessage); - } - } - } + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); - String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // copyCustomSourceEntity, + // sourceAttachmentId, + // updateNotesBody); - response = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update attachment notes field for facet: " + facetName); + // } - @Test - @Order(45) - void testCreateLinkNoSDMRoles() throws IOException { - System.out.println("Test (42): Create link fails due to no SDM roles assigned"); + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // copyCustomSourceEntity, + // sourceAttachmentId, + // bodyBoolean); + + // if (!updateSecondaryPropertyResponse1.equals("Updated")) { + // fail("Could not update attachment DocumentInfoRecordBoolean field for facet: " + + // facetName); + // } - String createLinkEntityNoSDMRoles = - apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntityNoSDMRoles.equals("Could not edit entity")) { - fail("Could not create entity"); - } + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + + // "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, + // bodyInt); + + // if (!updateSecondaryPropertyResponse2.equals("Updated")) { + // fail("Could not update attachment customProperty2 field for facet: " + facetName); + // } + // } - for (String facetName : facet) { - String linkName = "sample27"; - String linkUrl = "https://example.com"; - try { - apiNoRoles.createLink( - appUrl, entityName, facetName, createLinkEntityNoSDMRoles, linkName, linkUrl); - fail("Link got created without SDM roles"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals( - "You do not have the required permissions to upload attachments. Please contact your administrator for access.", - errorMessage); - } - } + // // Save source entity to persist attachments before fetching metadata and copying + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity after creating attachments"); + // } - String response = - apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntityNoSDMRoles); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } + // for (String facetName : facet) { + // List> sourceAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomSourceEntity); - response = api.deleteEntity(appUrl, entityName, createLinkEntityNoSDMRoles); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } + // Map sourceAttachmentMetadata = + // sourceAttachmentsMetadata.stream() + // .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - @Test - @Order(46) - void testDeleteLink() throws IOException { - System.out.println("Test (43): Delete link in entity"); - List> attachments = new ArrayList<>(); + // if (sourceAttachmentMetadata == null) { + // fail("Could not find attachment with file in facet: " + facetName); + // } - String createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId for facet: " + facetName); + // } - for (String facetName : facet) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet : " + facetName); - } - } + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // objectIdsToStore.add(sourceObjectId); + + // String sourceNoteValue = + // sourceAttachmentMetadata.get("note") != null + // ? sourceAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(sourceNoteValue)) { + // fail( + // "Notes field was not properly set in source attachment for facet " + // + facetName + // + ". Expected: " + // + notesValue + // + ", Got: " + // + sourceNoteValue); + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // Boolean sourceCustomProperty6 = + // sourceAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) sourceAttachmentMetadata.get("customProperty6") + // : null; + // Integer sourceCustomProperty2 = + // sourceAttachmentMetadata.get("customProperty2") != null + // ? (Integer) sourceAttachmentMetadata.get("customProperty2") + // : null; + + // if (sourceCustomProperty6 == null || !sourceCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly set in source attachment for facet " + // + facetName + // + ". Expected: true, Got: " + // + sourceCustomProperty6); + // } - for (String facetName : facet) { - attachments.add( - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList())); - } + // if (!customProperty2Value.equals(sourceCustomProperty2)) { + // fail( + // "customProperty2 was not properly set in source attachment for facet " + // + facetName + // + ". Expected: " + // + customProperty2Value + // + ", Got: " + // + sourceCustomProperty2); + // } + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // int startIndex = sourceObjectIds.size(); + // sourceObjectIds.addAll(objectIdsToStore); - int index = 0; - for (String facetName : facet) { - String deleteLinkResponse = - api.deleteAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(index).get(0)); - System.out.println("Delete response for facet " + facetName + ": " + deleteLinkResponse); - if (!deleteLinkResponse.equals("Deleted")) { - fail("Could not delete created link"); - } - index += 1; - } + // int facetIndex = 0; + // for (String facetName : facet) { + // String editTargetResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!editTargetResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity"); + // } - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(startIndex + facetIndex)); - index = 0; - attachments.clear(); - for (String facetName : facet) { - attachments.add( - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList())); - System.out.println( - "Attachments after deletion in facet " + facetName + ": " + attachments.get(index)); - if (attachments.get(index).size() != 0) { - fail("Link wasn't deleted"); - } - index += 1; - } + // String copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); - String response = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity for facet: " + facetName); + // } - @Test - @Order(47) - void testRenameLinkSuccess() throws IOException { - System.out.println("Test (44): Rename link in entity"); - List> attachments = new ArrayList<>(); + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity for facet: " + facetName); + // } - createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // facetIndex++; + // } - for (String facetName : facet) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } - } + // for (String facetName : facet) { + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // Map copiedAttachmentMetadata = + // targetAttachmentsMetadata.stream() + // .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - for (String facetName : facet) { - attachments.add( - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList())); - } + // if (copiedAttachmentMetadata == null) { + // fail( + // "Could not find the copied attachment with file in target entity for facet: " + // + facetName); + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // String copiedNoteValue = + // copiedAttachmentMetadata.get("note") != null + // ? copiedAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(copiedNoteValue)) { + // fail( + // "Notes field was not properly copied for facet " + // + facetName + // + ". Expected: " + // + notesValue + // + ", Got: " + // + copiedNoteValue); + // } - int index = 0; - for (String facetName : facet) { - successfullyRenamedAttachments.add(attachments.get(index).get(0)); - String renameLinkResponse = - api.renameAttachment( - appUrl, - entityName, - facetName, - createLinkEntity, - attachments.get(index).get(0), - "sampleRenamed"); - if (!renameLinkResponse.equals("Renamed")) { - fail("Could not Renamed created link"); - } - index += 1; - } + // Boolean copiedCustomProperty6 = + // copiedAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) copiedAttachmentMetadata.get("customProperty6") + // : null; + // Integer copiedCustomProperty2 = + // copiedAttachmentMetadata.get("customProperty2") != null + // ? (Integer) copiedAttachmentMetadata.get("customProperty2") + // : null; + + // if (copiedCustomProperty6 == null || !copiedCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean (customProperty6) was not properly copied for facet " + // + facetName + // + ". Expected: true, Got: " + // + copiedCustomProperty6); + // } + // if (!customProperty2Value.equals(copiedCustomProperty2)) { + // fail( + // "customProperty2 was not properly copied for facet " + // + facetName + // + ". Expected: " + // + customProperty2Value + // + ", Got: " + // + copiedCustomProperty2); + // } + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } - } + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment from target entity for facet: " + facetName); + // } else { + // testStatus = true; + // } + // } + // api.deleteEntity(appUrl, entityName, copyCustomSourceEntity); + // api.deleteEntity(appUrl, entityName, copyCustomTargetEntity); + // if (!testStatus) { + // fail( + // "Could not verify that notes field and all secondary properties were copied from source + // to target attachment for all facets"); + // } + // } - @Test - @Order(48) - void testRenameLinkDuplicate() throws IOException { - System.out.println("Test (45): Rename link in entity fails due to duplicate error"); - List attachments = new ArrayList<>(); - - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // @Test + // @Order(40) + // void testCopyAttachmentsSuccessExistingEntity() throws IOException { + // System.out.println("Test (40): Copy attachments from one entity to another existing entity"); + // List> attachments = new ArrayList<>(); + // for (int i = 0; i < 3; i++) { + // attachments.add(new ArrayList<>()); + // } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // File file1 = new File(classLoader.getResource("sample.pdf").getFile()); + // File file2 = new File(classLoader.getResource("sample1.pdf").getFile()); + // File tempFile1 = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file1.toPath(), tempFile1.toPath(), StandardCopyOption.REPLACE_EXISTING); + // File tempFile2 = new File(System.getProperty("java.io.tmpdir"), "sample4.pdf"); + // Files.copy(file2.toPath(), tempFile2.toPath(), StandardCopyOption.REPLACE_EXISTING); + // files.add(tempFile1); + // files.add(tempFile2); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String editResponse2 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (editResponse1.equals("Entity in draft mode") + // && editResponse2.equals("Entity in draft mode")) { + // for (int i = 0; i < facet.length; i++) { + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facet[i], + // copyAttachmentSourceEntity, + // srvpath, + // postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.get(i).add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } + // } + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (int i = 0; i < attachments.size(); i++) { + // for (String attachment : attachments.get(i)) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadataDraft( + // appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } + // } - int index = 0; - for (String facetName : facet) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } - } + // sourceObjectIds.clear(); + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + + // if (sourceObjectIds.size() == 6) { + // String copyResponse; + // int i = 0; + // for (String facetName : facet) { + // if (i != 0) { + // String editResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } + // } + // List currentFacetObjectIds = + // sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); + // if (currentFacetObjectIds.size() != 2) { + // fail("Not enough object IDs to copy attachments for facet: " + facet); + // } + // copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, + // currentFacetObjectIds); + // i += 2; + // if (copyResponse.equals("Attachments copied successfully")) { + // // Fetch copied attachment IDs from target draft + // List> copiedMetadataResponse = + // api.fetchEntityMetadata(appUrl, entityName, facetName, + // copyAttachmentTargetEntity); + // List copiedAttachmentIds = + // copiedMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadata( + // appUrl, entityName, facetName, copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // if (targetAttachmentIds.size() == 4) { + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (saveResponse.equals("Could not save entity")) { - fail("Could not save entity"); - } + // @Test + // @Order(41) + // void testCopyAttachmentsUnsuccessfulExistingEntity() throws IOException { + // System.out.println("Test (41): Copy attachments from one entity to another new entity"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String editResponse2 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (editResponse1.equals("Entity in draft mode") + // && editResponse2.equals("Entity in draft mode")) { + // if (sourceObjectIds.size() == 6) { + // int i = 0; + // for (String facetName : facet) { + // List currentFacetObjectIds = + // sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size())); + // currentFacetObjectIds.add("incorrectObjectId"); + // if (currentFacetObjectIds.size() != 3) { + // fail("Not enough object IDs to copy attachments for facet: " + facet); + // } + // try { + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); + // fail("Copy attachments did not throw an error"); + // } catch (IOException e) { + // i += 2; + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - index = 0; - List facetAttachments; - for (String facetName : facet) { - int lambdaIndex = index; - facetAttachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .filter( - item -> - !successfullyRenamedAttachments - .get(lambdaIndex) - .equals(item.get("ID"))) // skip unwanted filename - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - index += 1; - attachments.add(facetAttachments.get(0)); - } + // @Test + // @Order(42) + // void testCreateLinkSuccess() throws IOException { + // System.out.println("Test (42): Create link in entity"); + // List attachments = new ArrayList<>(); - System.out.println("Attachments to be renamed: " + attachments); - String response = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!response.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - index = 0; - for (String facetName : facet) { - api.renameAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(index), "sampleRenamed"); - index += 1; - } + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // for (String facetName : facet) { + // String createLinkResponse1 = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // String createLinkResponse2 = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName + "1", + // linkUrl); + // if (!createLinkResponse1.equals("Link created successfully") + // || !createLinkResponse2.equals("Link created successfully")) { + // fail("Could not create links for facet : " + facetName + createLinkResponse1); + // } + // } - String saveError = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - String expectedWarning = - "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"An object named \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - ObjectMapper mapper = new ObjectMapper(); - assertEquals(mapper.readTree(expectedWarning), mapper.readTree(saveError)); + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - String deleteEntityResponse = api.deleteEntityDraft(appUrl, entityName, createLinkEntity); - if (!deleteEntityResponse.equals("Entity Draft Deleted")) { - fail("Entity draft not deleted"); - } - } + // for (String facetName : facet) { + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String openAttachmentResponse; + // for (String attachment : attachments) { + // openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, createLinkEntity, attachment); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open created link in facet : " + facetName); + // } + // } + // } + // } - @Test - @Order(49) - void testRenameLinkUnsupportedCharacters() throws IOException { - System.out.println( - "Test (46): Rename link in entity fails due to unsupported characters in name"); - List> attachments = new ArrayList<>(); + // @Test + // @Order(43) + // void testCreateLinkDifferentEntity() throws IOException { + // System.out.println("Test (43): Create link with same name in different entity"); - createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // String createLinkDifferentEntity = + // api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkDifferentEntity.equals("Could not edit entity")) { + // fail("Could not create entity"); + // } - String linkName = "sample2"; - String linkUrl = "https://www.example.com"; + // String linkName = "sample"; + // String linkUrl = "https://example.com"; + // for (String facetName : facet) { + // String createResponse = + // api.createLink( + // appUrl, entityName, facetName, createLinkDifferentEntity, linkName, linkUrl); + // if (!createResponse.equals("Link created successfully")) { + // fail("Could not create link in different entity with same name"); + // } + // } - for (String facetName : facet) { - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } - } + // String response = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkDifferentEntity); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // response = api.deleteEntity(appUrl, entityName, createLinkDifferentEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } - for (String facetName : facet) { - attachments.add( - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList())); - } + // @Test + // @Order(44) + // void testCreateLinkFailure() throws IOException { + // System.out.println("Test (41): Create link fails due to invalid URL and name"); + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (editEntityResponse.equals("Could not edit entity")) { + // fail("Could not edit entity"); + // } + // for (String facetName : facet) { + // String linkName = "sample"; + // String linkUrl = "example.com"; + // try { + // String response = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // fail("Create link did not throw an error for invalid url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("400018", errorCode); + // assertTrue( + // errorMessage.equals("Enter a value that is within the expected pattern.") + // || errorMessage.equals("Enter a value that matches the expected pattern."), + // "Unexpected error message: " + errorMessage); + // } + // try { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName + "//", "https://" + + // linkUrl); + // fail("Create link did not throw an error for invalid name"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = + // "\"sample//\" contains unsupported characters (‘/’ or ‘\\’). Rename and try again."; + // assertEquals("500", errorCode); + // assertEquals( + // expected.replaceAll("\\s+", " ").trim(), errorMessage.replaceAll("\\s+", " + // ").trim()); + // } + // try { + // api.createLink(appUrl, entityName, facetName, createLinkEntity, "", ""); + // fail("Create link did not throw an error for empty name and url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = "Provide the missing value."; + // assertEquals("409008", errorCode); + // assertEquals(expected, errorMessage); + // } + // try { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName, "https://" + linkUrl); + // fail("Create link did not throw an error for duplicate name"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals( + // "An object named \"sample\" already exists. Rename the object and try again.", + // errorMessage); + // } + // try { + // for (int i = 2; i < 6; i++) { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName + i, "https://" + + // linkUrl); + // } + // System.out.println("Created 5 links in facet: " + facetName); + // if (!facetName.equals("footnotes")) { + // fail("More than 5 links were created in the same entity"); + // } + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // if (facetName.equals("references")) { + // assertEquals("Cannot upload more than 5 attachments.", errorMessage); + // } else if (facetName.equals("attachments")) { + // assertEquals("Cannot upload more than 4 attachments.", errorMessage); + // } + // } + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } - int index = 0; - for (String facetName : facet) { - api.renameAttachment( - appUrl, - entityName, - facetName, - createLinkEntity, - attachments.get(index).get(0), - "sampleRenamed//"); - index += 1; - } + // response = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } - String error = - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - String expectedError = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - ObjectMapper mapper = new ObjectMapper(); - assertEquals(mapper.readTree(expectedError), mapper.readTree(error)); + // @Test + // @Order(45) + // void testCreateLinkNoSDMRoles() throws IOException { + // System.out.println("Test (42): Create link fails due to no SDM roles assigned"); - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!deleteEntityResponse.equals("Entity Deleted")) { - fail("Entity draft not deleted"); - } - } + // String createLinkEntityNoSDMRoles = + // apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntityNoSDMRoles.equals("Could not edit entity")) { + // fail("Could not create entity"); + // } - @Test - @Order(50) - void testEditLinkSuccess() throws IOException { - System.out.println("Test (47): Edit existing link in entity"); - List> attachmentsPerFacet = new ArrayList<>(); + // for (String facetName : facet) { + // String linkName = "sample27"; + // String linkUrl = "https://example.com"; + // try { + // apiNoRoles.createLink( + // appUrl, entityName, facetName, createLinkEntityNoSDMRoles, linkName, linkUrl); + // fail("Link got created without SDM roles"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals( + // "You do not have the required permissions to upload attachments. Please contact your + // administrator for access.", + // errorMessage); + // } + // } - editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (editLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // String response = + // apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntityNoSDMRoles); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } - for (String facetName : facet) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet: " + facetName); - } - } + // response = api.deleteEntity(appUrl, entityName, createLinkEntityNoSDMRoles); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // @Test + // @Order(46) + // void testDeleteLink() throws IOException { + // System.out.println("Test (43): Delete link in entity"); + // List> attachments = new ArrayList<>(); - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // String createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - for (String facetName : facet) { - List attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // for (String facetName : facet) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet : " + facetName); + // } + // } - if (attachments.isEmpty()) { - fail("Could not find link in facet: " + facetName); - } - attachmentsPerFacet.add(attachments); - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - int index = 0; - for (String facetName : facet) { - String linkId = attachmentsPerFacet.get(index).get(0); - String updatedUrl = "https://editedexample.com"; - String editLinkResponse = - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - if (!editLinkResponse.equals("Link edited successfully")) { - fail("Could not edit link in facet: " + facetName); - } - index++; - } - api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - - int verificationIndex = 0; - for (String facetName : facet) { - List attachmentsInFacet = attachmentsPerFacet.get(verificationIndex); - for (String attachmentId : attachmentsInFacet) { - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, editLinkEntity, attachmentId); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open edited link " + attachmentId + " in facet: " + facetName); - } - } - verificationIndex++; - } - } + // for (String facetName : facet) { + // attachments.add( + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList())); + // } - @Test - @Order(51) - void testEditLinkFailureInvalidURL() throws IOException { - System.out.println("Test (48): Edit existing link with invalid url"); - List> attachmentsPerFacet = new ArrayList<>(); - - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - for (String facetName : facet) { - List attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // int index = 0; + // for (String facetName : facet) { + // String deleteLinkResponse = + // api.deleteAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(index).get(0)); + // System.out.println("Delete response for facet " + facetName + ": " + deleteLinkResponse); + // if (!deleteLinkResponse.equals("Deleted")) { + // fail("Could not delete created link"); + // } + // index += 1; + // } - if (attachments.isEmpty()) { - fail("Could not edit link in facet: " + facetName); - } - attachmentsPerFacet.add(attachments); - } + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - int index = 0; - for (String facetName : facet) { - try { - String linkId = attachmentsPerFacet.get(index).get(0); - String updatedUrl = "https://editedexample"; - index++; - String editLinkResponse = - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - System.out.println("response " + editLinkResponse); - fail("Edit link did not throw an error for invalid url in facet: " + facetName); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("400018", errorCode); - assertTrue( - errorMessage.equals("Enter a value that is within the expected pattern.") - || errorMessage.equals("Enter a value that matches the expected pattern."), - "Unexpected error message: " + errorMessage); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - } + // index = 0; + // attachments.clear(); + // for (String facetName : facet) { + // attachments.add( + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList())); + // System.out.println( + // "Attachments after deletion in facet " + facetName + ": " + attachments.get(index)); + // if (attachments.get(index).size() != 0) { + // fail("Link wasn't deleted"); + // } + // index += 1; + // } - @Test - @Order(52) - void testEditLinkFailureEmptyURL() throws IOException { - System.out.println("Test (49): Edit existing link with an empty url"); - List> attachmentsPerFacet = new ArrayList<>(); - - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // String response = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } - for (String facetName : facet) { - List attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // @Test + // @Order(47) + // void testRenameLinkSuccess() throws IOException { + // System.out.println("Test (44): Rename link in entity"); + // List> attachments = new ArrayList<>(); - if (attachments.isEmpty()) { - fail("Could not edit link in facet: " + facetName); - } - attachmentsPerFacet.add(attachments); - } + // createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - int index = 0; - for (String facetName : facet) { - try { - String linkId = attachmentsPerFacet.get(index).get(0); - String updatedUrl = ""; - index++; - - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - fail("Edit link did not throw an error for empty url in facet: " + facetName); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = "Provide the missing value."; - assertEquals("409008", errorCode); - assertEquals(expected, errorMessage); - } - } - api.deleteEntity(appUrl, entityName, editLinkEntity); - } + // for (String facetName : facet) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } + // } - @Test - @Order(53) - void testEditLinkNoSDMRoles() throws IOException { - System.out.println("Test (50): Edit link fails due to no SDM roles assigned"); + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - Boolean testStatus = false; + // for (String facetName : facet) { + // attachments.add( + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList())); + // } - editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (editLinkEntity.equals("Could not create entity")) { - fail("Could not edit entity"); - } + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - for (String facetName : facet) { - String linkName = "sampleNoRole_" + facetName; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link in facet: " + facetName); - } - } + // int index = 0; + // for (String facetName : facet) { + // successfullyRenamedAttachments.add(attachments.get(index).get(0)); + // String renameLinkResponse = + // api.renameAttachment( + // appUrl, + // entityName, + // facetName, + // createLinkEntity, + // attachments.get(index).get(0), + // "sampleRenamed"); + // if (!renameLinkResponse.equals("Renamed")) { + // fail("Could not Renamed created link"); + // } + // index += 1; + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } + // } - String editEntityResponse = - apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // @Test + // @Order(48) + // void testRenameLinkDuplicate() throws IOException { + // System.out.println("Test (45): Rename link in entity fails due to duplicate error"); + // List attachments = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - for (String facetName : facet) { - List attachments = - apiNoRoles.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // int index = 0; + // for (String facetName : facet) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } + // } - if (attachments.isEmpty()) { - fail("Could not find link in facet: " + facetName); - } + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (saveResponse.equals("Could not save entity")) { + // fail("Could not save entity"); + // } - String linkId = attachments.get(0); - String updatedUrl = "https://www.editedexample.com"; - - try { - apiNoRoles.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - fail("Link got edited without SDM roles in facet: " + facetName); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - - assertEquals("500", errorCode); - assertEquals( - "You do not have the required permissions to update attachments. Kindly contact the admin", - errorMessage); - - testStatus = true; - } - } - api.deleteEntity(appUrl, entityName, editLinkEntity); - if (!testStatus) { - fail("Link got edited without SDM roles"); - } - } + // index = 0; + // List facetAttachments; + // for (String facetName : facet) { + // int lambdaIndex = index; + // facetAttachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .filter( + // item -> + // !successfullyRenamedAttachments + // .get(lambdaIndex) + // .equals(item.get("ID"))) // skip unwanted filename + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // index += 1; + // attachments.add(facetAttachments.get(0)); + // } - @Test - @Order(54) - void testCopyLinkSuccessNewEntity() throws IOException { - System.out.println("Test (51): Copy link from one entity to another new entity"); - List> attachmentsByFacet = new ArrayList<>(); - String linkUrl = "https://www.example.com"; - for (int i = 0; i < facet.length; i++) { - attachmentsByFacet.add(new ArrayList<>()); - } + // System.out.println("Attachments to be renamed: " + attachments); + // String response = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!response.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // index = 0; + // for (String facetName : facet) { + // api.renameAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(index), + // "sampleRenamed"); + // index += 1; + // } - if (copyLinkSourceEntity.equals("Could not create entity") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not create source or target entities"); - } + // String saveError = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // String expectedWarning = + // "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sampleRenamed\\\" already + // exists. Rename the object and try again.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"An object named + // \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: + // attachments\\nPage: + // IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An + // object named \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: + // footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // ObjectMapper mapper = new ObjectMapper(); + // assertEquals(mapper.readTree(expectedWarning), mapper.readTree(saveError)); + + // String deleteEntityResponse = api.deleteEntityDraft(appUrl, entityName, createLinkEntity); + // if (!deleteEntityResponse.equals("Entity Draft Deleted")) { + // fail("Entity draft not deleted"); + // } + // } - for (int i = 0; i < facet.length; i++) { - String linkName = "sample" + i; - String createLinkResponse = - api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet: " + facet[i]); - } - } + // @Test + // @Order(49) + // void testRenameLinkUnsupportedCharacters() throws IOException { + // System.out.println( + // "Test (46): Rename link in entity fails due to unsupported characters in name"); + // List> attachments = new ArrayList<>(); - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - sourceObjectIds.clear(); - for (int i = 0; i < facet.length; i++) { - List objectIds = - api.fetchEntityMetadata(appUrl, entityName, facet[i], copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - sourceObjectIds.addAll(objectIds); - } + // String linkName = "sample2"; + // String linkUrl = "https://www.example.com"; - if (sourceObjectIds.size() != facet.length) { - fail( - "Could not fetch object Ids for all attachments. Expected: " - + facet.length - + ", Found: " - + sourceObjectIds.size()); - } + // for (String facetName : facet) { + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } + // } - int objectIdIndex = 0; - for (String facetName : facet) { - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft for facet: " + facetName); - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); + // for (String facetName : facet) { + // attachments.add( + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList())); + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); - } + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity after copying attachments for facet " + facetName); - } + // int index = 0; + // for (String facetName : facet) { + // api.renameAttachment( + // appUrl, + // entityName, + // facetName, + // createLinkEntity, + // attachments.get(index).get(0), + // "sampleRenamed//"); + // index += 1; + // } - List> attachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); + // String error = + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // String expectedError = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: references\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"sampleRenamed//\\\" + // contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: + // attachments\\nPage: + // IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: footnotes\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // ObjectMapper mapper = new ObjectMapper(); + // assertEquals(mapper.readTree(expectedError), mapper.readTree(error)); + + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!deleteEntityResponse.equals("Entity Deleted")) { + // fail("Entity draft not deleted"); + // } + // } - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // @Test + // @Order(50) + // void testEditLinkSuccess() throws IOException { + // System.out.println("Test (47): Edit existing link in entity"); + // List> attachmentsPerFacet = new ArrayList<>(); - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch in facet " + facetName); - - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); - System.out.println("Attachment type and URL validated for facet " + facetName); - - List attachments = - attachmentsMetadata.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - for (String attachment : attachments) { - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open copied link in facet: " + facetName); - } - } + // editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (editLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - objectIdIndex++; - } + // for (String facetName : facet) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet: " + facetName); + // } + // } - String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - if (!deleteTargetResponse.equals("Entity Deleted")) { - fail("Could not delete target entity"); - } - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - @Test - @Order(55) - void testCopyLinkUnsuccessfulNewEntity() throws IOException { - System.out.println( - "Test (52): Copy invalid type of link from one entity to another new entity"); - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - if (!editResponse.equals("Entity in draft mode") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not edit source entity or create target entity"); - } + // for (String facetName : facet) { + // List attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - sourceObjectIds.add("incorrectObjectId"); + // if (attachments.isEmpty()) { + // fail("Could not find link in facet: " + facetName); + // } + // attachmentsPerFacet.add(attachments); + // } - for (String facetName : facet) { - try { - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); - fail("Copy attachments did not throw an error for facet: " + facetName); - } catch (IOException e) { - System.out.println("Successfully caught expected error for facet: " + facetName); - } - } - api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - } + // int index = 0; + // for (String facetName : facet) { + // String linkId = attachmentsPerFacet.get(index).get(0); + // String updatedUrl = "https://editedexample.com"; + // String editLinkResponse = + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // if (!editLinkResponse.equals("Link edited successfully")) { + // fail("Could not edit link in facet: " + facetName); + // } + // index++; + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + + // int verificationIndex = 0; + // for (String facetName : facet) { + // List attachmentsInFacet = attachmentsPerFacet.get(verificationIndex); + // for (String attachmentId : attachmentsInFacet) { + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, editLinkEntity, attachmentId); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open edited link " + attachmentId + " in facet: " + facetName); + // } + // } + // verificationIndex++; + // } + // } - @Test - @Order(56) - void testCopyLinkFromNewEntityToExistingEntity() throws IOException { - System.out.println("Test (53): Copy link from a new entity to an existing target entity"); + // @Test + // @Order(51) + // void testEditLinkFailureInvalidURL() throws IOException { + // System.out.println("Test (48): Edit existing link with invalid url"); + // List> attachmentsPerFacet = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - List> attachmentsByFacet = new ArrayList<>(); - String linkUrl = "https://www.example.com"; - for (int i = 0; i < facet.length; i++) { - attachmentsByFacet.add(new ArrayList<>()); - } + // for (String facetName : facet) { + // List attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyLinkSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // if (attachments.isEmpty()) { + // fail("Could not edit link in facet: " + facetName); + // } + // attachmentsPerFacet.add(attachments); + // } - for (int i = 0; i < facet.length; i++) { - String linkName = "newsample" + i; - String createLinkResponse = - api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet: " + facet[i]); - } - } + // int index = 0; + // for (String facetName : facet) { + // try { + // String linkId = attachmentsPerFacet.get(index).get(0); + // String updatedUrl = "https://editedexample"; + // index++; + // String editLinkResponse = + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // System.out.println("response " + editLinkResponse); + // fail("Edit link did not throw an error for invalid url in facet: " + facetName); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("400018", errorCode); + // assertTrue( + // errorMessage.equals("Enter a value that is within the expected pattern.") + // || errorMessage.equals("Enter a value that matches the expected pattern."), + // "Unexpected error message: " + errorMessage); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // @Test + // @Order(52) + // void testEditLinkFailureEmptyURL() throws IOException { + // System.out.println("Test (49): Edit existing link with an empty url"); + // List> attachmentsPerFacet = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - sourceObjectIds.clear(); - for (String facetName : facet) { - List objectIds = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - sourceObjectIds.addAll(objectIds); - } + // for (String facetName : facet) { + // List attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - if (sourceObjectIds.isEmpty()) { - fail("Could not fetch object Ids for any attachments"); - } + // if (attachments.isEmpty()) { + // fail("Could not edit link in facet: " + facetName); + // } + // attachmentsPerFacet.add(attachments); + // } - int objectIdIndex = 0; - for (String facetName : facet) { - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft for facet: " + facetName); - } + // int index = 0; + // for (String facetName : facet) { + // try { + // String linkId = attachmentsPerFacet.get(index).get(0); + // String updatedUrl = ""; + // index++; + + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // fail("Edit link did not throw an error for empty url in facet: " + facetName); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = "Provide the missing value."; + // assertEquals("409008", errorCode); + // assertEquals(expected, errorMessage); + // } + // } + // api.deleteEntity(appUrl, entityName, editLinkEntity); + // } - List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); + // @Test + // @Order(53) + // void testEditLinkNoSDMRoles() throws IOException { + // System.out.println("Test (50): Edit link fails due to no SDM roles assigned"); - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); - } + // Boolean testStatus = false; - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity after copying attachments for facet " + facetName); - } + // editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (editLinkEntity.equals("Could not create entity")) { + // fail("Could not edit entity"); + // } - List> attachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); + // for (String facetName : facet) { + // String linkName = "sampleNoRole_" + facetName; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link in facet: " + facetName); + // } + // } - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch in facet " + facetName); - - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); - System.out.println("Attachment type and URL validated for facet " + facetName); - - List attachments = - attachmentsMetadata.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - for (String attachment : attachments) { - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open copied link in facet: " + facetName); - } - } + // String editEntityResponse = + // apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - objectIdIndex++; - } + // for (String facetName : facet) { + // List attachments = + // apiNoRoles.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - } + // if (attachments.isEmpty()) { + // fail("Could not find link in facet: " + facetName); + // } - @Test - @Order(57) - void testCopyInvalidLinkFromNewEntityToExistingEntity() throws IOException { - System.out.println( - "Test (54): Copy invalid type of link from new entity to existing target entity"); - String linkUrl = "https://www.example.com"; + // String linkId = attachments.get(0); + // String updatedUrl = "https://www.editedexample.com"; + + // try { + // apiNoRoles.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // fail("Link got edited without SDM roles in facet: " + facetName); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + + // assertEquals("500", errorCode); + // assertEquals( + // "You do not have the required permissions to update attachments. Kindly contact the + // admin", + // errorMessage); + + // testStatus = true; + // } + // } + // api.deleteEntity(appUrl, entityName, editLinkEntity); + // if (!testStatus) { + // fail("Link got edited without SDM roles"); + // } + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyLinkSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // @Test + // @Order(54) + // void testCopyLinkSuccessNewEntity() throws IOException { + // System.out.println("Test (51): Copy link from one entity to another new entity"); + // List> attachmentsByFacet = new ArrayList<>(); + // String linkUrl = "https://www.example.com"; + // for (int i = 0; i < facet.length; i++) { + // attachmentsByFacet.add(new ArrayList<>()); + // } - for (int i = 0; i < facet.length; i++) { - String linkName = "newsample" + i; - String createLinkResponse = - api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet: " + facet[i]); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit entities"); - } - for (String facetName : facet) { - List sourceObjectIds = new ArrayList<>(); - sourceObjectIds.add("incorrectObjectId"); - try { - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); - fail("Copy attachments did not throw an error for facet: " + facetName); - } catch (IOException e) { - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - } + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - @Test - @Order(58) - void testCopyLinkSuccessNewEntityDraft() throws IOException { - System.out.println("Test (55): Copy link from one entity to another new entity draft mode"); - List> attachmentsByFacet = new ArrayList<>(); - String linkUrl = "https://www.example.com"; - for (int i = 0; i < facet.length; i++) { - attachmentsByFacet.add(new ArrayList<>()); - } + // if (copyLinkSourceEntity.equals("Could not create entity") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not create source or target entities"); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // for (int i = 0; i < facet.length; i++) { + // String linkName = "sample" + i; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet: " + facet[i]); + // } + // } - if (copyLinkSourceEntity.equals("Could not create entity") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not create source or target entities"); - } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - for (int i = 0; i < facet.length; i++) { - String linkName = "sample" + i; - String createLinkResponse = - api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link for facet: " + facet[i]); - } - } + // sourceObjectIds.clear(); + // for (int i = 0; i < facet.length; i++) { + // List objectIds = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // sourceObjectIds.addAll(objectIds); + // } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (sourceObjectIds.size() != facet.length) { + // fail( + // "Could not fetch object Ids for all attachments. Expected: " + // + facet.length + // + ", Found: " + // + sourceObjectIds.size()); + // } - sourceObjectIds.clear(); - for (int i = 0; i < facet.length; i++) { - List objectIds = - api.fetchEntityMetadataDraft(appUrl, entityName, facet[i], copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - sourceObjectIds.addAll(objectIds); - } + // int objectIdIndex = 0; + // for (String facetName : facet) { + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft for facet: " + facetName); + // } - if (sourceObjectIds.size() != facet.length) { - fail( - "Could not fetch object Ids for all attachments. Expected: " - + facet.length - + ", Found: " - + sourceObjectIds.size()); - } + // List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); - int objectIdIndex = 0; - for (String facetName : facet) { - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft for facet: " + facetName); - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); + // } - List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity after copying attachments for facet " + facetName); + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); - } + // List> attachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity after copying attachments for facet " + facetName); - } + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); - List> attachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch in facet " + facetName); - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); + // System.out.println("Attachment type and URL validated for facet " + facetName); - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch in facet " + facetName); - - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); - System.out.println("Attachment type and URL validated for facet " + facetName); - - List attachments = - attachmentsMetadata.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - for (String attachment : attachments) { - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open copied link in facet: " + facetName); - } - } + // List attachments = + // attachmentsMetadata.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - objectIdIndex++; - } + // for (String attachment : attachments) { + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open copied link in facet: " + facetName); + // } + // } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - } + // objectIdIndex++; + // } - @Test - @Order(59) - void testCopyAttachmentsSuccessNewEntityDraft() throws IOException { - System.out.println( - "Test (56): Copy attachments from one entity to another new entity draft mode"); - List> attachments = new ArrayList<>(); - for (int i = 0; i < 3; i++) { - attachments.add(new ArrayList<>()); - } - copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!copyAttachmentSourceEntity.equals("Could not create entity") - && !copyAttachmentTargetEntity.equals("Could not create entity")) { - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample1.pdf").getFile())); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // if (!deleteTargetResponse.equals("Entity Deleted")) { + // fail("Could not delete target entity"); + // } + // } - sourceObjectIds.clear(); + // @Test + // @Order(55) + // void testCopyLinkUnsuccessfulNewEntity() throws IOException { + // System.out.println( + // "Test (52): Copy invalid type of link from one entity to another new entity"); + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - for (int i = 0; i < facet.length; i++) { - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, - entityName, - facet[i], - copyAttachmentSourceEntity, - srvpath, - postData, - file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.get(i).add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } - } - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (int i = 0; i < attachments.size(); i++) { - for (String attachment : attachments.get(i)) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadataDraft( - appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } - } - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } + // if (!editResponse.equals("Entity in draft mode") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not edit source entity or create target entity"); + // } - if (sourceObjectIds.size() == 6) { - String copyResponse; - int i = 0; - for (String facetName : facet) { - if (i != 0) { - String editResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } - } - copyResponse = - api.copyAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size()))); - i += 2; - if (copyResponse.equals("Attachments copied successfully")) { - // Fetch copied attachment IDs from target draft - List> copiedMetadataResponse = - api.fetchEntityMetadataDraft( - appUrl, entityName, facetName, copyAttachmentTargetEntity); - List copiedAttachmentIds = - copiedMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadataDraft( - appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not create entities"); - } - api.deleteEntityDraft(appUrl, entityName, copyAttachmentSourceEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); - } + // sourceObjectIds.add("incorrectObjectId"); - @Test - @Order(60) - void testViewChangelogForNewlyCreatedAttachment() throws IOException { - System.out.println( - "Test (60): View changelog for newly created attachment in all three facets"); + // for (String facetName : facet) { + // try { + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); + // fail("Copy attachments did not throw an error for facet: " + facetName); + // } catch (IOException e) { + // System.out.println("Successfully caught expected error for facet: " + facetName); + // } + // } + // api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // } - for (int i = 0; i < 3; i++) { - String facetName = facet[i]; + // @Test + // @Order(56) + // void testCopyLinkFromNewEntityToExistingEntity() throws IOException { + // System.out.println("Test (53): Copy link from a new entity to an existing target entity"); - // Create a new entity for changelog test - changelogEntityID[i] = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(changelogEntityID[i], "Failed to create changelog test entity"); - assertNotEquals("Could not create entity", changelogEntityID[i]); + // List> attachmentsByFacet = new ArrayList<>(); + // String linkUrl = "https://www.example.com"; + // for (int i = 0; i < facet.length; i++) { + // attachmentsByFacet.add(new ArrayList<>()); + // } - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.txt").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyLinkSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", changelogEntityID[i]); - postData.put("mimeType", "text/plain"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // for (int i = 0; i < facet.length; i++) { + // String linkName = "newsample" + i; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet: " + facet[i]); + // } + // } - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, changelogEntityID[i], srvpath, postData, file); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - changelogAttachmentID[i] = createResponse.get(1); + // sourceObjectIds.clear(); + // for (String facetName : facet) { + // List objectIds = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // sourceObjectIds.addAll(objectIds); + // } - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(changelogAttachmentID[i], "Attachment ID should not be null"); - assertNotEquals("", changelogAttachmentID[i], "Attachment ID should not be empty"); + // if (sourceObjectIds.isEmpty()) { + // fail("Could not fetch object Ids for any attachments"); + // } - // Fetch changelog for the newly created attachment - Map changelogResponse = - api.fetchChangelog( - appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + // int objectIdIndex = 0; + // for (String facetName : facet) { + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft for facet: " + facetName); + // } - assertNotNull(changelogResponse, "Changelog response should not be null"); + // List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); - // Verify changelog structure - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - "sample.txt", changelogResponse.get("filename"), "Filename should match uploaded file"); - assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); - assertEquals(1, changelogResponse.get("numItems"), "Should have 1 changelog entry"); - - // Verify the changelog entry - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); - - Map logEntry = changeLogs.get(0); - assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); - assertNotNull(logEntry.get("time"), "Time should not be null"); - assertNotNull(logEntry.get("user"), "User should not be null"); - assertFalse( - logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); - } - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); + // } - @Test - @Order(61) - void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { - System.out.println( - "Test (61): Modify note field and custom property, then verify changelog shows created + 3 updated entries in all three facets"); + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity after copying attachments for facet " + facetName); + // } - for (int i = 0; i < 3; i++) { - String facetName = facet[i]; + // List> attachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); - // Update attachment with notes field (entity is already in draft mode from test 60) - String notesValue = "Test note for changelog verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - changelogEntityID[i], - changelogAttachmentID[i], - updateNotesBody); - assertEquals("Updated", updateNotesResponse, "Should successfully update notes field"); - - // Update attachment with custom property - Integer customProperty2Value = 12345; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - changelogEntityID[i], - changelogAttachmentID[i], - bodyInt); - assertEquals( - "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch in facet " + facetName); - // Save the entity - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); + // System.out.println("Attachment type and URL validated for facet " + facetName); - // Edit entity again to fetch changelog - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // List attachments = + // attachmentsMetadata.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - // Fetch changelog after modifications - Map changelogResponse = - api.fetchChangelog( - appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + // for (String attachment : attachments) { + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open copied link in facet: " + facetName); + // } + // } - assertNotNull(changelogResponse, "Changelog response should not be null"); + // objectIdIndex++; + // } - // Verify changelog content - should have 1 created + 3 updated (note, customProperty2, and - // internal update) - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - 4, - changelogResponse.get("numItems"), - "Should have 4 changelog entries (1 created + 3 updated)"); + // api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // } - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(4, changeLogs.size(), "Should have exactly 4 changelog entries"); + // @Test + // @Order(57) + // void testCopyInvalidLinkFromNewEntityToExistingEntity() throws IOException { + // System.out.println( + // "Test (54): Copy invalid type of link from new entity to existing target entity"); + // String linkUrl = "https://www.example.com"; - // Verify first entry is 'created' - Map createdEntry = changeLogs.get(0); - assertEquals( - "created", createdEntry.get("operation"), "First entry should be 'created' operation"); - - // Verify remaining entries are 'updated' - long updatedCount = - changeLogs.stream().filter(log -> "updated".equals(log.get("operation"))).count(); - assertEquals(3, updatedCount, "Should have 3 'updated' operations"); - - // Verify that changeDetail exists in updated entries for note field - boolean hasNoteUpdate = - changeLogs.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .anyMatch( - log -> { - @SuppressWarnings("unchecked") - Map changeDetail = - (Map) log.get("changeDetail"); - return changeDetail != null - && "cmis:description".equals(changeDetail.get("field")); - }); - assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); - - // Save the entity so test 62 can edit it - String saveResponseFinal = - api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Saved", saveResponseFinal, "Entity should be saved successfully"); - } - } + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyLinkSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - @Test - @Order(62) - void testChangelogAfterRenamingAttachment() throws IOException { - System.out.println( - "Test (62): Rename attachment and verify changelog increases with rename entry in all three facets"); + // for (int i = 0; i < facet.length; i++) { + // String linkName = "newsample" + i; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet: " + facet[i]); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit entities"); + // } + // for (String facetName : facet) { + // List sourceObjectIds = new ArrayList<>(); + // sourceObjectIds.add("incorrectObjectId"); + // try { + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); + // fail("Copy attachments did not throw an error for facet: " + facetName); + // } catch (IOException e) { + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // } - for (int i = 0; i < 3; i++) { - String facetName = facet[i]; + // @Test + // @Order(58) + // void testCopyLinkSuccessNewEntityDraft() throws IOException { + // System.out.println("Test (55): Copy link from one entity to another new entity draft mode"); + // List> attachmentsByFacet = new ArrayList<>(); + // String linkUrl = "https://www.example.com"; + // for (int i = 0; i < facet.length; i++) { + // attachmentsByFacet.add(new ArrayList<>()); + // } - // Edit entity to put it in draft mode (entity was saved at end of test 61) - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - // Rename the attachment - String newFileName = "renamed_sample.txt"; - String renameResponse = - api.renameAttachment( - appUrl, - entityName, - facetName, - changelogEntityID[i], - changelogAttachmentID[i], - newFileName); - assertEquals("Renamed", renameResponse, "Should successfully rename attachment"); + // if (copyLinkSourceEntity.equals("Could not create entity") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not create source or target entities"); + // } - // Save entity after rename - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Saved", saveResponse, "Entity should be saved successfully after rename"); + // for (int i = 0; i < facet.length; i++) { + // String linkName = "sample" + i; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facet[i], copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link for facet: " + facet[i]); + // } + // } - // Edit entity again and fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - // Fetch changelog after rename - Map changelogAfterRename = - api.fetchChangelog( - appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + // sourceObjectIds.clear(); + // for (int i = 0; i < facet.length; i++) { + // List objectIds = + // api.fetchEntityMetadataDraft(appUrl, entityName, facet[i], + // copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // sourceObjectIds.addAll(objectIds); + // } - assertNotNull(changelogAfterRename, "Changelog response should not be null after rename"); + // if (sourceObjectIds.size() != facet.length) { + // fail( + // "Could not fetch object Ids for all attachments. Expected: " + // + facet.length + // + ", Found: " + // + sourceObjectIds.size()); + // } - // Verify changelog has increased (rename operation adds 1 entry for cmis:name change) - // Expected: 1 created + 3 initial updates + 1 rename update = 5 total - assertEquals( - 5, changelogAfterRename.get("numItems"), "Should have 5 changelog entries after rename"); + // int objectIdIndex = 0; + // for (String facetName : facet) { + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft for facet: " + facetName); + // } - @SuppressWarnings("unchecked") - List> changeLogsAfterRename = - (List>) changelogAfterRename.get("changeLogs"); - assertEquals( - 5, changeLogsAfterRename.size(), "Should have exactly 5 changelog entries after rename"); - - // Verify updated count is 4 (3 initial + 1 from rename operation) - long updatedCountAfterRename = - changeLogsAfterRename.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .count(); - assertEquals(4, updatedCountAfterRename, "Should have 4 'updated' operations after rename"); - - // Verify filename change in changelog - boolean hasFilenameUpdate = - changeLogsAfterRename.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .anyMatch( - log -> { - @SuppressWarnings("unchecked") - Map changeDetail = - (Map) log.get("changeDetail"); - return changeDetail != null && "cmis:name".equals(changeDetail.get("field")); - }); - assertTrue(hasFilenameUpdate, "Should have an update entry for filename (cmis:name)"); - - // Cleanup - entity was saved after rename, so delete the active entity - api.deleteEntity(appUrl, entityName, changelogEntityID[i]); - } - } + // List subListToCopy = sourceObjectIds.subList(objectIdIndex, objectIdIndex + 1); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, subListToCopy); - @Test - @Order(63) - void testChangelogWithCustomPropertyEditSave() throws IOException { - System.out.println( - "Test (63): Create entity with custom property, save, edit and save again - verify changelog remains at 3 entries in all three facets"); + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachments for facet " + facetName + ": " + copyResponse); + // } - for (int i = 0; i < 3; i++) { - String facetName = facet[i]; + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity after copying attachments for facet " + facetName); + // } - // Create a new entity - String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(newEntityID, "Failed to create new entity"); - assertNotEquals("Could not create entity", newEntityID); + // List> attachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", newEntityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch in facet " + facetName); - List createResponse = - api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, file); - - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - String attachmentID = createResponse.get(1); - - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(attachmentID, "Attachment ID should not be null"); - assertNotEquals("", attachmentID, "Attachment ID should not be empty"); - - // Add a custom property - Integer customPropertyValue = 99999; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customPropertyValue + "}", - MediaType.parse("application/json")); - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, newEntityID, attachmentID, bodyInt); - assertEquals( - "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch in facet " + facetName); + // System.out.println("Attachment type and URL validated for facet " + facetName); - // Save the entity - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // List attachments = + // attachmentsMetadata.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - // Edit entity to fetch initial changelog - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // for (String attachment : attachments) { + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachment); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open copied link in facet: " + facetName); + // } + // } - // Fetch changelog after initial save - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + // objectIdIndex++; + // } - assertNotNull(changelogResponse, "Changelog response should not be null"); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // } - // Verify changelog has 3 entries: 1 created + 2 updated (cmis:secondaryObjectTypeIds + - // customProperty2) - assertEquals( - 3, changelogResponse.get("numItems"), "Should have 3 changelog entries initially"); + // @Test + // @Order(59) + // void testCopyAttachmentsSuccessNewEntityDraft() throws IOException { + // System.out.println( + // "Test (56): Copy attachments from one entity to another new entity draft mode"); + // List> attachments = new ArrayList<>(); + // for (int i = 0; i < 3; i++) { + // attachments.add(new ArrayList<>()); + // } + // copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!copyAttachmentSourceEntity.equals("Could not create entity") + // && !copyAttachmentTargetEntity.equals("Could not create entity")) { + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample1.pdf").getFile())); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(3, changeLogs.size(), "Should have exactly 3 changelog entries"); + // sourceObjectIds.clear(); + + // for (int i = 0; i < facet.length; i++) { + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facet[i], + // copyAttachmentSourceEntity, + // srvpath, + // postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.get(i).add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } + // } + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (int i = 0; i < attachments.size(); i++) { + // for (String attachment : attachments.get(i)) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadataDraft( + // appUrl, entityName, facet[i], copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } + // } + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } - // Save entity again without any modifications - saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + // if (sourceObjectIds.size() == 6) { + // String copyResponse; + // int i = 0; + // for (String facetName : facet) { + // if (i != 0) { + // String editResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } + // } + // copyResponse = + // api.copyAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // sourceObjectIds.subList(i, Math.min(i + 2, sourceObjectIds.size()))); + // i += 2; + // if (copyResponse.equals("Attachments copied successfully")) { + // // Fetch copied attachment IDs from target draft + // List> copiedMetadataResponse = + // api.fetchEntityMetadataDraft( + // appUrl, entityName, facetName, copyAttachmentTargetEntity); + // List copiedAttachmentIds = + // copiedMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadataDraft( + // appUrl, entityName, facetName, copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not create entities"); + // } + // api.deleteEntityDraft(appUrl, entityName, copyAttachmentSourceEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); + // } - // Edit entity again and fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // @Test + // @Order(60) + // void testViewChangelogForNewlyCreatedAttachment() throws IOException { + // System.out.println( + // "Test (60): View changelog for newly created attachment in all three facets"); - // Fetch changelog after second save - Map changelogAfterSecondSave = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + // for (int i = 0; i < 3; i++) { + // String facetName = facet[i]; - assertNotNull( - changelogAfterSecondSave, "Changelog response should not be null after second save"); + // // Create a new entity for changelog test + // changelogEntityID[i] = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(changelogEntityID[i], "Failed to create changelog test entity"); + // assertNotEquals("Could not create entity", changelogEntityID[i]); - // Verify changelog still has only 3 entries (no new entries added) - assertEquals( - 3, - changelogAfterSecondSave.get("numItems"), - "Should still have only 3 changelog entries after edit-save without modifications"); + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.txt").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - @SuppressWarnings("unchecked") - List> changeLogsAfterSecondSave = - (List>) changelogAfterSecondSave.get("changeLogs"); - assertEquals( - 3, - changeLogsAfterSecondSave.size(), - "Should still have exactly 3 changelog entries after second save"); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", changelogEntityID[i]); + // postData.put("mimeType", "text/plain"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Clean up the entity - api.deleteEntity(appUrl, entityName, newEntityID); - } - } + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, changelogEntityID[i], srvpath, postData, file); + + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // changelogAttachmentID[i] = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(changelogAttachmentID[i], "Attachment ID should not be null"); + // assertNotEquals("", changelogAttachmentID[i], "Attachment ID should not be empty"); + + // // Fetch changelog for the newly created attachment + // Map changelogResponse = + // api.fetchChangelog( + // appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog structure + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // "sample.txt", changelogResponse.get("filename"), "Filename should match uploaded + // file"); + // assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); + // assertEquals(1, changelogResponse.get("numItems"), "Should have 1 changelog entry"); + + // // Verify the changelog entry + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); + + // Map logEntry = changeLogs.get(0); + // assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); + // assertNotNull(logEntry.get("time"), "Time should not be null"); + // assertNotNull(logEntry.get("user"), "User should not be null"); + // assertFalse( + // logEntry.containsKey("changeDetail"), "Created operation should not have + // changeDetail"); + // } + // } - @Test - @Order(64) - void testChangelogForSavedAttachmentWithoutModification() throws IOException { - System.out.println( - "Test (64): Create entity, upload attachment, save, edit and save again - verify changelog still has only 'created' entry in all three facets"); + // @Test + // @Order(61) + // void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { + // System.out.println( + // "Test (61): Modify note field and custom property, then verify changelog shows created + + // 3 updated entries in all three facets"); + + // for (int i = 0; i < 3; i++) { + // String facetName = facet[i]; + + // // Update attachment with notes field (entity is already in draft mode from test 60) + // String notesValue = "Test note for changelog verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // changelogEntityID[i], + // changelogAttachmentID[i], + // updateNotesBody); + // assertEquals("Updated", updateNotesResponse, "Should successfully update notes field"); + + // // Update attachment with custom property + // Integer customProperty2Value = 12345; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // changelogEntityID[i], + // changelogAttachmentID[i], + // bodyInt); + // assertEquals( + // "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + + // // Save the entity + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // changelogEntityID[i]); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity again to fetch changelog + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // changelogEntityID[i]); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after modifications + // Map changelogResponse = + // api.fetchChangelog( + // appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog content - should have 1 created + 3 updated (note, customProperty2, and + // // internal update) + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // 4, + // changelogResponse.get("numItems"), + // "Should have 4 changelog entries (1 created + 3 updated)"); + + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(4, changeLogs.size(), "Should have exactly 4 changelog entries"); + + // // Verify first entry is 'created' + // Map createdEntry = changeLogs.get(0); + // assertEquals( + // "created", createdEntry.get("operation"), "First entry should be 'created' operation"); + + // // Verify remaining entries are 'updated' + // long updatedCount = + // changeLogs.stream().filter(log -> "updated".equals(log.get("operation"))).count(); + // assertEquals(3, updatedCount, "Should have 3 'updated' operations"); + + // // Verify that changeDetail exists in updated entries for note field + // boolean hasNoteUpdate = + // changeLogs.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .anyMatch( + // log -> { + // @SuppressWarnings("unchecked") + // Map changeDetail = + // (Map) log.get("changeDetail"); + // return changeDetail != null + // && "cmis:description".equals(changeDetail.get("field")); + // }); + // assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); + + // // Save the entity so test 62 can edit it + // String saveResponseFinal = + // api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); + // assertEquals("Saved", saveResponseFinal, "Entity should be saved successfully"); + // } + // } - for (int i = 0; i < 3; i++) { - String facetName = facet[i]; + // @Test + // @Order(62) + // void testChangelogAfterRenamingAttachment() throws IOException { + // System.out.println( + // "Test (62): Rename attachment and verify changelog increases with rename entry in all + // three facets"); + + // for (int i = 0; i < 3; i++) { + // String facetName = facet[i]; + + // // Edit entity to put it in draft mode (entity was saved at end of test 61) + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // changelogEntityID[i]); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Rename the attachment + // String newFileName = "renamed_sample.txt"; + // String renameResponse = + // api.renameAttachment( + // appUrl, + // entityName, + // facetName, + // changelogEntityID[i], + // changelogAttachmentID[i], + // newFileName); + // assertEquals("Renamed", renameResponse, "Should successfully rename attachment"); + + // // Save entity after rename + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // changelogEntityID[i]); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully after rename"); + + // // Edit entity again and fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID[i]); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after rename + // Map changelogAfterRename = + // api.fetchChangelog( + // appUrl, entityName, facetName, changelogEntityID[i], changelogAttachmentID[i]); + + // assertNotNull(changelogAfterRename, "Changelog response should not be null after rename"); + + // // Verify changelog has increased (rename operation adds 1 entry for cmis:name change) + // // Expected: 1 created + 3 initial updates + 1 rename update = 5 total + // assertEquals( + // 5, changelogAfterRename.get("numItems"), "Should have 5 changelog entries after + // rename"); + + // @SuppressWarnings("unchecked") + // List> changeLogsAfterRename = + // (List>) changelogAfterRename.get("changeLogs"); + // assertEquals( + // 5, changeLogsAfterRename.size(), "Should have exactly 5 changelog entries after + // rename"); + + // // Verify updated count is 4 (3 initial + 1 from rename operation) + // long updatedCountAfterRename = + // changeLogsAfterRename.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .count(); + // assertEquals(4, updatedCountAfterRename, "Should have 4 'updated' operations after + // rename"); + + // // Verify filename change in changelog + // boolean hasFilenameUpdate = + // changeLogsAfterRename.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .anyMatch( + // log -> { + // @SuppressWarnings("unchecked") + // Map changeDetail = + // (Map) log.get("changeDetail"); + // return changeDetail != null && "cmis:name".equals(changeDetail.get("field")); + // }); + // assertTrue(hasFilenameUpdate, "Should have an update entry for filename (cmis:name)"); + + // // Cleanup - entity was saved after rename, so delete the active entity + // api.deleteEntity(appUrl, entityName, changelogEntityID[i]); + // } + // } - // Create a new entity - String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(newEntityID, "Failed to create new entity"); - assertNotEquals("Could not create entity", newEntityID); + // @Test + // @Order(63) + // void testChangelogWithCustomPropertyEditSave() throws IOException { + // System.out.println( + // "Test (63): Create entity with custom property, save, edit and save again - verify + // changelog remains at 3 entries in all three facets"); - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // for (int i = 0; i < 3; i++) { + // String facetName = facet[i]; - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", newEntityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Create a new entity + // String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(newEntityID, "Failed to create new entity"); + // assertNotEquals("Could not create entity", newEntityID); - List createResponse = - api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, file); + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - String newAttachmentID = createResponse.get(1); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", newEntityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(newAttachmentID, "Attachment ID should not be null"); - assertNotEquals("", newAttachmentID, "Attachment ID should not be empty"); + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, + // file); - // Save the entity immediately without any modifications - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // String attachmentID = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(attachmentID, "Attachment ID should not be null"); + // assertNotEquals("", attachmentID, "Attachment ID should not be empty"); + + // // Add a custom property + // Integer customPropertyValue = 99999; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customPropertyValue + "}", + // MediaType.parse("application/json")); + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, newEntityID, attachmentID, bodyInt); + // assertEquals( + // "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + + // // Save the entity + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity to fetch initial changelog + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after initial save + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog has 3 entries: 1 created + 2 updated (cmis:secondaryObjectTypeIds + + // // customProperty2) + // assertEquals( + // 3, changelogResponse.get("numItems"), "Should have 3 changelog entries initially"); + + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(3, changeLogs.size(), "Should have exactly 3 changelog entries"); + + // // Save entity again without any modifications + // saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + + // // Edit entity again and fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after second save + // Map changelogAfterSecondSave = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + + // assertNotNull( + // changelogAfterSecondSave, "Changelog response should not be null after second save"); + + // // Verify changelog still has only 3 entries (no new entries added) + // assertEquals( + // 3, + // changelogAfterSecondSave.get("numItems"), + // "Should still have only 3 changelog entries after edit-save without modifications"); + + // @SuppressWarnings("unchecked") + // List> changeLogsAfterSecondSave = + // (List>) changelogAfterSecondSave.get("changeLogs"); + // assertEquals( + // 3, + // changeLogsAfterSecondSave.size(), + // "Should still have exactly 3 changelog entries after second save"); + + // // Clean up the entity + // api.deleteEntity(appUrl, entityName, newEntityID); + // } + // } - // Edit entity again without making any changes to the attachment - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // @Test + // @Order(64) + // void testChangelogForSavedAttachmentWithoutModification() throws IOException { + // System.out.println( + // "Test (64): Create entity, upload attachment, save, edit and save again - verify + // changelog still has only 'created' entry in all three facets"); - // Save entity again without modifying the attachment - saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + // for (int i = 0; i < 3; i++) { + // String facetName = facet[i]; - // Edit entity to fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // // Create a new entity + // String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(newEntityID, "Failed to create new entity"); + // assertNotEquals("Could not create entity", newEntityID); - // Fetch changelog for the attachment - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, newAttachmentID); + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - assertNotNull(changelogResponse, "Changelog response should not be null"); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", newEntityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Verify changelog content - should only have 'created' entry even after edit and save - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - "sample.pdf", changelogResponse.get("filename"), "Filename should match uploaded file"); - assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); - assertEquals(1, changelogResponse.get("numItems"), "Should have only 1 changelog entry"); - - // Verify the changelog entry - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); - - Map logEntry = changeLogs.get(0); - assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); - assertNotNull(logEntry.get("time"), "Time should not be null"); - assertNotNull(logEntry.get("user"), "User should not be null"); - assertFalse( - logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); - - // Clean up the new entity - api.deleteEntity(appUrl, entityName, newEntityID); - } - } + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, + // file); - @Test - @Order(65) - void testMoveAttachmentsWithSourceFacet() throws IOException { - System.out.println( - "Test (65): Move attachments from Source Entity to Target Entity with sourceFacet"); + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // String newAttachmentID = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(newAttachmentID, "Attachment ID should not be null"); + // assertNotEquals("", newAttachmentID, "Attachment ID should not be empty"); + + // // Save the entity immediately without any modifications + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity again without making any changes to the attachment + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Save entity again without modifying the attachment + // saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + + // // Edit entity to fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog for the attachment + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, newAttachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog content - should only have 'created' entry even after edit and save + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // "sample.pdf", changelogResponse.get("filename"), "Filename should match uploaded + // file"); + // assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); + // assertEquals(1, changelogResponse.get("numItems"), "Should have only 1 changelog entry"); + + // // Verify the changelog entry + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); + + // Map logEntry = changeLogs.get(0); + // assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); + // assertNotNull(logEntry.get("time"), "Time should not be null"); + // assertNotNull(logEntry.get("user"), "User should not be null"); + // assertFalse( + // logEntry.containsKey("changeDetail"), "Created operation should not have + // changeDetail"); + + // // Clean up the new entity + // api.deleteEntity(appUrl, entityName, newEntityID); + // } + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // @Test + // @Order(65) + // void testMoveAttachmentsWithSourceFacet() throws IOException { + // System.out.println( + // "Test (65): Move attachments from Source Entity to Target Entity with sourceFacet"); - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); - files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); + // files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity"); - } + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity"); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - // Save target before move - String saveTargetBeforeMoveTest65 = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveTest65.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveTest65); - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Save target before move + // String saveTargetBeforeMoveTest65 = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveTest65.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveTest65); + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals( - sourceAttachmentIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all attachments after move"); + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - 0, sourceMetadataAfterMove.size(), "Source entity should have no attachments after move"); + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals( + // sourceAttachmentIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all attachments after move"); + + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // 0, sourceMetadataAfterMove.size(), "Source entity should have no attachments after + // move"); + + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // @Test + // @Order(66) + // public void testMoveAttachmentsToEntityWithDuplicateWithSourceFacet() throws Exception { + // System.out.println( + // "Test (66): Move attachments to entity with duplicate attachment with sourceFacet"); - @Test - @Order(66) - public void testMoveAttachmentsToEntityWithDuplicateWithSourceFacet() throws Exception { - System.out.println( - "Test (66): Move attachments to entity with duplicate attachment with sourceFacet"); + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity"); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity"); - } + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // Map targetPostData = new HashMap<>(); + // targetPostData.put("up__ID", moveTargetEntity); + // targetPostData.put("mimeType", "application/pdf"); + // targetPostData.put("createdAt", new Date().toString()); + // targetPostData.put("createdBy", "test@test.com"); + // targetPostData.put("modifiedBy", "test@test.com"); + + // File duplicateFile = new File(classLoader.getResource("sample.pdf").getFile()); + // List targetCreateResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // srvpath, + // targetPostData, + // duplicateFile); + + // if (!targetCreateResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment on target entity"); + // } - Map targetPostData = new HashMap<>(); - targetPostData.put("up__ID", moveTargetEntity); - targetPostData.put("mimeType", "application/pdf"); - targetPostData.put("createdAt", new Date().toString()); - targetPostData.put("createdBy", "test@test.com"); - targetPostData.put("modifiedBy", "test@test.com"); + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - File duplicateFile = new File(classLoader.getResource("sample.pdf").getFile()); - List targetCreateResponse = - api.createAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - srvpath, - targetPostData, - duplicateFile); + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // int targetCountBeforeMove = targetMetadataBeforeMove.size(); + + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - if (!targetCreateResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment on target entity"); - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + + // int expectedTargetCount = targetCountBeforeMove + (sourceAttachmentIds.size() - 1); + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target should have duplicate skipped, other attachments moved"); + + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // int expectedSourceCount = + // sourceAttachmentIds.size() - (targetMetadataAfterMove.size() - targetCountBeforeMove); + // assertEquals( + // expectedSourceCount, + // sourceMetadataAfterMove.size(), + // "Source should have duplicate attachment remaining"); + + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // @Test + // @Order(67) + // public void testMoveAttachmentsWithNotesAndSecondaryProperties() throws Exception { + // System.out.println( + // "Test (67): Move attachments with notes and secondary properties with sourceFacet"); - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - int targetCountBeforeMove = targetMetadataBeforeMove.size(); + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - int expectedTargetCount = targetCountBeforeMove + (sourceAttachmentIds.size() - 1); - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target should have duplicate skipped, other attachments moved"); - - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - int expectedSourceCount = - sourceAttachmentIds.size() - (targetMetadataAfterMove.size() - targetCountBeforeMove); - assertEquals( - expectedSourceCount, - sourceMetadataAfterMove.size(), - "Source should have duplicate attachment remaining"); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // String notesValue = "Test note for verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, attachmentId, updateNotesBody); + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update notes for attachment: " + attachmentId); + // } + // } - @Test - @Order(67) - public void testMoveAttachmentsWithNotesAndSecondaryProperties() throws Exception { - System.out.println( - "Test (67): Move attachments with notes and secondary properties with sourceFacet"); + // Integer customProperty2Value = 54321; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, attachmentId, bodyInt); + // if (!updateCustomPropertyResponse.equals("Updated")) { + // fail("Could not update custom property for attachment: " + attachmentId); + // } + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - String notesValue = "Test note for verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); - - for (String attachmentId : sourceAttachmentIds) { - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, attachmentId, updateNotesBody); - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update notes for attachment: " + attachmentId); - } - } + // // Save target before move + // String saveTargetBeforeMoveTest67 = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveTest67.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveTest67); + // } - Integer customProperty2Value = 54321; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - - for (String attachmentId : sourceAttachmentIds) { - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, attachmentId, bodyInt); - if (!updateCustomPropertyResponse.equals("Updated")) { - fail("Could not update custom property for attachment: " + attachmentId); - } - } + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals( + // sourceAttachmentIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all attachments after move"); + + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, + // targetAttachmentId); + + // if (detailedMetadata.containsKey("note")) { + // assertEquals( + // notesValue, + // detailedMetadata.get("note"), + // "Notes should be preserved after move for attachment: " + targetAttachmentId); + // } else { + // fail("Notes property missing after move for attachment: " + targetAttachmentId); + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // if (detailedMetadata.containsKey("customProperty2")) { + // assertEquals( + // customProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Custom property should be preserved after move for attachment: " + // + targetAttachmentId); + // } else { + // fail("Custom property missing after move for attachment: " + targetAttachmentId); + // } + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // 0, sourceMetadataAfterMove.size(), "Source entity has no attachments after move"); - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - // Save target before move - String saveTargetBeforeMoveTest67 = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveTest67.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveTest67); - } + // @Test + // @Order(68) + // public void testMoveAttachmentsWithoutSourceFacet() throws Exception { + // System.out.println( + // "Test (68): Move valid attachments from Source Entity to Target Entity without + // sourceFacet"); - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals( - sourceAttachmentIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all attachments after move"); - - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, targetAttachmentId); - - if (detailedMetadata.containsKey("note")) { - assertEquals( - notesValue, - detailedMetadata.get("note"), - "Notes should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Notes property missing after move for attachment: " + targetAttachmentId); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - if (detailedMetadata.containsKey("customProperty2")) { - assertEquals( - customProperty2Value, - detailedMetadata.get("customProperty2"), - "Custom property should be preserved after move for attachment: " - + targetAttachmentId); - } else { - fail("Custom property missing after move for attachment: " + targetAttachmentId); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - 0, sourceMetadataAfterMove.size(), "Source entity has no attachments after move"); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - @Test - @Order(68) - public void testMoveAttachmentsWithoutSourceFacet() throws Exception { - System.out.println( - "Test (68): Move valid attachments from Source Entity to Target Entity without sourceFacet"); + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals( + // moveObjectIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all moved attachments"); + + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // String readResponse = + // api.readAttachment(appUrl, entityName, facet[i], moveTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read moved attachment from target entity"); + // } + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } else { - fail("Attachment metadata does not contain objectId"); - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // moveObjectIds.size(), + // sourceMetadataAfterMove.size(), + // "Source entity should still have attachments in UI when sourceFacet is not specified"); + + // for (Map metadata : sourceMetadataAfterMove) { + // String objectId = (String) metadata.get("objectId"); + // assertTrue( + // moveObjectIds.contains(objectId), + // "Source entity should still show attachment with objectId: " + objectId); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // @Test + // @Order(69) + // public void testMoveAttachmentsToEntityWithDuplicateWithoutSourceFacet() throws Exception { + // System.out.println( + // "Test (69): Move attachments into existing Target Entity when duplicate exists without + // sourceFacet"); - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals( - moveObjectIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all moved attachments"); - - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - String readResponse = - api.readAttachment(appUrl, entityName, facet[i], moveTargetEntity, targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read moved attachment from target entity"); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - moveObjectIds.size(), - sourceMetadataAfterMove.size(), - "Source entity should still have attachments in UI when sourceFacet is not specified"); - - for (Map metadata : sourceMetadataAfterMove) { - String objectId = (String) metadata.get("objectId"); - assertTrue( - moveObjectIds.contains(objectId), - "Source entity should still show attachment with objectId: " + objectId); - } + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - @Test - @Order(69) - public void testMoveAttachmentsToEntityWithDuplicateWithoutSourceFacet() throws Exception { - System.out.println( - "Test (69): Move attachments into existing Target Entity when duplicate exists without sourceFacet"); + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // Map targetPostData = new HashMap<>(); + // targetPostData.put("up__ID", moveTargetEntity); + // targetPostData.put("mimeType", "application/pdf"); + // targetPostData.put("createdAt", new Date().toString()); + // targetPostData.put("createdBy", "test@test.com"); + // targetPostData.put("modifiedBy", "test@test.com"); + + // List createTargetResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // srvpath, + // targetPostData, + // files.get(0)); + // if (!createTargetResponse.get(0).equals("Attachment created")) { + // fail("Could not create duplicate attachment in target entity"); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity: " + saveTargetResponse); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // int initialTargetCount = targetMetadataBeforeMove.size(); + + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } else { - fail("Attachment metadata does not contain objectId"); - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // int nonDuplicateCount = moveObjectIds.size() - 1; + // int expectedTargetCount = initialTargetCount + nonDuplicateCount; - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target entity should have initial attachments plus non-duplicate moved attachments"); - Map targetPostData = new HashMap<>(); - targetPostData.put("up__ID", moveTargetEntity); - targetPostData.put("mimeType", "application/pdf"); - targetPostData.put("createdAt", new Date().toString()); - targetPostData.put("createdBy", "test@test.com"); - targetPostData.put("modifiedBy", "test@test.com"); + // assertTrue( + // targetMetadataAfterMove.size() > initialTargetCount, + // "Target should have more attachments after move (non-duplicates added)"); - List createTargetResponse = - api.createAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - srvpath, - targetPostData, - files.get(0)); - if (!createTargetResponse.get(0).equals("Attachment created")) { - fail("Could not create duplicate attachment in target entity"); - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // moveObjectIds.size(), + // sourceMetadataAfterMove.size(), + // "Source entity should still have all attachments in UI when sourceFacet is not + // specified"); - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity: " + saveTargetResponse); - } + // List sourceObjectIds = new ArrayList<>(); + // for (Map metadata : sourceMetadataAfterMove) { + // sourceObjectIds.add((String) metadata.get("objectId")); + // } + // for (String objectId : moveObjectIds) { + // assertTrue( + // sourceObjectIds.contains(objectId), + // "Source entity should still show attachment with objectId: " + objectId); + // } - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - int initialTargetCount = targetMetadataBeforeMove.size(); + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // @Test + // @Order(70) + // public void testMoveAttachmentsWithNotesAndSecondaryPropertiesWithoutSourceFacet() + // throws Exception { + // System.out.println( + // "Test (70): Move attachments with notes and secondary properties without sourceFacet"); - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - int nonDuplicateCount = moveObjectIds.size() - 1; - int expectedTargetCount = initialTargetCount + nonDuplicateCount; + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target entity should have initial attachments plus non-duplicate moved attachments"); + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertTrue( - targetMetadataAfterMove.size() > initialTargetCount, - "Target should have more attachments after move (non-duplicates added)"); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - moveObjectIds.size(), - sourceMetadataAfterMove.size(), - "Source entity should still have all attachments in UI when sourceFacet is not specified"); + // String notesValue = "Test note for migration verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, attachmentId, updateNotesBody); + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update notes for attachment: " + attachmentId); + // } + // } - List sourceObjectIds = new ArrayList<>(); - for (Map metadata : sourceMetadataAfterMove) { - sourceObjectIds.add((String) metadata.get("objectId")); - } - for (String objectId : moveObjectIds) { - assertTrue( - sourceObjectIds.contains(objectId), - "Source entity should still show attachment with objectId: " + objectId); - } + // Integer customProperty2Value = 54321; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, attachmentId, bodyInt); + // if (!updateCustomPropertyResponse.equals("Updated")) { + // fail("Could not update custom property for attachment: " + attachmentId); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - @Test - @Order(70) - public void testMoveAttachmentsWithNotesAndSecondaryPropertiesWithoutSourceFacet() - throws Exception { - System.out.println( - "Test (70): Move attachments with notes and secondary properties without sourceFacet"); + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // List> sourceMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - String notesValue = "Test note for migration verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); - - for (String attachmentId : sourceAttachmentIds) { - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, attachmentId, updateNotesBody); - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update notes for attachment: " + attachmentId); - } - } + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // int targetCountBeforeMove = targetMetadataBeforeMove.size(); + + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - Integer customProperty2Value = 54321; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - - for (String attachmentId : sourceAttachmentIds) { - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, attachmentId, bodyInt); - if (!updateCustomPropertyResponse.equals("Updated")) { - fail("Could not update custom property for attachment: " + attachmentId); - } - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // int expectedTargetCount = targetCountBeforeMove + sourceAttachmentIds.size(); + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target entity should have " + expectedTargetCount + " attachments after move"); + + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, + // targetAttachmentId); + + // if (detailedMetadata.containsKey("note")) { + // assertEquals( + // notesValue, + // detailedMetadata.get("note"), + // "Notes should be preserved after move for attachment: " + targetAttachmentId); + // } else { + // fail("Notes property missing after move for attachment: " + targetAttachmentId); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // if (detailedMetadata.containsKey("customProperty2")) { + // assertEquals( + // customProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Custom property should be preserved after move for attachment: " + // + targetAttachmentId); + // } else { + // fail("Custom property missing after move for attachment: " + targetAttachmentId); + // } + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // sourceCountBeforeMove, + // sourceMetadataAfterMove.size(), + // "Source entity should still have " + // + sourceCountBeforeMove + // + " attachments (without sourceFacet)"); + + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // @Test + // @Order(71) + // public void testMoveAttachmentsWithInvalidOrUndefinedSecondaryProperties() throws Exception { + // System.out.println( + // "Test (71): Move attachments with invalid or undefined secondary properties"); - List> sourceMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); + // files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - int targetCountBeforeMove = targetMetadataBeforeMove.size(); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // String validAttachmentId = sourceAttachmentIds.get(0); + // Integer validCustomProperty2Value = 12345; + // RequestBody validPropertyBody = + // RequestBody.create( + // "{\"customProperty2\": " + validCustomProperty2Value + "}", + // MediaType.parse("application/json")); + + // String validPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, validAttachmentId, + // validPropertyBody); + // if (!validPropertyResponse.equals("Updated")) { + // fail("Could not update valid property for attachment: " + validAttachmentId); + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - int expectedTargetCount = targetCountBeforeMove + sourceAttachmentIds.size(); - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target entity should have " + expectedTargetCount + " attachments after move"); - - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, targetAttachmentId); - - if (detailedMetadata.containsKey("note")) { - assertEquals( - notesValue, - detailedMetadata.get("note"), - "Notes should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Notes property missing after move for attachment: " + targetAttachmentId); - } + // String invalidAttachmentId = sourceAttachmentIds.get(1); + // RequestBody invalidPropertyBody = + // RequestBody.create( + // "{\"nonExistentProperty\": \"invalid\"}", MediaType.parse("application/json")); + + // api.updateSecondaryProperty( + // appUrl, entityName, facet[i], moveSourceEntity, invalidAttachmentId, + // invalidPropertyBody); + + // String undefinedAttachmentId = sourceAttachmentIds.get(2); + // RequestBody undefinedPropertyBody = + // RequestBody.create( + // "{\"undefinedField\": \"test\", \"anotherUndefined\": 999}", + // MediaType.parse("application/json")); + + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facet[i], + // moveSourceEntity, + // undefinedAttachmentId, + // undefinedPropertyBody); + + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - if (detailedMetadata.containsKey("customProperty2")) { - assertEquals( - customProperty2Value, - detailedMetadata.get("customProperty2"), - "Custom property should be preserved after move for attachment: " - + targetAttachmentId); - } else { - fail("Custom property missing after move for attachment: " + targetAttachmentId); - } - } + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - sourceCountBeforeMove, - sourceMetadataAfterMove.size(), - "Source entity should still have " - + sourceCountBeforeMove - + " attachments (without sourceFacet)"); - - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - @Test - @Order(71) - public void testMoveAttachmentsWithInvalidOrUndefinedSecondaryProperties() throws Exception { - System.out.println( - "Test (71): Move attachments with invalid or undefined secondary properties"); + // List> sourceMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); - files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); + // // Save target before move + // String saveTargetBeforeMoveResponseTest72 = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponseTest72.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveResponseTest72); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + + // assertTrue( + // targetMetadataAfterMove.size() > 0, "Target entity should have attachments after + // move"); + // assertEquals( + // sourceCountBeforeMove, + // targetMetadataAfterMove.size(), + // "All attachments should move (invalid properties are ignored)"); + + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, + // targetAttachmentId); + + // if (detailedMetadata.containsKey("customProperty2") + // && detailedMetadata.get("customProperty2") != null) { + // assertEquals( + // validCustomProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Valid customProperty2 should be preserved"); + // } + // } - String validAttachmentId = sourceAttachmentIds.get(0); - Integer validCustomProperty2Value = 12345; - RequestBody validPropertyBody = - RequestBody.create( - "{\"customProperty2\": " + validCustomProperty2Value + "}", - MediaType.parse("application/json")); - - String validPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, validAttachmentId, validPropertyBody); - if (!validPropertyResponse.equals("Updated")) { - fail("Could not update valid property for attachment: " + validAttachmentId); - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterMove.size(), + // "Source entity should have no attachments after move with sourceFacet"); - String invalidAttachmentId = sourceAttachmentIds.get(1); - RequestBody invalidPropertyBody = - RequestBody.create( - "{\"nonExistentProperty\": \"invalid\"}", MediaType.parse("application/json")); - - api.updateSecondaryProperty( - appUrl, entityName, facet[i], moveSourceEntity, invalidAttachmentId, invalidPropertyBody); - - String undefinedAttachmentId = sourceAttachmentIds.get(2); - RequestBody undefinedPropertyBody = - RequestBody.create( - "{\"undefinedField\": \"test\", \"anotherUndefined\": 999}", - MediaType.parse("application/json")); - - api.updateSecondaryProperty( - appUrl, - entityName, - facet[i], - moveSourceEntity, - undefinedAttachmentId, - undefinedPropertyBody); - - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } + + // @Test + // @Order(72) + // public void testMoveAttachmentsFromSourceEntityInDraftMode() throws Exception { + // System.out.println( + // "Test (72): Move attachments from Source Entity when Source Entity is in draft mode"); - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); + // files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); - List> sourceMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Save target before move - String saveTargetBeforeMoveResponseTest72 = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponseTest72.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveResponseTest72); - } + // int sourceCountBeforeMove = sourceAttachmentIds.size(); + // assertTrue(sourceCountBeforeMove > 0, "Source entity should have attachments before move"); + // assertEquals( + // files.size(), + // sourceCountBeforeMove, + // "Source should have " + files.size() + " attachments"); + + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - assertTrue( - targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); - assertEquals( - sourceCountBeforeMove, - targetMetadataAfterMove.size(), - "All attachments should move (invalid properties are ignored)"); - - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, targetAttachmentId); - - if (detailedMetadata.containsKey("customProperty2") - && detailedMetadata.get("customProperty2") != null) { - assertEquals( - validCustomProperty2Value, - detailedMetadata.get("customProperty2"), - "Valid customProperty2 should be preserved"); - } - } + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterMove.size(), - "Source entity should have no attachments after move with sourceFacet"); + // String editSourceResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!editSourceResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity back to draft mode"); + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - @Test - @Order(72) - public void testMoveAttachmentsFromSourceEntityInDraftMode() throws Exception { - System.out.println( - "Test (72): Move attachments from Source Entity when Source Entity is in draft mode"); + // // Save target before move + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity: " + saveTargetResponse); + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); - files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertTrue( + // targetMetadataAfterMove.size() > 0, "Target entity should have attachments after + // move"); + // assertEquals( + // sourceCountBeforeMove, + // targetMetadataAfterMove.size(), + // "Target should have " + sourceCountBeforeMove + " attachments after move"); + + // Set targetFileNames = + // targetMetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // targetFileNames.contains(file.getName()), + // "Target should contain attachment: " + file.getName()); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String saveSourceAfterMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceAfterMoveResponse.equals("Saved")) { + // fail("Could not save source entity after move: " + saveSourceAfterMoveResponse); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // sourceCountBeforeMove, + // sourceMetadataAfterMove.size(), + // "Source entity in draft mode retains attachments after move (copy behavior)"); + + // Set sourceFileNamesAfterMove = + // sourceMetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // sourceFileNamesAfterMove.contains(file.getName()), + // "Source (draft) should still contain attachment: " + file.getName()); + // } - int sourceCountBeforeMove = sourceAttachmentIds.size(); - assertTrue(sourceCountBeforeMove > 0, "Source entity should have attachments before move"); - assertEquals( - files.size(), - sourceCountBeforeMove, - "Source should have " + files.size() + " attachments"); - - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // @Test + // @Order(73) + // public void testEditAttachmentFileNameAndMoveToTarget() throws Exception { + // System.out.println( + // "Test (73): Edit attachment file name in Source Entity and move it to Target Entity"); - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); + // ClassLoader classLoader = getClass().getClassLoader(); + // File originalFile = new File(classLoader.getResource("sample.txt").getFile()); - String editSourceResponse = - api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!editSourceResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity back to draft mode"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "text/plain"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, originalFile); + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment in source entity"); + // } - // Save target before move - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity: " + saveTargetResponse); - } + // String attachmentId = createResponse.get(1); + // assertNotNull(attachmentId, "Attachment ID should not be null"); - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertTrue( - targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); - assertEquals( - sourceCountBeforeMove, - targetMetadataAfterMove.size(), - "Target should have " + sourceCountBeforeMove + " attachments after move"); - - Set targetFileNames = - targetMetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); - - for (File file : files) { - assertTrue( - targetFileNames.contains(file.getName()), - "Target should contain attachment: " + file.getName()); - } + // List> metadataBeforeRename = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals(1, metadataBeforeRename.size(), "Source should have 1 attachment"); + // assertEquals( + // "sample.txt", + // metadataBeforeRename.get(0).get("fileName"), + // "Original filename should be sample.txt"); + + // String editSourceResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!editSourceResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity to draft mode"); + // } - String saveSourceAfterMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceAfterMoveResponse.equals("Saved")) { - fail("Could not save source entity after move: " + saveSourceAfterMoveResponse); - } + // String newFileName = "testEdited.txt"; + // String renameResponse = + // api.renameAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, attachmentId, newFileName); + // assertEquals("Renamed", renameResponse, "Attachment should be renamed successfully"); - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - sourceCountBeforeMove, - sourceMetadataAfterMove.size(), - "Source entity in draft mode retains attachments after move (copy behavior)"); - - Set sourceFileNamesAfterMove = - sourceMetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); - - for (File file : files) { - assertTrue( - sourceFileNamesAfterMove.contains(file.getName()), - "Source (draft) should still contain attachment: " + file.getName()); - } + // saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity after rename: " + saveSourceResponse); + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // List> metadataAfterRename = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals(1, metadataAfterRename.size(), "Source should still have 1 attachment"); + // assertEquals( + // newFileName, + // metadataAfterRename.get(0).get("fileName"), + // "Filename should be updated to " + newFileName); + + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // String objectId = metadata.get("objectId").toString(); + // moveSourceFolderId = metadata.get("folderId").toString(); + // assertNotNull(objectId, "Object ID should not be null"); + // assertNotNull(moveSourceFolderId, "Folder ID should not be null"); + + // moveObjectIds = new ArrayList<>(); + // moveObjectIds.add(objectId); + + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - @Test - @Order(73) - public void testEditAttachmentFileNameAndMoveToTarget() throws Exception { - System.out.println( - "Test (73): Edit attachment file name in Source Entity and move it to Target Entity"); + // // Save target before move + // String saveTargetBeforeMoveResponseTest73 = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponseTest73.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveResponseTest73); + // } - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - File originalFile = new File(classLoader.getResource("sample.txt").getFile()); + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals(1, targetMetadataAfterMove.size(), "Target should have 1 attachment after + // move"); + // assertEquals( + // newFileName, + // targetMetadataAfterMove.get(0).get("fileName"), + // "Target should have attachment with renamed filename: " + newFileName); + + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterMove.size(), + // "Source entity should have no attachments after move with sourceFacet"); + + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "text/plain"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // @Test + // @Order(74) + // public void testChainMoveAttachmentsFromSourceToTarget1ToTarget2() throws Exception { + // System.out.println( + // "Test (74): Move attachments from Source Entity to Target Entity 1 and then to Target + // Entity 2"); - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, originalFile); - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment in source entity"); - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - String attachmentId = createResponse.get(1); - assertNotNull(attachmentId, "Attachment ID should not be null"); + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List> metadataBeforeRename = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals(1, metadataBeforeRename.size(), "Source should have 1 attachment"); - assertEquals( - "sample.txt", - metadataBeforeRename.get(0).get("fileName"), - "Original filename should be sample.txt"); - - String editSourceResponse = - api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!editSourceResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity to draft mode"); - } + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - String newFileName = "testEdited.txt"; - String renameResponse = - api.renameAttachment( - appUrl, entityName, facet[i], moveSourceEntity, attachmentId, newFileName); - assertEquals("Renamed", renameResponse, "Attachment should be renamed successfully"); + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity after rename: " + saveSourceResponse); - } + // int sourceCountInitial = sourceAttachmentIds.size(); + // assertTrue(sourceCountInitial > 0, "Source should have attachments"); + + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - List> metadataAfterRename = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals(1, metadataAfterRename.size(), "Source should still have 1 attachment"); - assertEquals( - newFileName, - metadataAfterRename.get(0).get("fileName"), - "Filename should be updated to " + newFileName); - - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - String objectId = metadata.get("objectId").toString(); - moveSourceFolderId = metadata.get("folderId").toString(); - assertNotNull(objectId, "Object ID should not be null"); - assertNotNull(moveSourceFolderId, "Folder ID should not be null"); - - moveObjectIds = new ArrayList<>(); - moveObjectIds.add(objectId); - - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Save target before move - String saveTargetBeforeMoveResponseTest73 = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponseTest73.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveResponseTest73); - } + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity 1"); + // } - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals(1, targetMetadataAfterMove.size(), "Target should have 1 attachment after move"); - assertEquals( - newFileName, - targetMetadataAfterMove.get(0).get("fileName"), - "Target should have attachment with renamed filename: " + newFileName); + // // Save target1 before move + // String saveTarget1BeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTarget1BeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity 1 before move"); + // } - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterMove.size(), - "Source entity should have no attachments after move with sourceFacet"); + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult1 = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult1 == null) { + // fail("Move operation from source to target 1 returned null result"); + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } - } + // List> target1MetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertTrue( + // target1MetadataAfterMove.size() > 0, + // "Target entity 1 should have attachments after move"); + // assertEquals( + // sourceCountInitial, + // target1MetadataAfterMove.size(), + // "Target 1 should have " + sourceCountInitial + " attachments"); + + // Set target1FileNames = + // target1MetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // target1FileNames.contains(file.getName()), + // "Target 1 should contain attachment: " + file.getName()); + // } - @Test - @Order(74) - public void testChainMoveAttachmentsFromSourceToTarget1ToTarget2() throws Exception { - System.out.println( - "Test (74): Move attachments from Source Entity to Target Entity 1 and then to Target Entity 2"); + // List> sourceMetadataAfterFirstMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterFirstMove.size(), + // "Source entity should have no attachments after move to target 1"); - for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // String moveTargetEntity2 = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity2.equals("Could not create entity")) { + // fail("Could not create target entity 2"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // // Save target2 before move + // String saveTarget2BeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity2); + // if (!saveTarget2BeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity 2 before move"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // List target1AttachmentIds = new ArrayList<>(); + // for (Map metadata : target1MetadataAfterMove) { + // String attachmentId = metadata.get("ID").toString(); + // target1AttachmentIds.add(attachmentId); + // } - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // moveObjectIds = new ArrayList<>(); + // String target1FolderId = null; + // for (String attachmentId : target1AttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (target1FolderId == null && metadata.containsKey("folderId")) { + // target1FolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata from target 1: " + e.getMessage()); + // } + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // assertNotNull(target1FolderId, "Target 1 folder ID should not be null"); + + // Map moveResult2 = + // api.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity2, + // target1FolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult2 == null) { + // fail("Move operation from target 1 to target 2 returned null result"); + // } - int sourceCountInitial = sourceAttachmentIds.size(); - assertTrue(sourceCountInitial > 0, "Source should have attachments"); - - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // List> target2MetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity2); + // assertTrue( + // target2MetadataAfterMove.size() > 0, + // "Target entity 2 should have attachments after move"); + // assertEquals( + // sourceCountInitial, + // target2MetadataAfterMove.size(), + // "Target 2 should have " + sourceCountInitial + " attachments"); + + // Set target2FileNames = + // target2MetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // target2FileNames.contains(file.getName()), + // "Target 2 should contain attachment: " + file.getName()); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // List> target1MetadataAfterSecondMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals( + // 0, + // target1MetadataAfterSecondMove.size(), + // "Target entity 1 should have no attachments after move to target 2"); - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); + // api.deleteEntity(appUrl, entityName, moveTargetEntity2); + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity 1"); - } + // @Test + // @Order(75) + // public void testMoveAttachmentsWithoutSDMRole() throws Exception { + // System.out.println("Test (75): Move attachments when user does not have SDM Role"); - // Save target1 before move - String saveTarget1BeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTarget1BeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity 1 before move"); - } + // for (int i = 0; i < facet.length; i++) { + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult1 = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult1 == null) { - fail("Move operation from source to target 1 returned null result"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - List> target1MetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertTrue( - target1MetadataAfterMove.size() > 0, - "Target entity 1 should have attachments after move"); - assertEquals( - sourceCountInitial, - target1MetadataAfterMove.size(), - "Target 1 should have " + sourceCountInitial + " attachments"); - - Set target1FileNames = - target1MetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); - - for (File file : files) { - assertTrue( - target1FileNames.contains(file.getName()), - "Target 1 should contain attachment: " + file.getName()); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List> sourceMetadataAfterFirstMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterFirstMove.size(), - "Source entity should have no attachments after move to target 1"); + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - String moveTargetEntity2 = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity2.equals("Could not create entity")) { - fail("Could not create target entity 2"); - } + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Save target2 before move - String saveTarget2BeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity2); - if (!saveTarget2BeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity 2 before move"); - } + // int sourceCountInitial = sourceAttachmentIds.size(); + // assertTrue(sourceCountInitial > 0, "Source should have attachments"); + + // moveObjectIds = new ArrayList<>(); + // moveSourceFolderId = null; + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - List target1AttachmentIds = new ArrayList<>(); - for (Map metadata : target1MetadataAfterMove) { - String attachmentId = metadata.get("ID").toString(); - target1AttachmentIds.add(attachmentId); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - moveObjectIds = new ArrayList<>(); - String target1FolderId = null; - for (String attachmentId : target1AttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveTargetEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (target1FolderId == null && metadata.containsKey("folderId")) { - target1FolderId = metadata.get("folderId").toString(); - } - } - } catch (IOException e) { - fail("Could not fetch attachment metadata from target 1: " + e.getMessage()); - } - } + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - assertNotNull(target1FolderId, "Target 1 folder ID should not be null"); + // moveTargetEntity = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity with no SDM role"); + // } - Map moveResult2 = - api.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity2, - target1FolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult2 == null) { - fail("Move operation from target 1 to target 2 returned null result"); - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - List> target2MetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity2); - assertTrue( - target2MetadataAfterMove.size() > 0, - "Target entity 2 should have attachments after move"); - assertEquals( - sourceCountInitial, - target2MetadataAfterMove.size(), - "Target 2 should have " + sourceCountInitial + " attachments"); - - Set target2FileNames = - target2MetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); - - for (File file : files) { - assertTrue( - target2FileNames.contains(file.getName()), - "Target 2 should contain attachment: " + file.getName()); - } + // String sourceFacet = serviceName + "." + entityName + "." + facet[i]; + // String targetFacet = serviceName + "." + entityName + "." + facet[i]; + // Map moveResult = null; + // boolean moveOperationFailed = false; + // String errorMessage = null; + + // try { + // moveResult = + // apiNoRoles.moveAttachment( + // appUrl, + // entityName, + // facet[i], + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // moveOperationFailed = true; + // errorMessage = "Move operation returned null"; + // } else if (moveResult.containsKey("error")) { + // moveOperationFailed = true; + // errorMessage = moveResult.get("error").toString(); + // } + // } catch (Exception e) { + // moveOperationFailed = true; + // errorMessage = e.getMessage(); + // } - List> target1MetadataAfterSecondMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals( - 0, - target1MetadataAfterSecondMove.size(), - "Target entity 1 should have no attachments after move to target 2"); + // assertTrue( + // moveOperationFailed, "Move operation should fail when user does not have SDM role"); + // assertNotNull(errorMessage, "Error message should be present when move operation fails"); + // System.out.println("Move operation failed as expected. Error: " + errorMessage); + + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); + // assertEquals( + // sourceCountInitial, + // sourceMetadataAfterMove.size(), + // "Source should still have all attachments after failed move"); + + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); + // assertEquals( + // 0, targetMetadataAfterMove.size(), "Target should have no attachments after failed + // move"); + + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } + // } - api.deleteEntity(appUrl, entityName, moveTargetEntity2); - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); + @Test + @Order(76) + void testReadCmisMetadataCreatedBy() { + System.out.println("Test (76) : Read CMIS metadata and verify createdBy field"); + String createdBy = CmisDocumentHelper.getCmisProperty(entityID, "sample.pdf", "cmis:createdBy"); + System.out.println("cmis:createdBy value: " + createdBy); + String tokenFlowFlag = System.getProperty("tokenFlow"); + if ("namedUser".equals(tokenFlowFlag)) { + assertEquals(username, createdBy, "cmis:createdBy should match username from credentials"); + } else { + assertNotNull(createdBy, "cmis:createdBy should not be null for technical user"); + assertFalse(createdBy.isEmpty(), "cmis:createdBy should not be empty for technical user"); } } @Test - @Order(75) - public void testMoveAttachmentsWithoutSDMRole() throws Exception { - System.out.println("Test (75): Move attachments when user does not have SDM Role"); + @Order(77) + void testUploadVirusFileInScanDisabledRepo() throws IOException { + System.out.println( + "Test (77) : Upload EICAR virus file in virus scan disabled repo — expect upload to succeed"); for (int i = 0; i < facet.length; i++) { - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); + boolean testStatus = false; + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + if (response.equals("Could not create entity")) { + fail("Could not create entity for facet: " + facet[i]); } + String testEntityID = response; - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // Use EICAR test virus file + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); + postData.put("up__ID", testEntityID); + postData.put("mimeType", "text/plain"); postData.put("createdAt", new Date().toString()); postData.put("createdBy", "test@test.com"); postData.put("modifiedBy", "test@test.com"); - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facet[i], moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } - - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } - - int sourceCountInitial = sourceAttachmentIds.size(); - assertTrue(sourceCountInitial > 0, "Source should have attachments"); - - moveObjectIds = new ArrayList<>(); - moveSourceFolderId = null; - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facet[i], moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], testEntityID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.equals("Attachment created")) { + String testAttachmentID = createResponse.get(1); + response = api.saveEntityDraft(appUrl, entityName, srvpath, testEntityID); + if (response.equals("Saved")) { + // Verify attachment is readable (upload succeeded despite being a virus file) + response = + api.readAttachment(appUrl, entityName, facet[i], testEntityID, testAttachmentID); + if (response.equals("OK")) { + testStatus = true; } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); } } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } - - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - - moveTargetEntity = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity with no SDM role"); - } - - // Save target before move - String saveTargetBeforeMoveResponse = - apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // Clean up + api.deleteEntity(appUrl, entityName, testEntityID); - String sourceFacet = serviceName + "." + entityName + "." + facet[i]; - String targetFacet = serviceName + "." + entityName + "." + facet[i]; - Map moveResult = null; - boolean moveOperationFailed = false; - String errorMessage = null; - - try { - moveResult = - apiNoRoles.moveAttachment( - appUrl, - entityName, - facet[i], - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - moveOperationFailed = true; - errorMessage = "Move operation returned null"; - } else if (moveResult.containsKey("error")) { - moveOperationFailed = true; - errorMessage = moveResult.get("error").toString(); - } - } catch (Exception e) { - moveOperationFailed = true; - errorMessage = e.getMessage(); + if (!testStatus) { + fail( + "Virus file upload should succeed in a virus scan disabled repository for facet: " + + facet[i]); } - - assertTrue( - moveOperationFailed, "Move operation should fail when user does not have SDM role"); - assertNotNull(errorMessage, "Error message should be present when move operation fails"); - System.out.println("Move operation failed as expected. Error: " + errorMessage); - - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveSourceEntity); - assertEquals( - sourceCountInitial, - sourceMetadataAfterMove.size(), - "Source should still have all attachments after failed move"); - - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facet[i], moveTargetEntity); - assertEquals( - 0, targetMetadataAfterMove.size(), "Target should have no attachments after failed move"); - - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); } } @@ -7463,7 +7735,7 @@ void testDownloadButtonWithPdfAndLinkAcrossFacetsInDraftState() throws IOExcepti } // @Test - // @Order(77) + // @Order(78) // void testUploadAttachmentExceedingMaximumFileSize() throws IOException { // System.out.println( // "Test (76) : Upload attachment exceeding maximum file size in references facet"); diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_RepoSpecific.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_RepoSpecific.java new file mode 100644 index 000000000..a88344064 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_RepoSpecific.java @@ -0,0 +1,372 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.utils.ShellScriptRunner; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +/** + * Integration tests for "Displaying Attachments Specific To Repository" with multiple facets. + * Verifies that attachments created under one repository are not visible when the application + * switches to a different repository, and that duplicate file names across repositories are allowed + * for all facets (attachments, references, footnotes). + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_MultipleFacet_RepoSpecific { + + private static final String UPDATE_ENV_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh"; + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String entityName = "Books"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String tenancyModel; + private static String defaultRepositoryID; + private static String virusScanRepositoryID; + private static ApiInterface api; + + // Entity IDs used across tests + private static String entityID1; + private static String[] attachmentID1 = new String[3]; + private static String entityID_rename; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryID"); + virusScanRepositoryID = credentialsProperties.getProperty("virusScanRepositoryID"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryIDMT"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + private static int runUpdateEnv(String value) throws Exception { + if (tenancyModel.equals("multi")) { + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--app", "bookshop-mt-srv", "--value", value); + } + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--value", value); + } + + @Test + @Order(1) + void testSetupRepo1AndCreateAttachments() throws Exception { + System.out.println( + "Test (1) : Setup — switch to defaultRepositoryID (" + + defaultRepositoryID + + "), create entity with attachments in all facets"); + + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Entity creation should succeed"); + entityID1 = response; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", entityID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], entityID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Attachment creation should succeed for " + facet[i]); + attachmentID1[i] = createResponse.get(1); + } + + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID1); + assertEquals("Saved", response, "Entity save should succeed"); + + for (int i = 0; i < facet.length; i++) { + response = api.readAttachment(appUrl, entityName, facet[i], entityID1, attachmentID1[i]); + assertEquals( + "OK", + response, + "Attachment should be readable under defaultRepositoryID for " + facet[i]); + + List> attachments = + api.fetchEntityMetadata(appUrl, entityName, facet[i], entityID1); + assertEquals( + 1, + attachments.size(), + "Entity should have 1 attachment under defaultRepositoryID for " + facet[i]); + } + } + + @Test + @Order(2) + void testSwitchToRepo2AttachmentsNotVisible() throws Exception { + System.out.println( + "Test (2) : Switch to virusScanRepositoryID, verify attachments from defaultRepositoryID are not visible in any facet"); + + int exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + String response = api.checkEntity(appUrl, entityName, entityID1); + assertEquals("Entity exists", response, "Entity should still be visible after repo switch"); + + for (int i = 0; i < facet.length; i++) { + List> attachments = + api.fetchEntityMetadata(appUrl, entityName, facet[i], entityID1); + assertEquals( + 0, + attachments.size(), + "Entity should have 0 attachments after switching to virusScanRepositoryID for " + + facet[i]); + } + } + + @Test + @Order(3) + void testDuplicateAttachmentCreateAcrossRepos() throws Exception { + System.out.println( + "Test (3) : Create attachment with same name under virusScanRepositoryID in all facets — should succeed"); + + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID1); + assertEquals("Entity in draft mode", response, "Edit entity should succeed"); + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", entityID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], entityID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Duplicate attachment across repos should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID1); + assertEquals("Saved", response, "Entity save should succeed"); + } + + @Test + @Order(4) + void testDuplicateAttachmentRenameAcrossRepos() throws Exception { + System.out.println( + "Test (4) : Create new entity with sample.pdf in defaultRepositoryID, switch to virusScanRepositoryID, upload" + + " sample1.pdf, rename to sample.pdf in all facets — should succeed"); + + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Entity creation should succeed"); + entityID_rename = response; + + ClassLoader classLoader = getClass().getClassLoader(); + File pdfFile = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", entityID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, entityName, facet[i], entityID_rename, srvpath, postData, pdfFile); + assertEquals( + "Attachment created", + createResponse.get(0), + "Attachment creation should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID_rename); + assertEquals("Saved", response, "Entity save should succeed under defaultRepositoryID"); + + exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + response = api.editEntityDraft(appUrl, entityName, srvpath, entityID_rename); + assertEquals("Entity in draft mode", response, "Edit entity should succeed"); + + for (int i = 0; i < facet.length; i++) { + File pdfFile2 = new File(classLoader.getResource("sample1.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", entityID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, entityName, facet[i], entityID_rename, srvpath, postData, pdfFile2); + assertEquals( + "Attachment created", + createResponse.get(0), + "Upload sample1.pdf should succeed for " + facet[i]); + String attachmentID2 = createResponse.get(1); + + response = + api.renameAttachment( + appUrl, entityName, facet[i], entityID_rename, attachmentID2, "sample.pdf"); + assertEquals( + "Renamed", + response, + "Renaming to duplicate name across repos should succeed for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID_rename); + assertEquals("Saved", response, "Entity save after rename should succeed"); + } + + @Test + @Order(5) + void testCreateAttachment_NonExistentRepo_FailsWithRepoInfoError() throws Exception { + String fakeRepoId = "non-existent-repo-" + UUID.randomUUID(); + System.out.println( + "Test (5) : Switch to non-existent repo (" + + fakeRepoId + + ") and attempt attachment creation — expect failure"); + + // Switch to a random non-existent repository ID + int exitCode = runUpdateEnv(fakeRepoId); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + + // Create an entity (draft creation should still succeed) + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Entity creation should succeed"); + String entityId = response; + + // Upload an attachment to the first facet + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.txt").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", entityId); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[0], entityId, srvpath, postData, file); + + // Attachment content upload should fail because the repo doesn't exist + String status = createResponse.get(0); + assertNotEquals( + "Attachment created", status, "Attachment should fail with non-existent repository"); + assertTrue( + status.toLowerCase().contains("repository") + || status.toLowerCase().contains("error") + || status.toLowerCase().contains("not found") + || status.toLowerCase().contains("failed"), + "Error should indicate repository issue. Got: " + status); + System.out.println("Expected error received: " + status); + } + + @Test + @Order(6) + void testRevertToDefaultRepository() throws Exception { + System.out.println("Test (6) : Revert REPOSITORY_ID to default repository"); + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_VersionedRepository.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_VersionedRepository.java new file mode 100644 index 000000000..f19f09cd4 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_VersionedRepository.java @@ -0,0 +1,147 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +class IntegrationTest_MultipleFacet_VersionedRepository { + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String entityName = "Books"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String tenancyModel; + private static ApiInterface api; + private static String entityID; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + @Test + void testCreateEntityAndUploadAttachmentShouldFail() throws IOException { + System.out.println( + "Test (2) : Create entity and upload attachments on versioned repository in all facets — expect error"); + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Entity creation should succeed"); + entityID = response; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, file); + String check = createResponse.get(0); + + if (check.equals("Attachment created")) { + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + assertNotEquals( + "Saved", response, "Save should fail on versioned repository for " + facet[i]); + System.out.println("Save failed as expected for " + facet[i] + ": " + response); + } else { + System.out.println("Operation failed as expected for " + facet[i] + ": " + check); + assertTrue( + check.contains("error") || check.contains("Error"), + "Response should contain an error message for " + facet[i]); + } + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_Virus.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_Virus.java new file mode 100644 index 000000000..cb20a2949 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_MultipleFacet_Virus.java @@ -0,0 +1,290 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_MultipleFacet_Virus { + private static String token; + private static String entityID; + private static String[] facet = {"attachments", "references", "footnotes"}; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String entityName = "Books"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static ApiInterface api; + private static String[] attachmentID1 = new String[3]; + private static String[] attachmentID2 = new String[3]; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + String tenancyModel = System.getProperty("tenancyModel"); + String tenant = System.getProperty("tenant"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + if (tenancyModel.equals("single")) { + System.out.println("Running integration tests | Single tenant Scenario"); + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + if (tenant.equals("TENANT1")) { + System.out.println("Running integration tests | Multitenant Scenario | SDM DEV Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else if (tenant.equals("TENANT2")) { + System.out.println( + "Running integration tests | Multitenant Scenario | Googleworkspace Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT2"); + } else { + throw new IllegalArgumentException("Invalid tenant specified: " + tenant); + } + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request; + + String tokenFlowFlag = System.getProperty("tokenFlow"); + if (tokenFlowFlag.equals("namedUser")) { + System.out.println("Named user token flow"); + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + System.out.println("Technical user token flow"); + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + String errorBody = response.body().string(); + System.out.println("Error body: " + errorBody); + } + token = new ObjectMapper().readTree(response.body().string()).get("access_token").asText(); + response.close(); + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else if (tenancyModel.equals("single")) { + config.put("serviceName", serviceName); + api = new Api(config); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + } + + /** + * Helper method to wait for attachment upload completion. + * + * @param entityId The ID of the entity containing the attachment + * @param attachmentId The ID of the attachment to check + * @param facetName The facet name for the attachment + * @param timeoutSeconds Maximum time to wait in seconds + * @return true if upload completed successfully, false if failed or timed out + */ + private boolean waitForUploadCompletion( + String entityId, String attachmentId, String facetName, int timeoutSeconds) { + int maxIterations = timeoutSeconds / 2; + for (int i = 0; i < maxIterations; i++) { + try { + Map metadata = + api.fetchMetadataDraft(appUrl, entityName, facetName, entityId, attachmentId); + String uploadStatus = (String) metadata.get("uploadStatus"); + + if ("Success".equals(uploadStatus)) { + return true; + } else if ("Failed".equals(uploadStatus)) { + System.err.println("Upload failed for attachment: " + attachmentId); + return false; + } + + Thread.sleep(2000); + } catch (Exception e) { + System.err.println( + "Error checking upload status for attachment " + attachmentId + ": " + e.getMessage()); + return false; + } + } + + System.err.println("Upload timed out for attachment: " + attachmentId); + return false; + } + + @Test + @Order(1) + void testCreateEntityAndCheck() { + System.out.println("Test (1) : Create entity and check if it exists"); + boolean testStatus = false; + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + if (response != "Could not create entity") { + entityID = response; + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Saved") { + response = api.checkEntity(appUrl, entityName, entityID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + if (!testStatus) { + fail("Could not create entity"); + } + } + + @Test + @Order(2) + void testUpdateEmptyEntity() { + System.out.println("Test (2) : Update an existing entity"); + boolean testStatus = false; + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Entity in draft mode") { + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Saved") { + response = api.checkEntity(appUrl, entityName, entityID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + if (!testStatus) { + fail("Could not update entity"); + } + } + + @Test + @Order(3) + void testUploadSingleAttachmentPDF() throws IOException { + System.out.println("Test (3) : Upload pdf in all facets"); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + assertEquals("Entity in draft mode", response, "Entity should be in draft mode"); + + for (int i = 0; i < facet.length; i++) { + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, file); + assertEquals( + "Attachment created", createResponse.get(0), "Upload should succeed for " + facet[i]); + attachmentID1[i] = createResponse.get(1); + + response = api.readAttachmentDraft(appUrl, entityName, facet[i], entityID, attachmentID1[i]); + assertEquals("OK", response, "Attachment should be readable in draft for " + facet[i]); + } + + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + assertEquals("Saved", response, "Entity save should succeed"); + + for (int i = 0; i < facet.length; i++) { + response = api.readAttachment(appUrl, entityName, facet[i], entityID, attachmentID1[i]); + assertEquals("OK", response, "Attachment should be readable after save for " + facet[i]); + } + } + + @Test + @Order(4) + void testUploadVirusFileInScannedRepo() throws IOException { + System.out.println( + "Test (4) : Upload EICAR virus file in all facets — expect virus scan to reject"); + + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } + + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + assertEquals("Entity in draft mode", response, "Entity should be in draft mode"); + + for (int i = 0; i < facet.length; i++) { + boolean testStatus = false; + + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facet[i], entityID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.contains("malware") || check.contains("potential malware")) { + testStatus = true; + } else if (check.equals("Attachment created")) { + attachmentID2[i] = createResponse.get(1); + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response.equals("Saved")) { + boolean uploadSucceeded = + waitForUploadCompletion(entityID, attachmentID2[i], facet[i], 120); + if (!uploadSucceeded) { + testStatus = true; + } else { + fail( + "Virus file should have been rejected by the virus scanner but upload succeeded for " + + facet[i]); + } + } + } + + if (!testStatus) { + fail("Could not verify virus file rejection for " + facet[i]); + } + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet.java index 444a63841..ce69f08d8 100644 --- a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet.java +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet.java @@ -2,18 +2,13 @@ import static org.junit.jupiter.api.Assertions.*; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.utils.CmisDocumentHelper; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.time.LocalDateTime; import java.util.*; -import java.util.stream.Collectors; import okhttp3.*; -import okio.ByteString; import org.json.JSONArray; import org.json.JSONObject; import org.junit.jupiter.api.*; @@ -278,6088 +273,6349 @@ void testUploadSingleAttachmentPDF() throws IOException { } } - @Test - @Order(4) - void testUploadSingleAttachmentTXT() throws IOException { - System.out.println("Test (4) : Upload txt"); - Boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.txt").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/txt"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Entity in draft mode") { - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - attachmentID2 = createResponse.get(1); - response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID, attachmentID2); - if (response.equals("OK")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - response = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID2); - if (response.equals("OK")) { - testStatus = true; - } - } - } - } - } - if (!testStatus) { - fail("Could not upload sample.txt"); - } - } - - @Test - @Order(5) - void testUploadSingleAttachmentEXE() throws IOException { - System.out.println("Test (5) : Upload exe"); - Boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.exe").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/exe"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Entity in draft mode") { - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - attachmentID3 = createResponse.get(1); - response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID, attachmentID3); - if (response.equals("OK")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - response = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID3); - if (response.equals("OK")) { - testStatus = true; - } - } - } - } - } - if (!testStatus) { - fail("Could not create sample.exe"); - } - } - - @Test - @Order(6) - void testUploadAttachmentWithoutSDMRole() throws IOException { - System.out.println("Test (6) : Upload attachment with no SDM role"); - Boolean testStatus = false; - String response = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID4 = response; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID4); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - apiNoRoles.createAttachment( - appUrl, entityName, facetName, entityID4, srvpath, postData, tempFile); - String check = createResponse.get(0); - String expectedString = - "{\"error\":{\"code\":\"500\",\"message\":\"You do not have the required permissions to upload attachments. Please contact your administrator for access.\"}}"; - if (check.equals(expectedString)) { - testStatus = true; - } - } - if (!testStatus) { - fail("Attachment created without SDM role"); - } - } - - @Test - @Order(7) - void testUploadSingleAttachmentPDFDuplicate() throws IOException { - System.out.println("Test (7) : Upload duplicate pdf"); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Boolean testStatus = false; - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Entity in draft mode") { - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - testStatus = false; - } else { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - String expectedJson = - "{\"error\":{\"code\":\"500\",\"message\":\"An object named \\\"sample.pdf\\\" already exists. Rename the object and try again.\"}}"; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode actualJsonNode = objectMapper.readTree(check); - JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); - if (expectedJsonNode.equals(actualJsonNode)) { - testStatus = true; - } - } - } - } - if (!testStatus) { - fail("Attachment created"); - } - } - - @Test - @Order(8) - void testUploadSingleAttachmentPDFDuplicateDifferentEntity() throws IOException { - System.out.println("Test (8) : Upload duplicate pdf in different entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID2 = response; - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - if (response == "Saved") { - response = api.checkEntity(appUrl, entityName, entityID2); - if (response.equals("Entity exists")) { - testStatus = true; - } - } - } - if (!testStatus) { - fail("Could not create entity"); - } - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID2); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - response = api.editEntityDraft(appUrl, entityName, srvpath, entityID2); - if (response == "Entity in draft mode") { - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID2, srvpath, postData, file); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - attachmentID4 = createResponse.get(1); - response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID2, attachmentID4); - if (response.equals("OK")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - if (response.equals("Saved")) { - response = api.readAttachment(appUrl, entityName, facetName, entityID2, attachmentID4); - - if (response.equals("OK")) { - testStatus = true; - } - } - } - } - } - if (!testStatus) { - fail("Could not upload sample.pdf " + response); - } - } - - @Test - @Order(9) - void testCreateAttachmentWithRestrictedCharacterInFilename() throws IOException { - System.out.println("Test (9): Create attachment with restricted character in filename"); - - boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Entity in draft mode")) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, entityID, srvpath, postData, tempFile); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - attachmentID6 = createResponse.get(1); - - String restrictedFilename = "a/\\bc.pdf"; - response = - api.renameAttachment( - appUrl, entityName, facetName, entityID, attachmentID6, restrictedFilename); - - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - if (response.equals(expected)) { - api.renameAttachment( - appUrl, entityName, facetName, entityID, attachmentID6, "sample3.pdf"); - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if ("Saved".equals(response)) testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - } - if (!testStatus) { - fail("Attachment created with restricted character in filename"); - } - } - - @Test - @Order(10) - void testDraftUpdateWithFileUploadDeleteAndCreate() throws IOException { - System.out.println("Test (10): Upload attachments, delete one and create entity"); - - boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - - entityID5 = response; - ClassLoader classLoader = getClass().getClassLoader(); - - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID5); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - List createResponse1 = - api.createAttachment(appUrl, entityName, facetName, entityID5, srvpath, postData1, file); - if (createResponse1.get(0).equals("Attachment created")) { - attachmentID7 = createResponse1.get(1); - } - - file = new File(classLoader.getResource("sample.txt").getFile()); - Map postData2 = new HashMap<>(); - postData2.put("up__ID", entityID5); - postData2.put("mimeType", "application/txt"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - List createResponse2 = - api.createAttachment(appUrl, entityName, facetName, entityID5, srvpath, postData2, file); - if (createResponse2.get(0).equals("Attachment created")) { - attachmentID8 = createResponse2.get(1); - } - response = api.deleteAttachment(appUrl, entityName, facetName, entityID5, attachmentID8); - if (response.equals("Deleted")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); - - if (response.equals("Saved")) { - testStatus = true; - } - } - } - if (!testStatus) { - fail("Failed to create entity after deleting one attachment"); - } - } - - @Test - @Order(11) - void testUpdateEntityDraft() throws IOException { - System.out.println("Test (11): Update entity in draft"); - boolean testStatus = false; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - - File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); - Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID5); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID5); - if (response.equals("Entity in draft mode")) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, entityID5, srvpath, postData, tempFile); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); - if (response.equals("Saved")) { - testStatus = true; - } - } - } - if (!testStatus) { - fail("update entity draft with uploading attachment failed"); - } - api.deleteEntity(appUrl, entityName, entityID5); - } - - @Test - @Order(12) - void testRenameSingleAttachment() { - System.out.println("Test (12) : Rename single attachment"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String name = "sample123"; - if (response == "Entity in draft mode") { - response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, name); - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment was not renamed"); - } - } - - @Test - @Order(13) - void testRenameAttachmentWithUnsupportedCharacter() { - System.out.println("Test (13) : Rename single attachment with unsupported characters"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String name = "invalid/name"; - if (response == "Entity in draft mode") { - response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, name); - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"invalid/name\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - if (response.equals(expected)) { - api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, "sample123"); - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if ("Saved".equals(response)) testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment was renamed with unsupported characters"); - } - } - - @Test - @Order(14) - void testRenameMultipleAttachments() { - System.out.println("Test (14) : Rename multiple attachments"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String name1 = "sample1234"; - String name2 = "sample12345"; - if (response == "Entity in draft mode") { - String response1 = - api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID2, name1); - String response2 = - api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, name2); - if (response1.equals("Renamed") && response2.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment was not renamed"); - } - } - - @Test - @Order(15) - void testRenameSingleAttachmentDuplicate() { - System.out.println("Test (15) : Rename single attachment duplicate"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - String name = "sample123"; - String name2 = "sample123456"; - if (response == "Entity in draft mode") { - response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, name); - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sample123\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - if (response.equals(expected)) { - response = - api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, name2); - if (response.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response.equals("Saved")) { - testStatus = true; - } - } - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment was renamed"); - } - } - - @Test - @Order(16) - void testRenameMultipleAttachmentsWithOneUnsupportedCharacter() { - System.out.println( - "Test (16) : Rename multiple attachments where one name has unsupported characters"); - Boolean testStatus = false; - - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - - if (response.equals("Entity in draft mode")) { - String validName1 = "valid_attachment1.pdf"; - String invalidName2 = "invalid/attachment2.pdf"; - - String renameResponse1 = - api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, validName1); - String renameResponse2 = - api.renameAttachment( - appUrl, entityName, facetName, entityID, attachmentID2, invalidName2); - - if (renameResponse1.equals("Renamed") && renameResponse2.equals("Renamed")) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"invalid/attachment2.pdf\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - if (response.equals(expected)) { - api.renameAttachment( - appUrl, entityName, facetName, entityID, attachmentID2, "sample1234"); - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if ("Saved".equals(response)) testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - - if (!testStatus) { - fail("Multiple renames should have failed due to one unsupported characters"); - } - } - - @Test - @Order(17) - void testRenameSingleAttachmentWithoutSDMRole() throws IOException { - System.out.println("Test (17) : Rename attachments where user don't have SDM Roles"); - boolean testStatus = false; - String apiResponse = apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, entityID); - String name = "sample123"; // Renaming the attachment - if (apiResponse == "Entity in draft mode") { - apiResponse = - apiNoRoles.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, name); - if (apiResponse.equals("Renamed")) { - apiResponse = apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); - String expected = - "[{\"code\":\"\",\"message\":\"Could not update the following files. \\n" - + // - "\\n" - + // - "\\t\\u2022 valid_attachment1.pdf\\n" - + // - "\\n" - + // - "You do not have the required permissions to update attachments. Kindly contact the admin\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (apiResponse.equals(expected)) { - testStatus = true; - } - } else { - apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); - } - } - if (!testStatus) { - fail("Attachment got renamed without SDM roles."); - } - } - - @Test - @Order(18) - void testRenameToValidateNames() throws IOException { - System.out.println("Test (18) : Rename attachments to validate names"); - boolean testStatus = false, successCount = true; - String generatedID = ""; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID3 = response; - String[] filetoUpload = {"sample.pdf", "sample.txt", "sample.exe", "sample2.pdf"}; - String[] names = {"Restricted/Character", " ", "duplicateName.pdf", "duplicateName.pdf"}; - - ClassLoader classLoader = getClass().getClassLoader(); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - for (int i = 0; i < filetoUpload.length; i++) { - File file = new File(classLoader.getResource(filetoUpload[i]).getFile()); - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, file); - generatedID = createResponse.get(1); - response = - api.renameAttachment(appUrl, entityName, facetName, entityID3, generatedID, names[i]); - successCount &= "Renamed".equals(response); - } - if (successCount) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - String expected = - "{\"error\":{\"code\":\"400\",\"message\":\"The object name cannot be empty or consist entirely of space characters. Enter a value.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"Restricted/Character\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"duplicateName.pdf\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; - if (response.equals(expected)) { - response = api.deleteEntityDraft(appUrl, entityName, entityID3); - if (response.equals("Entity Draft Deleted")) testStatus = true; - } - } - if (!testStatus) fail("Could not create entity"); - } else { - fail("Could not create entity"); - return; - } - } - - @Test - @Order(19) - void testDeleteSingleAttachment() throws IOException { - System.out.println("Test (19) : Delete single attachment"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Entity in draft mode") { - response = api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID1); - if (response == "Deleted") { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Saved") { - response = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID1); - if (response.equals("Could not read Attachment")) { - testStatus = true; - } - } - } - } - if (!testStatus) { - fail("Could not read Attachment"); - } - } - - @Test - @Order(20) - void testDeleteMultipleAttachments() throws IOException { - System.out.println("Test (20) : Delete multiple attachments"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Entity in draft mode") { - String response1 = - api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID2); - String response2 = - api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID3); - if (response1 == "Deleted" && response2 == "Deleted") { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); - if (response == "Saved") { - response1 = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID2); - response2 = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID3); - if (response1.equals("Could not read Attachment") - && response2.equals("Could not read Attachment")) { - testStatus = true; - } - } - } - } - if (!testStatus) { - fail("Could not delete attachment"); - } - } - - @Test - @Order(21) - void testUploadBlockedMimeType() throws IOException { - System.out.println("Test (21): Upload blocked mimeType .rtf"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!"Could not create entity".equals(response)) { - entityID2 = response; - - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(Objects.requireNonNull(classLoader.getResource("sample.rtf")).getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID2); - postData.put("mimeType", "application/rtf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID2, srvpath, postData, file); - String actualResponse = createResponse.get(0); - String expectedJson = - "{\"error\":{\"code\":\"500\",\"message\":\"This file type is not allowed in this repository. Contact your administrator for assistance.\"}}"; - - if (expectedJson.equals(actualResponse)) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - if ("Saved".equals(response)) { - testStatus = true; - } - } else { - api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); - } - } - if (!testStatus) { - fail("Attachment got uploaded with blocked .rtf MIME type"); - } - } - - @Test - @Order(22) - void testDeleteEntity() { - System.out.println("Test (22) : Delete entity"); - Boolean testStatus = false; - String response = api.deleteEntity(appUrl, entityName, entityID); - String response2 = api.deleteEntity(appUrl, entityName, entityID2); - if (response == "Entity Deleted" && response2 == "Entity Deleted") { - testStatus = true; - } - if (!testStatus) { - fail("Could not delete entity"); - } - } - - @Test - @Order(23) - void testUpdateValidSecondaryProperty_beforeEntityIsSaved_singleAttachment() throws IOException { - System.out.println("Test (23): Rename & Update secondary property before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID3 = response; - System.out.println("Entity created"); - System.out.println("Creating attachment"); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, file); - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - attachmentID1 = createResponse.get(1); - System.out.println("Attachment created"); - String name1 = "sample1234.pdf"; - String secondaryPropertyString = "sample12345"; - Integer secondaryPropertyInt = 1234; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - System.out.println("Renaming and updating secondary properties for attachment"); - String response1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - if (response1 == "Renamed" - && updateSecondaryPropertyResponse1 == "Updated" - && updateSecondaryPropertyResponse2 == "Updated" - && updateSecondaryPropertyResponse3 == "Updated" - && updateSecondaryPropertyResponse4 == "Updated") { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachment"); - } - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(24) - void testUpdateValidSecondaryProperty_afterEntityIsSaved_singleAttachment() { - System.out.println("Test (24): Rename & Update secondary property after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response == "Entity in draft mode") { - String name1 = "sample.pdf"; - String secondaryPropertyString = "sample"; - Integer secondaryPropertyInt = 12; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - System.out.println("Renaming and updating secondary properties for attachment"); - String response1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - if (response1 == "Renamed" - && updateSecondaryPropertyResponse1 == "Updated" - && updateSecondaryPropertyResponse2 == "Updated" - && updateSecondaryPropertyResponse3 == "Updated" - && updateSecondaryPropertyResponse4 == "Updated") { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachment"); - } - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - if (!testStatus) { - fail("Could not update secondary property after entity is saved"); - } - } - - @Test - @Order(25) - void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_singleAttachment() - throws IOException { - System.out.println( - "Test (25): Rename & Update invalid secondary property before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!"Could not create entity".equals(response)) { - entityID3 = response; - System.out.println("Entity created"); - System.out.println("Creating attachment"); - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID3); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, file); - String check = createResponse.get(0); - if ("Attachment created".equals(check)) { - attachmentID1 = createResponse.get(1); - System.out.println("Attachment created"); - String name1 = "sample1234.pdf"; - - // Dropdown values for secondaryPropertyString - String[] dropdownValues = {"A", "B", "C"}; - // Select one dropdown value (e.g., "A") - String secondaryPropertyString = dropdownValues[0]; - - Integer secondaryPropertyInt = 1234; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - String invalidProperty = "testid"; - - System.out.println("Renaming and updating invalid secondary properties for attachment"); - String response1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - - // Update secondary properties for String using dropdown selected value as object with code - - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown1); - - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - - // Update invalid secondary property - String updateSecondaryPropertyResponse5 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, invalidProperty); - - if ("Renamed".equals(response1) - && "Updated".equals(updateSecondaryPropertyResponse1) - && "Updated".equals(updateSecondaryPropertyResponse2) - && "Updated".equals(updateSecondaryPropertyResponse3) - && "Updated".equals(updateSecondaryPropertyResponse4) - && "Updated".equals(updateSecondaryPropertyResponse5)) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - Map attachmentMetadata = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); - assertEquals("sample.pdf", attachmentMetadata.get("fileName")); - assertNull(attachmentMetadata.get("customProperty3")); - assertNull(attachmentMetadata.get("customProperty4")); - assertNull(attachmentMetadata.get("customProperty1_code")); - assertNull(attachmentMetadata.get("customProperty2")); - assertNull(attachmentMetadata.get("customProperty6")); - assertNull(attachmentMetadata.get("customProperty5")); - - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update secondary properties for attachment is unsuccessfull"); - } - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(26) - void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_singleAttachment() throws IOException { - System.out.println( - "Test (26): Rename & Update invalid secondary property after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response == "Entity in draft mode") { - String name1 = "sample.pdf"; - String secondaryPropertyString = "A"; - Integer secondaryPropertyInt = 12; - LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); - String invalidProperty = "testidinvalid"; - System.out.println("Renaming and updating invalid secondary properties for attachment"); - String response1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); - String updateSecondaryPropertyResponse3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - // Update invalid secondary property - String updateSecondaryPropertyResponse5 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, invalidProperty); - if (response1 == "Renamed" - && updateSecondaryPropertyResponse1 == "Updated" - && updateSecondaryPropertyResponse2 == "Updated" - && updateSecondaryPropertyResponse3 == "Updated" - && updateSecondaryPropertyResponse4 == "Updated" - && updateSecondaryPropertyResponse5 == "Updated") { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - Map attachmentMetadata = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); - assertEquals("sample.pdf", attachmentMetadata.get("fileName")); - assertNull(attachmentMetadata.get("customProperty3")); - assertNull(attachmentMetadata.get("customProperty4")); - assertNull(attachmentMetadata.get("customProperty1_code")); - assertNull(attachmentMetadata.get("customProperty2")); - assertNull(attachmentMetadata.get("customProperty6")); - assertNull(attachmentMetadata.get("customProperty5")); - - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update secondary properties for attachment is unsuccessfull"); - } - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(27) - void testUpdateValidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (27): Rename & Update valid secondary properties for multiple attachments before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID3 = response; - - System.out.println("Entity created"); - - System.out.println("Creating attachment PDF"); - ClassLoader classLoader = getClass().getClassLoader(); - - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID3); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - List createResponse1 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData1, file); - if (createResponse1.get(0).equals("Attachment created")) { - attachmentID1 = createResponse1.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment TXT"); - file = new File(classLoader.getResource("sample.txt").getFile()); - Map postData2 = new HashMap<>(); - postData2.put("up__ID", entityID3); - postData2.put("mimeType", "application/txt"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - List createResponse2 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData2, file); - if (createResponse2.get(0).equals("Attachment created")) { - attachmentID2 = createResponse2.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment EXE"); - file = new File(classLoader.getResource("sample.exe").getFile()); - Map postData3 = new HashMap<>(); - postData3.put("up__ID", entityID3); - postData3.put("mimeType", "application/exe"); - postData3.put("createdAt", new Date().toString()); - postData3.put("createdBy", "test@test.com"); - postData3.put("modifiedBy", "test@test.com"); - - List createResponse3 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData3, file); - if (createResponse3.get(0).equals("Attachment created")) { - attachmentID3 = createResponse3.get(1); - System.out.println("Attachment created"); - } - - String check1 = createResponse1.get(0); - String check2 = createResponse2.get(0); - String check3 = createResponse3.get(0); - if (check1.equals("Attachment created") - && check2.equals("Attachment created") - && check3.equals("Attachment created")) { - Boolean attachment1Updated = false; - Boolean attachment2Updated = false; - Boolean attachment3Updated = false; - - String name1 = "sample1234.pdf"; - Integer secondaryPropertyInt1 = 1234; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - System.out.println("Renaming and updating secondary properties for attachment PDF"); - String responsePDF1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponsePDF1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponsePDF2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponsePDF3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponsePDF4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - if (responsePDF1 == "Renamed" - && updateSecondaryPropertyResponsePDF1 == "Updated" - && updateSecondaryPropertyResponsePDF2 == "Updated" - && updateSecondaryPropertyResponsePDF3 == "Updated" - && updateSecondaryPropertyResponsePDF4 == "Updated") { - System.out.println("Renamed & updated Secondary properties for attachment PDF"); - attachment1Updated = true; - } - - System.out.println("Updating secondary properties for attachment TXT"); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); - if (updateSecondaryPropertyResponseTXT1 == "Updated") { - System.out.println("Updated Secondary properties for attachment TXT"); - attachment2Updated = true; - } - Integer secondaryPropertyInt3 = 1234; - LocalDateTime secondaryPropertyDateTime3 = LocalDateTime.now(); - System.out.println("Updating secondary properties for attachment EXE"); - // Update secondary properties for String - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); - // Update secondary properties for Integer - RequestBody bodyInt3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); - // Update secondary properties for DateTime - RequestBody bodyDateTime3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime3 + "\"\n}")); - String updateSecondaryPropertyResponseEXE3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDateTime3); - - if (updateSecondaryPropertyResponseEXE1 == "Updated" - && updateSecondaryPropertyResponseEXE2 == "Updated" - && updateSecondaryPropertyResponseEXE3 == "Updated") { - System.out.println("Updated Secondary properties for attachment EXE"); - attachment3Updated = true; - } - - if (attachment1Updated && attachment2Updated && attachment3Updated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachments"); - } - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(28) - void testUpdateValidSecondaryProperty_afterEntityIsSaved_multipleAttachments() { - System.out.println( - "Test (28): Rename & Update valid secondary properties for multiple attachments after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response == "Entity in draft mode") { - Boolean attachment1Updated = false; - Boolean attachment2Updated = false; - Boolean attachment3Updated = false; - - String name1 = "sample1.pdf"; - Integer secondaryPropertyInt1 = 12; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - System.out.println("Renaming and updating secondary properties for attachment PDF"); - String responsePDF1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue1 = integrationTestUtils.getDropDownValue(); - String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); - String updateSecondaryPropertyResponsePDF1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown1); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponsePDF2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponsePDF3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponsePDF4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - - if (responsePDF1 == "Renamed" - && updateSecondaryPropertyResponsePDF1 == "Updated" - && updateSecondaryPropertyResponsePDF2 == "Updated" - && updateSecondaryPropertyResponsePDF3 == "Updated" - && updateSecondaryPropertyResponsePDF4 == "Updated") { - System.out.println("Renamed & updated Secondary properties for attachment PDF"); - attachment1Updated = true; - } - - System.out.println("Updating secondary properties for attachment TXT"); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); - if (updateSecondaryPropertyResponseTXT1 == "Updated") { - System.out.println("Updated Secondary properties for attachment TXT"); - attachment2Updated = true; - } - - Integer secondaryPropertyInt3 = 123; - LocalDateTime secondaryPropertyDateTime3 = LocalDateTime.now(); - System.out.println("Updating secondary properties for attachment EXE"); - // Update secondary properties for String - String dropdownValue2 = integrationTestUtils.getDropDownValue(); - String jsonDropdown2 = "{ \"customProperty1_code\" : \"" + dropdownValue2 + "\" }"; - RequestBody bodyDropdown2 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown2); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown2); - // Update secondary properties for Integer - RequestBody bodyInt3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); - // Update secondary properties for DateTime - RequestBody bodyDateTime3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime3 + "\"\n}")); - String updateSecondaryPropertyResponseEXE3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDateTime3); - - if (updateSecondaryPropertyResponseEXE1 == "Updated" - && updateSecondaryPropertyResponseEXE2 == "Updated" - && updateSecondaryPropertyResponseEXE3 == "Updated") { - System.out.println("Updated Secondary properties for attachment EXE"); - attachment3Updated = true; - } - - if (attachment1Updated && attachment2Updated && attachment3Updated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response.equals("Saved")) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println("Renamed & updated Secondary properties for attachments"); - } - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - if (!testStatus) { - fail("Could not update secondary property after entity is saved"); - } - } - - @Test - @Order(29) - void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (29): Rename & Update invalid and valid secondary properties for multiple attachments before entity is saved"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID3 = response; - - System.out.println("Entity created"); - - System.out.println("Creating attachment PDF"); - ClassLoader classLoader = getClass().getClassLoader(); - - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID3); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - List createResponse1 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData1, file); - if (createResponse1.get(0).equals("Attachment created")) { - attachmentID1 = createResponse1.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment TXT"); - file = new File(classLoader.getResource("sample.txt").getFile()); - Map postData2 = new HashMap<>(); - postData2.put("up__ID", entityID3); - postData2.put("mimeType", "application/txt"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - List createResponse2 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData2, file); - if (createResponse2.get(0).equals("Attachment created")) { - attachmentID2 = createResponse2.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment EXE"); - file = new File(classLoader.getResource("sample.exe").getFile()); - Map postData3 = new HashMap<>(); - postData3.put("up__ID", entityID3); - postData3.put("mimeType", "application/exe"); - postData3.put("createdAt", new Date().toString()); - postData3.put("createdBy", "test@test.com"); - postData3.put("modifiedBy", "test@test.com"); - - List createResponse3 = - api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData3, file); - if (createResponse3.get(0).equals("Attachment created")) { - attachmentID3 = createResponse3.get(1); - System.out.println("Attachment created"); - } - - String check1 = createResponse1.get(0); - String check2 = createResponse2.get(0); - String check3 = createResponse3.get(0); - if (check1.equals("Attachment created") - && check2.equals("Attachment created") - && check3.equals("Attachment created")) { - Boolean attachment1Updated = false; - Boolean attachment2Updated = false; - Boolean attachment3Updated = false; - - String name1 = "sample1234.pdf"; - Integer secondaryPropertyInt1 = 1234; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - String invalidPropertyPDF = "testidinvalidPDF"; - System.out.println("Renaming and updating invalid secondary properties for attachment PDF"); - String responsePDF1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponsePDF1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyint = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponsePDF2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyint); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponsePDF3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponsePDF4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - // Update invalid secondary property - String updateSecondaryPropertyResponsePDF5 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, invalidPropertyPDF); - if (responsePDF1 == "Renamed" - && updateSecondaryPropertyResponsePDF1 == "Updated" - && updateSecondaryPropertyResponsePDF2 == "Updated" - && updateSecondaryPropertyResponsePDF3 == "Updated" - && updateSecondaryPropertyResponsePDF4 == "Updated" - && updateSecondaryPropertyResponsePDF5 == "Updated") { - attachment1Updated = true; - } - - System.out.println("Updating valid secondary properties for attachment TXT"); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); - if (updateSecondaryPropertyResponseTXT1 == "Updated") { - System.out.println("Updated Secondary properties for attachment TXT"); - attachment2Updated = true; - } - - Integer secondaryPropertyInt3 = 1234; - System.out.println("Updating valid secondary properties for attachment EXE"); - - // Update secondary properties for String - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); - // Update secondary properties for Integer - RequestBody bodyInt3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); - - if (updateSecondaryPropertyResponseEXE1 == "Updated" - && updateSecondaryPropertyResponseEXE2 == "Updated") { - System.out.println("Updated Secondary properties for attachment EXE"); - attachment3Updated = true; - } - - if (attachment1Updated && attachment2Updated && attachment3Updated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - Map attachmentMetadataPDF = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); - assertEquals("sample.pdf", attachmentMetadataPDF.get("fileName")); - assertNull(attachmentMetadataPDF.get("customProperty3")); - assertNull(attachmentMetadataPDF.get("customProperty4")); - assertNull(attachmentMetadataPDF.get("customProperty1_code")); - assertNull(attachmentMetadataPDF.get("customProperty2")); - assertNull(attachmentMetadataPDF.get("customProperty6")); - assertNull(attachmentMetadataPDF.get("customProperty5")); - - Map attachmentMetadataTXT = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID2); - assertEquals("sample.txt", attachmentMetadataTXT.get("fileName")); - assertNull(attachmentMetadataTXT.get("customProperty3")); - assertNull(attachmentMetadataTXT.get("customProperty4")); - assertNull(attachmentMetadataTXT.get("customProperty1_code")); - assertNull(attachmentMetadataTXT.get("customProperty2")); - assertTrue((Boolean) attachmentMetadataTXT.get("customProperty6")); - assertNull(attachmentMetadataTXT.get("customProperty5")); - - Map attachmentMetadataEXE = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID3); - assertEquals("sample.exe", attachmentMetadataEXE.get("fileName")); - assertNull(attachmentMetadataEXE.get("customProperty3")); - assertNull(attachmentMetadataEXE.get("customProperty4")); - assertEquals(dropdownValue, attachmentMetadataEXE.get("customProperty1_code")); - assertEquals(1234, attachmentMetadataEXE.get("customProperty2")); - - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update unsuccessfull for invalid Secondary properties and successfull for valid property attachments"); - } - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(30) - void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_multipleAttachments() - throws IOException { - System.out.println( - "Test (30): Rename & Update invalid and valid secondary properties for multiple attachments after entity is saved"); - System.out.println("Editing entity"); - Boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); - if (response == "Entity in draft mode") { - Boolean attachment1Updated = false; - Boolean attachment2Updated = false; - Boolean attachment3Updated = false; - - String name1 = "sample.pdf"; - Integer secondaryPropertyInt1 = 12; - LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); - String invalidPropertyPDF = "testidinvalidPDF"; - System.out.println("Renaming and updating invalid secondary properties for attachment PDF"); - String responsePDF1 = - api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); - // Update secondary properties for String - String dropdownValue = integrationTestUtils.getDropDownValue(); - String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; - RequestBody bodyDropdown = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponsePDF1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); - // Update secondary properties for Integer - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); - String updateSecondaryPropertyResponsePDF2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); - // Update secondary properties for DateTime - RequestBody bodyDateTime = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); - String updateSecondaryPropertyResponsePDF3 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); - // Update secondary properties for Boolean - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponsePDF4 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); - // Update invalid secondary property - String updateSecondaryPropertyResponsePDF5 = - api.updateInvalidSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID1, invalidPropertyPDF); - if (responsePDF1 == "Renamed" - && updateSecondaryPropertyResponsePDF1 == "Updated" - && updateSecondaryPropertyResponsePDF2 == "Updated" - && updateSecondaryPropertyResponsePDF3 == "Updated" - && updateSecondaryPropertyResponsePDF4 == "Updated" - && updateSecondaryPropertyResponsePDF5 == "Updated") { - attachment1Updated = true; - } - - System.out.println("Updating valid secondary properties for attachment TXT"); - // Update secondary properties for Boolean - RequestBody bodyBool = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + false + "\n}")); - String updateSecondaryPropertyResponseTXT1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); - if (updateSecondaryPropertyResponseTXT1 == "Updated") { - System.out.println("Updated Secondary properties for attachment TXT"); - attachment2Updated = true; - } - - Integer secondaryPropertyInt3 = 12; - System.out.println("Updating valid secondary properties for attachment EXE"); - - // Update secondary properties for String - RequestBody bodyDropdown1 = - RequestBody.create(MediaType.parse("application/json"), jsonDropdown); - String updateSecondaryPropertyResponseEXE1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); - // Update secondary properties for Integer - RequestBody bodyInt3 = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8( - "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); - String updateSecondaryPropertyResponseEXE2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); - - if (updateSecondaryPropertyResponseEXE1 == "Updated" - && updateSecondaryPropertyResponseEXE2 == "Updated") { - System.out.println("Updated Secondary properties for attachment EXE"); - attachment3Updated = true; - } - - if (attachment1Updated && attachment2Updated && attachment3Updated) { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); - Map attachmentMetadataPDF = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); - assertEquals("sample.pdf", attachmentMetadataPDF.get("fileName")); - assertNull(attachmentMetadataPDF.get("customProperty3")); - assertNull(attachmentMetadataPDF.get("customProperty4")); - assertNull(attachmentMetadataPDF.get("customProperty1_code")); - assertNull(attachmentMetadataPDF.get("customProperty2")); - assertNull(attachmentMetadataPDF.get("customProperty6")); - assertNull(attachmentMetadataPDF.get("customProperty5")); - - Map attachmentMetadataTXT = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID2); - assertEquals("sample.txt", attachmentMetadataTXT.get("fileName")); - assertNull(attachmentMetadataTXT.get("customProperty3")); - assertNull(attachmentMetadataTXT.get("customProperty4")); - assertNull(attachmentMetadataTXT.get("customProperty1_code")); - assertNull(attachmentMetadataTXT.get("customProperty2")); - assertFalse((Boolean) attachmentMetadataTXT.get("customProperty6")); - assertNull(attachmentMetadataTXT.get("customProperty5")); - - Map attachmentMetadataEXE = - api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID3); - assertEquals("sample.exe", attachmentMetadataEXE.get("fileName")); - assertNull(attachmentMetadataEXE.get("customProperty3")); - assertNull(attachmentMetadataEXE.get("customProperty4")); - assertEquals(dropdownValue, attachmentMetadataEXE.get("customProperty1_code")); - assertEquals(12, attachmentMetadataEXE.get("customProperty2")); - - String expectedResponse = - "[{\"code\":\"\",\"message\":\"The following secondary properties are not supported.\\n" - + // - "\\n" - + // - "\\t\\u2022 id1\\n" - + // - "\\n" - + // - "Please contact your administrator for assistance with any necessary adjustments.\\n" - + // - "\\n" - + // - "Table: attachments\\n" - + // - "Page: IntegrationTestEntity\",\"numericSeverity\":3}]"; - if (response.equals(expectedResponse)) { - System.out.println("Entity saved"); - testStatus = true; - System.out.println( - "Rename & update unsuccessfull for invalid Secondary properties and successfull for valid property attachments"); - } - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } - } - } - if (!testStatus) { - fail("Could not update secondary property before entity is saved"); - } - } - - @Test - @Order(31) - void testNAttachments_NewEntity() throws IOException { - System.out.println( - "Test (31): Creating new entity and checking only max 4 attachments are allowed to be uploaded"); - System.out.println("Creating entity"); - Boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (response != "Could not create entity") { - entityID4 = response; - - System.out.println("Entity created"); - - System.out.println("Creating attachment PDF"); - ClassLoader classLoader = getClass().getClassLoader(); - - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID4); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); - - List createResponse1 = - api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData1, file); - if (createResponse1.get(0).equals("Attachment created")) { - attachmentID1 = createResponse1.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment TXT"); - file = new File(classLoader.getResource("sample.txt").getFile()); - Map postData2 = new HashMap<>(); - postData2.put("up__ID", entityID4); - postData2.put("mimeType", "application/txt"); - postData2.put("createdAt", new Date().toString()); - postData2.put("createdBy", "test@test.com"); - postData2.put("modifiedBy", "test@test.com"); - - List createResponse2 = - api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData2, file); - if (createResponse2.get(0).equals("Attachment created")) { - attachmentID2 = createResponse2.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating attachment EXE"); - file = new File(classLoader.getResource("sample.exe").getFile()); - Map postData3 = new HashMap<>(); - postData3.put("up__ID", entityID4); - postData3.put("mimeType", "application/exe"); - postData3.put("createdAt", new Date().toString()); - postData3.put("createdBy", "test@test.com"); - postData3.put("modifiedBy", "test@test.com"); - - List createResponse3 = - api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, file); - if (createResponse3.get(0).equals("Attachment created")) { - attachmentID3 = createResponse3.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating second attachment pdf"); - file = new File(classLoader.getResource("sample1.pdf").getFile()); - Map postData4 = new HashMap<>(); - postData4.put("up__ID", entityID4); - postData4.put("mimeType", "application/pdf"); - postData4.put("createdAt", new Date().toString()); - postData4.put("createdBy", "test@test.com"); - postData4.put("modifiedBy", "test@test.com"); - - List createResponse4 = - api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, file); - if (createResponse4.get(0).equals("Attachment created")) { - attachmentID4 = createResponse4.get(1); - System.out.println("Attachment created"); - } - - System.out.println("Creating third attachment pdf"); - file = new File(classLoader.getResource("sample2.pdf").getFile()); - Map postData5 = new HashMap<>(); - postData5.put("up__ID", entityID4); - postData5.put("mimeType", "application/pdf"); - postData5.put("createdAt", new Date().toString()); - postData5.put("createdBy", "test@test.com"); - postData5.put("modifiedBy", "test@test.com"); - - List createResponse5 = - api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, file); - if (createResponse5.get(0).equals("Only 4 attachments allowed.")) { - testStatus = true; - attachmentID5 = createResponse5.get(1); - System.out.println("Expected error received: Only 4 attachments allowed."); - } - String check = createResponse5.get(0); - if (check.equals("Attachment created")) { - testStatus = false; - } else { - response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID4); - if (response.equals("Saved")) { - String expectedJson = - "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 attachments.\"}}"; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode actualJsonNode = objectMapper.readTree(check); - JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); - if (expectedJsonNode.equals(actualJsonNode)) { - testStatus = true; - } - } - } - } - if (!testStatus) { - fail("Attachment was created"); - } - } - - @Test - @Order(32) - void testUploadNAttachments() throws IOException { - System.out.println("Test (32): Upload maximum 4 attachments in an exsisting entity"); - - ClassLoader classLoader = getClass().getClassLoader(); - File originalFile = new File(classLoader.getResource("sample.exe").getFile()); + // @Test + // @Order(4) + // void testUploadSingleAttachmentTXT() throws IOException { + // System.out.println("Test (4) : Upload txt"); + // Boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.txt").getFile()); - boolean testStatus = false; - String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID4); - System.out.println("response: " + response); - - if ("Entity in draft mode".equals(response)) { - for (int i = 1; i <= 5; i++) { - // Ensure only one file is uploaded at a time and complete before next - File tempFile = File.createTempFile("sample_" + i + "_", ".exe"); - Files.copy(originalFile.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - - Map postData = new HashMap<>(); - postData.put("up__ID", entityID4); - postData.put("mimeType", "application/exe"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, entityID4, srvpath, postData, tempFile); - - String resultMessage = createResponse.get(0); - System.out.println("Result message for attachment " + i + ": " + resultMessage); - - String expectedResponse = - "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 attachments.\"}}"; - if (resultMessage.equals(expectedResponse)) { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode actualJsonNode = objectMapper.readTree(resultMessage); - JsonNode expectedJsonNode = objectMapper.readTree(expectedResponse); - if (expectedJsonNode.equals(actualJsonNode)) { - testStatus = true; - } - } else { - testStatus = false; - } - tempFile.delete(); - } - if (!testStatus) { - fail("5th attachment did not trigger the expected error."); - } - // Delete the newly created entity - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID4); - if (deleteEntityResponse != "Entity Deleted") { - fail("Could not delete entity"); - } else { - System.out.println("Successfully deleted the test entity4"); - } - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/txt"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - @Test - @Order(33) - void testDiscardDraftWithoutAttachments() { - System.out.println("Test (33) : Discard draft without adding attachments"); + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Entity in draft mode") { + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // attachmentID2 = createResponse.get(1); + // response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID, + // attachmentID2); + // if (response.equals("OK")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // response = api.readAttachment(appUrl, entityName, facetName, entityID, + // attachmentID2); + // if (response.equals("OK")) { + // testStatus = true; + // } + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not upload sample.txt"); + // } + // } - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // @Test + // @Order(5) + // void testUploadSingleAttachmentEXE() throws IOException { + // System.out.println("Test (5) : Upload exe"); + // Boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.exe").getFile()); - if (response.equals("Could not create entity")) { - fail("Could not create entity"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/exe"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - response = api.deleteEntityDraft(appUrl, entityName, response); - if (!response.equals("Entity Draft Deleted")) { - fail("Draft was not discarded properly"); - } - } + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Entity in draft mode") { + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // attachmentID3 = createResponse.get(1); + // response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID, + // attachmentID3); + // if (response.equals("OK")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // response = api.readAttachment(appUrl, entityName, facetName, entityID, + // attachmentID3); + // if (response.equals("OK")) { + // testStatus = true; + // } + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not create sample.exe"); + // } + // } - @Test - @Order(34) - void testDiscardDraftWithAttachments() throws IOException { - System.out.println("Test (34) : Discard draft with attachments"); - boolean testStatus = false; - String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!response.equals("Could not create entity")) { - entityID7 = response; - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - - Map postData1 = new HashMap<>(); - postData1.put("up__ID", entityID7); - postData1.put("mimeType", "application/pdf"); - postData1.put("createdAt", new Date().toString()); - postData1.put("createdBy", "test@test.com"); - postData1.put("modifiedBy", "test@test.com"); + // @Test + // @Order(6) + // void testUploadAttachmentWithoutSDMRole() throws IOException { + // System.out.println("Test (6) : Upload attachment with no SDM role"); + // Boolean testStatus = false; + // String response = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID4 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID4); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // apiNoRoles.createAttachment( + // appUrl, entityName, facetName, entityID4, srvpath, postData, tempFile); + // String check = createResponse.get(0); + // String expectedString = + // "{\"error\":{\"code\":\"500\",\"message\":\"You do not have the required permissions to + // upload attachments. Please contact your administrator for access.\"}}"; + // if (check.equals(expectedString)) { + // testStatus = true; + // } + // } + // if (!testStatus) { + // fail("Attachment created without SDM role"); + // } + // } - List createResponse = - api.createAttachment(appUrl, entityName, facetName, entityID7, srvpath, postData1, file); - if (createResponse.get(0).equals("Attachment created")) { - attachmentID1 = createResponse.get(1); - } - String check = createResponse.get(0); - if (check.equals("Attachment created")) { - response = api.deleteEntityDraft(appUrl, entityName, entityID7); - } - if (response.equals("Entity Draft Deleted")) { - testStatus = true; - } - } - if (!testStatus) { - fail("Draft was not discarded properly"); - } - } + // @Test + // @Order(7) + // void testUploadSingleAttachmentPDFDuplicate() throws IOException { + // System.out.println("Test (7) : Upload duplicate pdf"); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Boolean testStatus = false; - @Test - @Order(35) - void testCopyAttachmentsSuccessNewEntity() throws IOException { - System.out.println("Test (35): Copy attachments from one entity to another new entity"); - List attachments = new ArrayList<>(); - copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!copyAttachmentSourceEntity.equals("Could not create entity") - && !copyAttachmentTargetEntity.equals("Could not create entity")) { - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample1.pdf").getFile())); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (String attachment : attachments) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadata( - appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - if (sourceObjectIds.size() == 2) { - String copyResponse; - copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); - if (copyResponse.equals("Attachments copied successfully")) { - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not create entities"); - } - } + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Entity in draft mode") { + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // testStatus = false; + // } else { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // String expectedJson = + // "{\"error\":{\"code\":\"500\",\"message\":\"An object named \\\"sample.pdf\\\" + // already exists. Rename the object and try again.\"}}"; + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode actualJsonNode = objectMapper.readTree(check); + // JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); + // if (expectedJsonNode.equals(actualJsonNode)) { + // testStatus = true; + // } + // } + // } + // } + // if (!testStatus) { + // fail("Attachment created"); + // } + // } - @Test - @Order(36) - void testCopyAttachmentsUnsuccessfulNewEntity() throws IOException { - System.out.println("Test (36): Copy attachments from one entity to another new entity"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - copyAttachmentTargetEntityEmpty = - api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (editResponse1.equals("Entity in draft mode") - && !copyAttachmentTargetEntityEmpty.equals("Could not create entity")) { - sourceObjectIds.add("incorrectObjectId"); - if (sourceObjectIds.size() == 3) { - try { - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntityEmpty, sourceObjectIds); - fail("Copy attachments did not throw an error"); - } catch (IOException e) { - String saveEntityResponse1 = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String saveEntityResponse2 = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntityEmpty); - String deleteResponse = - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntityEmpty); - if (!saveEntityResponse1.equals("Saved") - || !saveEntityResponse2.equals("Saved") - || !deleteResponse.equals("Entity Deleted")) { - fail("Could not save entities"); - } - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // @Test + // @Order(8) + // void testUploadSingleAttachmentPDFDuplicateDifferentEntity() throws IOException { + // System.out.println("Test (8) : Upload duplicate pdf in different entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID2 = response; + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + // if (response == "Saved") { + // response = api.checkEntity(appUrl, entityName, entityID2); + // if (response.equals("Entity exists")) { + // testStatus = true; + // } + // } + // } + // if (!testStatus) { + // fail("Could not create entity"); + // } - @Test - @Order(37) - void testCopyAttachmentWithNotesField() throws IOException { - System.out.println( - "Test (37): Create entity with attachment containing notes, copy to new entity and verify notes field"); - Boolean testStatus = false; - // Create source entity - copyCustomSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyCustomSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); - // Create and upload attachment to source entity - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID2); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // response = api.editEntityDraft(appUrl, entityName, srvpath, entityID2); + // if (response == "Entity in draft mode") { + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID2, srvpath, postData, + // file); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // attachmentID4 = createResponse.get(1); + // response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID2, + // attachmentID4); + // if (response.equals("OK")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + // if (response.equals("Saved")) { + // response = api.readAttachment(appUrl, entityName, facetName, entityID2, + // attachmentID4); + + // if (response.equals("OK")) { + // testStatus = true; + // } + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not upload sample.pdf " + response); + // } + // } - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment"); - } + // @Test + // @Order(9) + // void testCreateAttachmentWithRestrictedCharacterInFilename() throws IOException { + // System.out.println("Test (9): Create attachment with restricted character in filename"); - String sourceAttachmentId = createResponse.get(1); + // boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - // Update attachment with notes field - String notesValue = "This is a test note for copy attachment verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateBody = RequestBody.create(jsonPayload, mediaType); + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - String updateResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, updateBody); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - if (!updateResponse.equals("Updated")) { - fail("Could not update attachment notes field"); - } + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Entity in draft mode")) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, entityID, srvpath, postData, tempFile); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // attachmentID6 = createResponse.get(1); + + // String restrictedFilename = "a/\\bc.pdf"; + // response = + // api.renameAttachment( + // appUrl, entityName, facetName, entityID, attachmentID6, restrictedFilename); + + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"a/\\bc.pdf\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // if (response.equals(expected)) { + // api.renameAttachment( + // appUrl, entityName, facetName, entityID, attachmentID6, "sample3.pdf"); + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if ("Saved".equals(response)) testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // } + // if (!testStatus) { + // fail("Attachment created with restricted character in filename"); + // } + // } - // Save source entity - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity"); - } + // @Test + // @Order(10) + // void testDraftUpdateWithFileUploadDeleteAndCreate() throws IOException { + // System.out.println("Test (10): Upload attachments, delete one and create entity"); - // Fetch attachment metadata to get objectId - Map sourceAttachmentMetadata = - api.fetchMetadata( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); + // boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + + // entityID5 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID5); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // List createResponse1 = + // api.createAttachment(appUrl, entityName, facetName, entityID5, srvpath, postData1, + // file); + // if (createResponse1.get(0).equals("Attachment created")) { + // attachmentID7 = createResponse1.get(1); + // } - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId"); - } + // file = new File(classLoader.getResource("sample.txt").getFile()); + // Map postData2 = new HashMap<>(); + // postData2.put("up__ID", entityID5); + // postData2.put("mimeType", "application/txt"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // List createResponse2 = + // api.createAttachment(appUrl, entityName, facetName, entityID5, srvpath, postData2, + // file); + // if (createResponse2.get(0).equals("Attachment created")) { + // attachmentID8 = createResponse2.get(1); + // } + // response = api.deleteAttachment(appUrl, entityName, facetName, entityID5, attachmentID8); + // if (response.equals("Deleted")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); - // Store objectId in array - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - if (sourceObjectIds.isEmpty()) { - sourceObjectIds.add(sourceObjectId); - } else { - sourceObjectIds.set(0, sourceObjectId); - } + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } + // } + // if (!testStatus) { + // fail("Failed to create entity after deleting one attachment"); + // } + // } - String sourceNoteValue = - sourceAttachmentMetadata.get("note") != null - ? sourceAttachmentMetadata.get("note").toString() - : null; - - if (!notesValue.equals(sourceNoteValue)) { - fail( - "Notes field was not properly set in source attachment. Expected: " - + notesValue - + ", Got: " - + sourceNoteValue); - } + // @Test + // @Order(11) + // void testUpdateEntityDraft() throws IOException { + // System.out.println("Test (11): Update entity in draft"); + // boolean testStatus = false; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.pdf")).getFile()); - // Create target entity - copyCustomTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyCustomTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // File tempFile = new File(System.getProperty("java.io.tmpdir"), "sample3.pdf"); + // Files.copy(file.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - // Copy attachment to target entity - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(0)); // Use objectId from array + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID5); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID5); + // if (response.equals("Entity in draft mode")) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, entityID5, srvpath, postData, tempFile); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID5); + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } + // } + // if (!testStatus) { + // fail("update entity draft with uploading attachment failed"); + // } + // api.deleteEntity(appUrl, entityName, entityID5); + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity: " + copyResponse); - } + // @Test + // @Order(12) + // void testRenameSingleAttachment() { + // System.out.println("Test (12) : Rename single attachment"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String name = "sample123"; + // if (response == "Entity in draft mode") { + // response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, + // name); + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment was not renamed"); + // } + // } - // Save target entity - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity"); - } + // @Test + // @Order(13) + // void testRenameAttachmentWithUnsupportedCharacter() { + // System.out.println("Test (13) : Rename single attachment with unsupported characters"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String name = "invalid/name"; + // if (response == "Entity in draft mode") { + // response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, + // name); + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"invalid/name\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // if (response.equals(expected)) { + // api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, + // "sample123"); + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if ("Saved".equals(response)) testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment was renamed with unsupported characters"); + // } + // } - // Fetch target entity attachments metadata - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // @Test + // @Order(14) + // void testRenameMultipleAttachments() { + // System.out.println("Test (14) : Rename multiple attachments"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String name1 = "sample1234"; + // String name2 = "sample12345"; + // if (response == "Entity in draft mode") { + // String response1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID2, name1); + // String response2 = + // api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, name2); + // if (response1.equals("Renamed") && response2.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment was not renamed"); + // } + // } - if (targetAttachmentsMetadata.isEmpty()) { - fail("No attachments found in target entity"); - } + // @Test + // @Order(15) + // void testRenameSingleAttachmentDuplicate() { + // System.out.println("Test (15) : Rename single attachment duplicate"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String name = "sample123"; + // String name2 = "sample123456"; + // if (response == "Entity in draft mode") { + // response = api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, + // name); + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sample123\\\" already + // exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // if (response.equals(expected)) { + // response = + // api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID3, + // name2); + // if (response.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response.equals("Saved")) { + // testStatus = true; + // } + // } + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment was renamed"); + // } + // } - // Verify the copied attachment has the same notes value - Map copiedAttachmentMetadata = targetAttachmentsMetadata.get(0); - String copiedNoteValue = - copiedAttachmentMetadata.get("note") != null - ? copiedAttachmentMetadata.get("note").toString() - : null; - - if (!notesValue.equals(copiedNoteValue)) { - fail( - "Notes field was not properly copied. Expected: " - + notesValue - + ", Got: " - + copiedNoteValue); - } + // @Test + // @Order(16) + // void testRenameMultipleAttachmentsWithOneUnsupportedCharacter() { + // System.out.println( + // "Test (16) : Rename multiple attachments where one name has unsupported characters"); + // Boolean testStatus = false; + + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + + // if (response.equals("Entity in draft mode")) { + // String validName1 = "valid_attachment1.pdf"; + // String invalidName2 = "invalid/attachment2.pdf"; + + // String renameResponse1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, + // validName1); + // String renameResponse2 = + // api.renameAttachment( + // appUrl, entityName, facetName, entityID, attachmentID2, invalidName2); + + // if (renameResponse1.equals("Renamed") && renameResponse2.equals("Renamed")) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"invalid/attachment2.pdf\\\" contains + // unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // if (response.equals(expected)) { + // api.renameAttachment( + // appUrl, entityName, facetName, entityID, attachmentID2, "sample1234"); + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if ("Saved".equals(response)) testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } - // Verify attachment content can be read from target entity - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // if (!testStatus) { + // fail("Multiple renames should have failed due to one unsupported characters"); + // } + // } - if (readResponse.equals("OK")) { - testStatus = true; - } - if (!testStatus) { - fail("Could not verify that notes field was copied from source to target attachment"); - } - } + // @Test + // @Order(17) + // void testRenameSingleAttachmentWithoutSDMRole() throws IOException { + // System.out.println("Test (17) : Rename attachments where user don't have SDM Roles"); + // boolean testStatus = false; + // String apiResponse = apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, entityID); + // String name = "sample123"; // Renaming the attachment + // if (apiResponse == "Entity in draft mode") { + // apiResponse = + // apiNoRoles.renameAttachment(appUrl, entityName, facetName, entityID, attachmentID1, + // name); + // if (apiResponse.equals("Renamed")) { + // apiResponse = apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // String expected = + // "[{\"code\":\"\",\"message\":\"Could not update the following files. \\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 valid_attachment1.pdf\\n" + // + // + // "\\n" + // + // + // "You do not have the required permissions to update attachments. Kindly contact + // the admin\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (apiResponse.equals(expected)) { + // testStatus = true; + // } + // } else { + // apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // } + // } + // if (!testStatus) { + // fail("Attachment got renamed without SDM roles."); + // } + // } - @Test - @Order(38) - void testCopyAttachmentWithSecondaryPropertiesField() throws IOException { - System.out.println( - "Test (38): Verify that secondary properties are preserved when copying attachments between entities"); - Boolean testStatus = false; + // @Test + // @Order(18) + // void testRenameToValidateNames() throws IOException { + // System.out.println("Test (18) : Rename attachments to validate names"); + // boolean testStatus = false, successCount = true; + // String generatedID = ""; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID3 = response; + // String[] filetoUpload = {"sample.pdf", "sample.txt", "sample.exe", "sample2.pdf"}; + // String[] names = {"Restricted/Character", " ", "duplicateName.pdf", + // "duplicateName.pdf"}; + + // ClassLoader classLoader = getClass().getClassLoader(); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // for (int i = 0; i < filetoUpload.length; i++) { + // File file = new File(classLoader.getResource(filetoUpload[i]).getFile()); + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, + // file); + // generatedID = createResponse.get(1); + // response = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, generatedID, + // names[i]); + // successCount &= "Renamed".equals(response); + // } + // if (successCount) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // String expected = + // "{\"error\":{\"code\":\"400\",\"message\":\"The object name cannot be empty or + // consist entirely of space characters. Enter a value.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\",\"details\":[{\"code\":\"\",\"message\":\"\\\"Restricted/Character\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4},{\"code\":\"\",\"message\":\"An object named \\\"duplicateName.pdf\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"@Common.numericSeverity\":4}]}}"; + // if (response.equals(expected)) { + // response = api.deleteEntityDraft(appUrl, entityName, entityID3); + // if (response.equals("Entity Draft Deleted")) testStatus = true; + // } + // } + // if (!testStatus) fail("Could not create entity"); + // } else { + // fail("Could not create entity"); + // return; + // } + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity"); - } + // @Test + // @Order(19) + // void testDeleteSingleAttachment() throws IOException { + // System.out.println("Test (19) : Delete single attachment"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Entity in draft mode") { + // response = api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID1); + // if (response == "Deleted") { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Saved") { + // response = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID1); + // if (response.equals("Could not read Attachment")) { + // testStatus = true; + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not read Attachment"); + // } + // } - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample1.pdf").getFile()); + // @Test + // @Order(20) + // void testDeleteMultipleAttachments() throws IOException { + // System.out.println("Test (20) : Delete multiple attachments"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Entity in draft mode") { + // String response1 = + // api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID2); + // String response2 = + // api.deleteAttachment(appUrl, entityName, facetName, entityID, attachmentID3); + // if (response1 == "Deleted" && response2 == "Deleted") { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + // if (response == "Saved") { + // response1 = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID2); + // response2 = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID3); + // if (response1.equals("Could not read Attachment") + // && response2.equals("Could not read Attachment")) { + // testStatus = true; + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not delete attachment"); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // @Test + // @Order(21) + // void testUploadBlockedMimeType() throws IOException { + // System.out.println("Test (21): Upload blocked mimeType .rtf"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!"Could not create entity".equals(response)) { + // entityID2 = response; + + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new + // File(Objects.requireNonNull(classLoader.getResource("sample.rtf")).getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID2); + // postData.put("mimeType", "application/rtf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID2, srvpath, postData, + // file); + // String actualResponse = createResponse.get(0); + // String expectedJson = + // "{\"error\":{\"code\":\"500\",\"message\":\"This file type is not allowed in this + // repository. Contact your administrator for assistance.\"}}"; + + // if (expectedJson.equals(actualResponse)) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + // if ("Saved".equals(response)) { + // testStatus = true; + // } + // } else { + // api.saveEntityDraft(appUrl, entityName, srvpath, entityID2); + // } + // } + // if (!testStatus) { + // fail("Attachment got uploaded with blocked .rtf MIME type"); + // } + // } - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // @Test + // @Order(22) + // void testDeleteEntity() { + // System.out.println("Test (22) : Delete entity"); + // Boolean testStatus = false; + // String response = api.deleteEntity(appUrl, entityName, entityID); + // String response2 = api.deleteEntity(appUrl, entityName, entityID2); + // if (response == "Entity Deleted" && response2 == "Entity Deleted") { + // testStatus = true; + // } + // if (!testStatus) { + // fail("Could not delete entity"); + // } + // } - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment"); - } + // @Test + // @Order(23) + // void testUpdateValidSecondaryProperty_beforeEntityIsSaved_singleAttachment() throws IOException + // { + // System.out.println("Test (23): Rename & Update secondary property before entity is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID3 = response; + // System.out.println("Entity created"); + // System.out.println("Creating attachment"); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, + // file); + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // attachmentID1 = createResponse.get(1); + // System.out.println("Attachment created"); + // String name1 = "sample1234.pdf"; + // String secondaryPropertyString = "sample12345"; + // Integer secondaryPropertyInt = 1234; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // System.out.println("Renaming and updating secondary properties for attachment"); + // String response1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // if (response1 == "Renamed" + // && updateSecondaryPropertyResponse1 == "Updated" + // && updateSecondaryPropertyResponse2 == "Updated" + // && updateSecondaryPropertyResponse3 == "Updated" + // && updateSecondaryPropertyResponse4 == "Updated") { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachment"); + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - String sourceAttachmentId = createResponse.get(1); - - // Update attachment with secondary properties - // DocumentInfoRecordBoolean : Set to true - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyBoolean); - - if (!updateSecondaryPropertyResponse1.equals("Updated")) { - fail( - "Could not update attachment DocumentInfoRecordBoolean field. Response: " - + updateSecondaryPropertyResponse1); - } + // @Test + // @Order(24) + // void testUpdateValidSecondaryProperty_afterEntityIsSaved_singleAttachment() { + // System.out.println("Test (24): Rename & Update secondary property after entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response == "Entity in draft mode") { + // String name1 = "sample.pdf"; + // String secondaryPropertyString = "sample"; + // Integer secondaryPropertyInt = 12; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // System.out.println("Renaming and updating secondary properties for attachment"); + // String response1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // if (response1 == "Renamed" + // && updateSecondaryPropertyResponse1 == "Updated" + // && updateSecondaryPropertyResponse2 == "Updated" + // && updateSecondaryPropertyResponse3 == "Updated" + // && updateSecondaryPropertyResponse4 == "Updated") { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachment"); + // } + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property after entity is saved"); + // } + // } - // customProperty2 : Set to 12345 - Integer customProperty2Value = 12345; - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); - - if (!updateSecondaryPropertyResponse2.equals("Updated")) { - fail( - "Could not update attachment customProperty2 field. Response: " - + updateSecondaryPropertyResponse2); - } + // @Test + // @Order(25) + // void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_singleAttachment() + // throws IOException { + // System.out.println( + // "Test (25): Rename & Update invalid secondary property before entity is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!"Could not create entity".equals(response)) { + // entityID3 = response; + // System.out.println("Entity created"); + // System.out.println("Creating attachment"); + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID3); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData, + // file); + // String check = createResponse.get(0); + // if ("Attachment created".equals(check)) { + // attachmentID1 = createResponse.get(1); + // System.out.println("Attachment created"); + // String name1 = "sample1234.pdf"; + + // // Dropdown values for secondaryPropertyString + // String[] dropdownValues = {"A", "B", "C"}; + // // Select one dropdown value (e.g., "A") + // String secondaryPropertyString = dropdownValues[0]; + + // Integer secondaryPropertyInt = 1234; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // String invalidProperty = "testid"; + + // System.out.println("Renaming and updating invalid secondary properties for attachment"); + // String response1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + + // // Update secondary properties for String using dropdown selected value as object with + // code + + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown1); + + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + + // // Update invalid secondary property + // String updateSecondaryPropertyResponse5 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, invalidProperty); + + // if ("Renamed".equals(response1) + // && "Updated".equals(updateSecondaryPropertyResponse1) + // && "Updated".equals(updateSecondaryPropertyResponse2) + // && "Updated".equals(updateSecondaryPropertyResponse3) + // && "Updated".equals(updateSecondaryPropertyResponse4) + // && "Updated".equals(updateSecondaryPropertyResponse5)) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // Map attachmentMetadata = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); + // assertEquals("sample.pdf", attachmentMetadata.get("fileName")); + // assertNull(attachmentMetadata.get("customProperty3")); + // assertNull(attachmentMetadata.get("customProperty4")); + // assertNull(attachmentMetadata.get("customProperty1_code")); + // assertNull(attachmentMetadata.get("customProperty2")); + // assertNull(attachmentMetadata.get("customProperty6")); + // assertNull(attachmentMetadata.get("customProperty5")); + + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update secondary properties for attachment is unsuccessfull"); + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - // Save source entity - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity. Response: " + saveSourceResponse); - } + // @Test + // @Order(26) + // void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_singleAttachment() throws + // IOException { + // System.out.println( + // "Test (26): Rename & Update invalid secondary property after entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response == "Entity in draft mode") { + // String name1 = "sample.pdf"; + // String secondaryPropertyString = "A"; + // Integer secondaryPropertyInt = 12; + // LocalDateTime secondaryPropertyDateTime = LocalDateTime.now(); + // String invalidProperty = "testidinvalid"; + // System.out.println("Renaming and updating invalid secondary properties for attachment"); + // String response1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime + "\"\n}")); + // String updateSecondaryPropertyResponse3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // // Update invalid secondary property + // String updateSecondaryPropertyResponse5 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, invalidProperty); + // if (response1 == "Renamed" + // && updateSecondaryPropertyResponse1 == "Updated" + // && updateSecondaryPropertyResponse2 == "Updated" + // && updateSecondaryPropertyResponse3 == "Updated" + // && updateSecondaryPropertyResponse4 == "Updated" + // && updateSecondaryPropertyResponse5 == "Updated") { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // Map attachmentMetadata = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); + // assertEquals("sample.pdf", attachmentMetadata.get("fileName")); + // assertNull(attachmentMetadata.get("customProperty3")); + // assertNull(attachmentMetadata.get("customProperty4")); + // assertNull(attachmentMetadata.get("customProperty1_code")); + // assertNull(attachmentMetadata.get("customProperty2")); + // assertNull(attachmentMetadata.get("customProperty6")); + // assertNull(attachmentMetadata.get("customProperty5")); + + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update secondary properties for attachment is unsuccessfull"); + // } + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - // Fetch attachment metadata to get objectId and verify secondary properties - Map sourceAttachmentMetadata = - api.fetchMetadata( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); + // @Test + // @Order(27) + // void testUpdateValidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (27): Rename & Update valid secondary properties for multiple attachments before + // entity is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID3 = response; + + // System.out.println("Entity created"); + + // System.out.println("Creating attachment PDF"); + // ClassLoader classLoader = getClass().getClassLoader(); + + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID3); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // List createResponse1 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData1, + // file); + // if (createResponse1.get(0).equals("Attachment created")) { + // attachmentID1 = createResponse1.get(1); + // System.out.println("Attachment created"); + // } - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId"); - } + // System.out.println("Creating attachment TXT"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // Map postData2 = new HashMap<>(); + // postData2.put("up__ID", entityID3); + // postData2.put("mimeType", "application/txt"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // List createResponse2 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData2, + // file); + // if (createResponse2.get(0).equals("Attachment created")) { + // attachmentID2 = createResponse2.get(1); + // System.out.println("Attachment created"); + // } - // Store objectId in array for reuse - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - if (sourceObjectIds.size() < 2) { - sourceObjectIds.add(sourceObjectId); - } else { - sourceObjectIds.set(1, sourceObjectId); - } + // System.out.println("Creating attachment EXE"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // Map postData3 = new HashMap<>(); + // postData3.put("up__ID", entityID3); + // postData3.put("mimeType", "application/exe"); + // postData3.put("createdAt", new Date().toString()); + // postData3.put("createdBy", "test@test.com"); + // postData3.put("modifiedBy", "test@test.com"); + + // List createResponse3 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData3, + // file); + // if (createResponse3.get(0).equals("Attachment created")) { + // attachmentID3 = createResponse3.get(1); + // System.out.println("Attachment created"); + // } - // Verify all secondary properties in source attachment - Boolean sourceCustomProperty6 = - sourceAttachmentMetadata.get("customProperty6") != null - ? (Boolean) sourceAttachmentMetadata.get("customProperty6") - : null; - Integer sourceCustomProperty2 = - sourceAttachmentMetadata.get("customProperty2") != null - ? (Integer) sourceAttachmentMetadata.get("customProperty2") - : null; - - if (sourceCustomProperty6 == null || !sourceCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly set in source attachment. Expected: true, Got: " - + sourceCustomProperty6); - } + // String check1 = createResponse1.get(0); + // String check2 = createResponse2.get(0); + // String check3 = createResponse3.get(0); + // if (check1.equals("Attachment created") + // && check2.equals("Attachment created") + // && check3.equals("Attachment created")) { + // Boolean attachment1Updated = false; + // Boolean attachment2Updated = false; + // Boolean attachment3Updated = false; + + // String name1 = "sample1234.pdf"; + // Integer secondaryPropertyInt1 = 1234; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // System.out.println("Renaming and updating secondary properties for attachment PDF"); + // String responsePDF1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponsePDF1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponsePDF2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponsePDF3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponsePDF4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // if (responsePDF1 == "Renamed" + // && updateSecondaryPropertyResponsePDF1 == "Updated" + // && updateSecondaryPropertyResponsePDF2 == "Updated" + // && updateSecondaryPropertyResponsePDF3 == "Updated" + // && updateSecondaryPropertyResponsePDF4 == "Updated") { + // System.out.println("Renamed & updated Secondary properties for attachment PDF"); + // attachment1Updated = true; + // } + + // System.out.println("Updating secondary properties for attachment TXT"); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); + // if (updateSecondaryPropertyResponseTXT1 == "Updated") { + // System.out.println("Updated Secondary properties for attachment TXT"); + // attachment2Updated = true; + // } + // Integer secondaryPropertyInt3 = 1234; + // LocalDateTime secondaryPropertyDateTime3 = LocalDateTime.now(); + // System.out.println("Updating secondary properties for attachment EXE"); + // // Update secondary properties for String + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); + // // Update secondary properties for Integer + // RequestBody bodyInt3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime3 + "\"\n}")); + // String updateSecondaryPropertyResponseEXE3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDateTime3); + + // if (updateSecondaryPropertyResponseEXE1 == "Updated" + // && updateSecondaryPropertyResponseEXE2 == "Updated" + // && updateSecondaryPropertyResponseEXE3 == "Updated") { + // System.out.println("Updated Secondary properties for attachment EXE"); + // attachment3Updated = true; + // } + + // if (attachment1Updated && attachment2Updated && attachment3Updated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachments"); + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - if (!customProperty2Value.equals(sourceCustomProperty2)) { - fail( - "customProperty2 was not properly set in source attachment. Expected: " - + customProperty2Value - + ", Got: " - + sourceCustomProperty2); - } + // @Test + // @Order(28) + // void testUpdateValidSecondaryProperty_afterEntityIsSaved_multipleAttachments() { + // System.out.println( + // "Test (28): Rename & Update valid secondary properties for multiple attachments after + // entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response == "Entity in draft mode") { + // Boolean attachment1Updated = false; + // Boolean attachment2Updated = false; + // Boolean attachment3Updated = false; + + // String name1 = "sample1.pdf"; + // Integer secondaryPropertyInt1 = 12; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // System.out.println("Renaming and updating secondary properties for attachment PDF"); + // String responsePDF1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue1 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown1 = "{ \"customProperty1_code\" : \"" + dropdownValue1 + "\" }"; + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown1); + // String updateSecondaryPropertyResponsePDF1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown1); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponsePDF2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponsePDF3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponsePDF4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + + // if (responsePDF1 == "Renamed" + // && updateSecondaryPropertyResponsePDF1 == "Updated" + // && updateSecondaryPropertyResponsePDF2 == "Updated" + // && updateSecondaryPropertyResponsePDF3 == "Updated" + // && updateSecondaryPropertyResponsePDF4 == "Updated") { + // System.out.println("Renamed & updated Secondary properties for attachment PDF"); + // attachment1Updated = true; + // } - String editTargetResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!editTargetResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity"); - } + // System.out.println("Updating secondary properties for attachment TXT"); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); + // if (updateSecondaryPropertyResponseTXT1 == "Updated") { + // System.out.println("Updated Secondary properties for attachment TXT"); + // attachment2Updated = true; + // } - // Copy attachment to target entity - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(1)); // Use objectId from array + // Integer secondaryPropertyInt3 = 123; + // LocalDateTime secondaryPropertyDateTime3 = LocalDateTime.now(); + // System.out.println("Updating secondary properties for attachment EXE"); + // // Update secondary properties for String + // String dropdownValue2 = integrationTestUtils.getDropDownValue(); + // String jsonDropdown2 = "{ \"customProperty1_code\" : \"" + dropdownValue2 + "\" }"; + // RequestBody bodyDropdown2 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown2); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown2); + // // Update secondary properties for Integer + // RequestBody bodyInt3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime3 + "\"\n}")); + // String updateSecondaryPropertyResponseEXE3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDateTime3); + + // if (updateSecondaryPropertyResponseEXE1 == "Updated" + // && updateSecondaryPropertyResponseEXE2 == "Updated" + // && updateSecondaryPropertyResponseEXE3 == "Updated") { + // System.out.println("Updated Secondary properties for attachment EXE"); + // attachment3Updated = true; + // } - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // if (attachment1Updated && attachment2Updated && attachment3Updated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response.equals("Saved")) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println("Renamed & updated Secondary properties for attachments"); + // } + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property after entity is saved"); + // } + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity: " + copyResponse); - } + // @Test + // @Order(29) + // void testUpdateInvalidSecondaryProperty_beforeEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (29): Rename & Update invalid and valid secondary properties for multiple + // attachments before entity is saved"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID3 = response; + + // System.out.println("Entity created"); + + // System.out.println("Creating attachment PDF"); + // ClassLoader classLoader = getClass().getClassLoader(); + + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID3); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // List createResponse1 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData1, + // file); + // if (createResponse1.get(0).equals("Attachment created")) { + // attachmentID1 = createResponse1.get(1); + // System.out.println("Attachment created"); + // } - // Save target entity - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity"); - } + // System.out.println("Creating attachment TXT"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // Map postData2 = new HashMap<>(); + // postData2.put("up__ID", entityID3); + // postData2.put("mimeType", "application/txt"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // List createResponse2 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData2, + // file); + // if (createResponse2.get(0).equals("Attachment created")) { + // attachmentID2 = createResponse2.get(1); + // System.out.println("Attachment created"); + // } - // Fetch target entity attachments metadata - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // System.out.println("Creating attachment EXE"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // Map postData3 = new HashMap<>(); + // postData3.put("up__ID", entityID3); + // postData3.put("mimeType", "application/exe"); + // postData3.put("createdAt", new Date().toString()); + // postData3.put("createdBy", "test@test.com"); + // postData3.put("modifiedBy", "test@test.com"); + + // List createResponse3 = + // api.createAttachment(appUrl, entityName, facetName, entityID3, srvpath, postData3, + // file); + // if (createResponse3.get(0).equals("Attachment created")) { + // attachmentID3 = createResponse3.get(1); + // System.out.println("Attachment created"); + // } - if (targetAttachmentsMetadata.isEmpty()) { - fail("No attachments found in target entity"); - } + // String check1 = createResponse1.get(0); + // String check2 = createResponse2.get(0); + // String check3 = createResponse3.get(0); + // if (check1.equals("Attachment created") + // && check2.equals("Attachment created") + // && check3.equals("Attachment created")) { + // Boolean attachment1Updated = false; + // Boolean attachment2Updated = false; + // Boolean attachment3Updated = false; + + // String name1 = "sample1234.pdf"; + // Integer secondaryPropertyInt1 = 1234; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // String invalidPropertyPDF = "testidinvalidPDF"; + // System.out.println("Renaming and updating invalid secondary properties for attachment + // PDF"); + // String responsePDF1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponsePDF1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyint = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponsePDF2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyint); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponsePDF3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponsePDF4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // // Update invalid secondary property + // String updateSecondaryPropertyResponsePDF5 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, invalidPropertyPDF); + // if (responsePDF1 == "Renamed" + // && updateSecondaryPropertyResponsePDF1 == "Updated" + // && updateSecondaryPropertyResponsePDF2 == "Updated" + // && updateSecondaryPropertyResponsePDF3 == "Updated" + // && updateSecondaryPropertyResponsePDF4 == "Updated" + // && updateSecondaryPropertyResponsePDF5 == "Updated") { + // attachment1Updated = true; + // } + + // System.out.println("Updating valid secondary properties for attachment TXT"); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); + // if (updateSecondaryPropertyResponseTXT1 == "Updated") { + // System.out.println("Updated Secondary properties for attachment TXT"); + // attachment2Updated = true; + // } + + // Integer secondaryPropertyInt3 = 1234; + // System.out.println("Updating valid secondary properties for attachment EXE"); + + // // Update secondary properties for String + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); + // // Update secondary properties for Integer + // RequestBody bodyInt3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); + + // if (updateSecondaryPropertyResponseEXE1 == "Updated" + // && updateSecondaryPropertyResponseEXE2 == "Updated") { + // System.out.println("Updated Secondary properties for attachment EXE"); + // attachment3Updated = true; + // } + + // if (attachment1Updated && attachment2Updated && attachment3Updated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // Map attachmentMetadataPDF = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); + // assertEquals("sample.pdf", attachmentMetadataPDF.get("fileName")); + // assertNull(attachmentMetadataPDF.get("customProperty3")); + // assertNull(attachmentMetadataPDF.get("customProperty4")); + // assertNull(attachmentMetadataPDF.get("customProperty1_code")); + // assertNull(attachmentMetadataPDF.get("customProperty2")); + // assertNull(attachmentMetadataPDF.get("customProperty6")); + // assertNull(attachmentMetadataPDF.get("customProperty5")); + + // Map attachmentMetadataTXT = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID2); + // assertEquals("sample.txt", attachmentMetadataTXT.get("fileName")); + // assertNull(attachmentMetadataTXT.get("customProperty3")); + // assertNull(attachmentMetadataTXT.get("customProperty4")); + // assertNull(attachmentMetadataTXT.get("customProperty1_code")); + // assertNull(attachmentMetadataTXT.get("customProperty2")); + // assertTrue((Boolean) attachmentMetadataTXT.get("customProperty6")); + // assertNull(attachmentMetadataTXT.get("customProperty5")); + + // Map attachmentMetadataEXE = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID3); + // assertEquals("sample.exe", attachmentMetadataEXE.get("fileName")); + // assertNull(attachmentMetadataEXE.get("customProperty3")); + // assertNull(attachmentMetadataEXE.get("customProperty4")); + // assertEquals(dropdownValue, attachmentMetadataEXE.get("customProperty1_code")); + // assertEquals(1234, attachmentMetadataEXE.get("customProperty2")); + + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update unsuccessfull for invalid Secondary properties and successfull + // for valid property attachments"); + // } + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - // Verify the copied attachment has the same secondary properties - // Find the attachment we just copied by matching the filename - Map copiedAttachmentMetadata = - targetAttachmentsMetadata.stream() - .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // @Test + // @Order(30) + // void testUpdateInvalidSecondaryProperty_afterEntityIsSaved_multipleAttachments() + // throws IOException { + // System.out.println( + // "Test (30): Rename & Update invalid and valid secondary properties for multiple + // attachments after entity is saved"); + // System.out.println("Editing entity"); + // Boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID3); + // if (response == "Entity in draft mode") { + // Boolean attachment1Updated = false; + // Boolean attachment2Updated = false; + // Boolean attachment3Updated = false; + + // String name1 = "sample.pdf"; + // Integer secondaryPropertyInt1 = 12; + // LocalDateTime secondaryPropertyDateTime1 = LocalDateTime.now(); + // String invalidPropertyPDF = "testidinvalidPDF"; + // System.out.println("Renaming and updating invalid secondary properties for attachment + // PDF"); + // String responsePDF1 = + // api.renameAttachment(appUrl, entityName, facetName, entityID3, attachmentID1, name1); + // // Update secondary properties for String + // String dropdownValue = integrationTestUtils.getDropDownValue(); + // String jsonDropdown = "{ \"customProperty1_code\" : \"" + dropdownValue + "\" }"; + // RequestBody bodyDropdown = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponsePDF1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDropdown); + // // Update secondary properties for Integer + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt1 + "\n}")); + // String updateSecondaryPropertyResponsePDF2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyInt); + // // Update secondary properties for DateTime + // RequestBody bodyDateTime = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty5\" : \"" + secondaryPropertyDateTime1 + "\"\n}")); + // String updateSecondaryPropertyResponsePDF3 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyDateTime); + // // Update secondary properties for Boolean + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponsePDF4 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, bodyBoolean); + // // Update invalid secondary property + // String updateSecondaryPropertyResponsePDF5 = + // api.updateInvalidSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID1, invalidPropertyPDF); + // if (responsePDF1 == "Renamed" + // && updateSecondaryPropertyResponsePDF1 == "Updated" + // && updateSecondaryPropertyResponsePDF2 == "Updated" + // && updateSecondaryPropertyResponsePDF3 == "Updated" + // && updateSecondaryPropertyResponsePDF4 == "Updated" + // && updateSecondaryPropertyResponsePDF5 == "Updated") { + // attachment1Updated = true; + // } - if (copiedAttachmentMetadata == null) { - fail("Could not find the copied attachment with file in target entity"); - } + // System.out.println("Updating valid secondary properties for attachment TXT"); + // // Update secondary properties for Boolean + // RequestBody bodyBool = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + false + "\n}")); + // String updateSecondaryPropertyResponseTXT1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID2, bodyBool); + // if (updateSecondaryPropertyResponseTXT1 == "Updated") { + // System.out.println("Updated Secondary properties for attachment TXT"); + // attachment2Updated = true; + // } - Boolean copiedCustomProperty6 = - copiedAttachmentMetadata.get("customProperty6") != null - ? (Boolean) copiedAttachmentMetadata.get("customProperty6") - : null; - Integer copiedCustomProperty2 = - copiedAttachmentMetadata.get("customProperty2") != null - ? (Integer) copiedAttachmentMetadata.get("customProperty2") - : null; - - // Verify DocumentInfoRecordBoolean - if (copiedCustomProperty6 == null || !copiedCustomProperty6) { - fail( - "DocumentInfoRecordBoolean as not properly copied. Expected: true, Got: " - + copiedCustomProperty6); - } + // Integer secondaryPropertyInt3 = 12; + // System.out.println("Updating valid secondary properties for attachment EXE"); + + // // Update secondary properties for String + // RequestBody bodyDropdown1 = + // RequestBody.create(MediaType.parse("application/json"), jsonDropdown); + // String updateSecondaryPropertyResponseEXE1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyDropdown1); + // // Update secondary properties for Integer + // RequestBody bodyInt3 = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8( + // "{\n \"customProperty2\" : " + secondaryPropertyInt3 + "\n}")); + // String updateSecondaryPropertyResponseEXE2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, entityID3, attachmentID3, bodyInt3); + + // if (updateSecondaryPropertyResponseEXE1 == "Updated" + // && updateSecondaryPropertyResponseEXE2 == "Updated") { + // System.out.println("Updated Secondary properties for attachment EXE"); + // attachment3Updated = true; + // } - // Verify customProperty2 - if (!customProperty2Value.equals(copiedCustomProperty2)) { - fail( - "customProperty2 was not properly copied. Expected: " - + customProperty2Value - + ", Got: " - + copiedCustomProperty2); - } + // if (attachment1Updated && attachment2Updated && attachment3Updated) { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID3); + // Map attachmentMetadataPDF = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID1); + // assertEquals("sample.pdf", attachmentMetadataPDF.get("fileName")); + // assertNull(attachmentMetadataPDF.get("customProperty3")); + // assertNull(attachmentMetadataPDF.get("customProperty4")); + // assertNull(attachmentMetadataPDF.get("customProperty1_code")); + // assertNull(attachmentMetadataPDF.get("customProperty2")); + // assertNull(attachmentMetadataPDF.get("customProperty6")); + // assertNull(attachmentMetadataPDF.get("customProperty5")); + + // Map attachmentMetadataTXT = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID2); + // assertEquals("sample.txt", attachmentMetadataTXT.get("fileName")); + // assertNull(attachmentMetadataTXT.get("customProperty3")); + // assertNull(attachmentMetadataTXT.get("customProperty4")); + // assertNull(attachmentMetadataTXT.get("customProperty1_code")); + // assertNull(attachmentMetadataTXT.get("customProperty2")); + // assertFalse((Boolean) attachmentMetadataTXT.get("customProperty6")); + // assertNull(attachmentMetadataTXT.get("customProperty5")); + + // Map attachmentMetadataEXE = + // api.fetchMetadata(appUrl, entityName, facetName, entityID3, attachmentID3); + // assertEquals("sample.exe", attachmentMetadataEXE.get("fileName")); + // assertNull(attachmentMetadataEXE.get("customProperty3")); + // assertNull(attachmentMetadataEXE.get("customProperty4")); + // assertEquals(dropdownValue, attachmentMetadataEXE.get("customProperty1_code")); + // assertEquals(12, attachmentMetadataEXE.get("customProperty2")); + + // String expectedResponse = + // "[{\"code\":\"\",\"message\":\"The following secondary properties are not + // supported.\\n" + // + // + // "\\n" + // + // + // "\\t\\u2022 id1\\n" + // + // + // "\\n" + // + // + // "Please contact your administrator for assistance with any necessary + // adjustments.\\n" + // + // + // "\\n" + // + // + // "Table: attachments\\n" + // + // + // "Page: IntegrationTestEntity\",\"numericSeverity\":3}]"; + // if (response.equals(expectedResponse)) { + // System.out.println("Entity saved"); + // testStatus = true; + // System.out.println( + // "Rename & update unsuccessfull for invalid Secondary properties and successfull for + // valid property attachments"); + // } + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID3); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } + // } + // } + // if (!testStatus) { + // fail("Could not update secondary property before entity is saved"); + // } + // } - // Verify attachment content can be read from target entity - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // @Test + // @Order(31) + // void testNAttachments_NewEntity() throws IOException { + // System.out.println( + // "Test (31): Creating new entity and checking only max 4 attachments are allowed to be + // uploaded"); + // System.out.println("Creating entity"); + // Boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (response != "Could not create entity") { + // entityID4 = response; + + // System.out.println("Entity created"); + + // System.out.println("Creating attachment PDF"); + // ClassLoader classLoader = getClass().getClassLoader(); + + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID4); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // List createResponse1 = + // api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData1, + // file); + // if (createResponse1.get(0).equals("Attachment created")) { + // attachmentID1 = createResponse1.get(1); + // System.out.println("Attachment created"); + // } - if (readResponse.equals("OK")) { - testStatus = true; - } - if (!testStatus) { - fail( - "Could not verify that all secondary properties were copied from source to target attachment"); - } - } + // System.out.println("Creating attachment TXT"); + // file = new File(classLoader.getResource("sample.txt").getFile()); + // Map postData2 = new HashMap<>(); + // postData2.put("up__ID", entityID4); + // postData2.put("mimeType", "application/txt"); + // postData2.put("createdAt", new Date().toString()); + // postData2.put("createdBy", "test@test.com"); + // postData2.put("modifiedBy", "test@test.com"); + + // List createResponse2 = + // api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData2, + // file); + // if (createResponse2.get(0).equals("Attachment created")) { + // attachmentID2 = createResponse2.get(1); + // System.out.println("Attachment created"); + // } - @Test - @Order(39) - void testCopyAttachmentWithNotesAndSecondaryPropertiesField() throws IOException { - System.out.println( - "Test (39): Verify that both notes field and secondary properties are preserved during attachment copy"); - Boolean testStatus = false; + // System.out.println("Creating attachment EXE"); + // file = new File(classLoader.getResource("sample.exe").getFile()); + // Map postData3 = new HashMap<>(); + // postData3.put("up__ID", entityID4); + // postData3.put("mimeType", "application/exe"); + // postData3.put("createdAt", new Date().toString()); + // postData3.put("createdBy", "test@test.com"); + // postData3.put("modifiedBy", "test@test.com"); + + // List createResponse3 = + // api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, + // file); + // if (createResponse3.get(0).equals("Attachment created")) { + // attachmentID3 = createResponse3.get(1); + // System.out.println("Attachment created"); + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity"); - } + // System.out.println("Creating second attachment pdf"); + // file = new File(classLoader.getResource("sample1.pdf").getFile()); + // Map postData4 = new HashMap<>(); + // postData4.put("up__ID", entityID4); + // postData4.put("mimeType", "application/pdf"); + // postData4.put("createdAt", new Date().toString()); + // postData4.put("createdBy", "test@test.com"); + // postData4.put("modifiedBy", "test@test.com"); + + // List createResponse4 = + // api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, + // file); + // if (createResponse4.get(0).equals("Attachment created")) { + // attachmentID4 = createResponse4.get(1); + // System.out.println("Attachment created"); + // } - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample2.pdf").getFile()); + // System.out.println("Creating third attachment pdf"); + // file = new File(classLoader.getResource("sample2.pdf").getFile()); + // Map postData5 = new HashMap<>(); + // postData5.put("up__ID", entityID4); + // postData5.put("mimeType", "application/pdf"); + // postData5.put("createdAt", new Date().toString()); + // postData5.put("createdBy", "test@test.com"); + // postData5.put("modifiedBy", "test@test.com"); + + // List createResponse5 = + // api.createAttachment(appUrl, entityName, facetName, entityID4, srvpath, postData3, + // file); + // if (createResponse5.get(0).equals("Only 4 attachments allowed.")) { + // testStatus = true; + // attachmentID5 = createResponse5.get(1); + // System.out.println("Expected error received: Only 4 attachments allowed."); + // } + // String check = createResponse5.get(0); + // if (check.equals("Attachment created")) { + // testStatus = false; + // } else { + // response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID4); + // if (response.equals("Saved")) { + // String expectedJson = + // "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 + // attachments.\"}}"; + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode actualJsonNode = objectMapper.readTree(check); + // JsonNode expectedJsonNode = objectMapper.readTree(expectedJson); + // if (expectedJsonNode.equals(actualJsonNode)) { + // testStatus = true; + // } + // } + // } + // } + // if (!testStatus) { + // fail("Attachment was created"); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", copyCustomSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // @Test + // @Order(32) + // void testUploadNAttachments() throws IOException { + // System.out.println("Test (32): Upload maximum 4 attachments in an exsisting entity"); - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); + // ClassLoader classLoader = getClass().getClassLoader(); + // File originalFile = new File(classLoader.getResource("sample.exe").getFile()); + + // boolean testStatus = false; + // String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID4); + // System.out.println("response: " + response); + + // if ("Entity in draft mode".equals(response)) { + // for (int i = 1; i <= 5; i++) { + // // Ensure only one file is uploaded at a time and complete before next + // File tempFile = File.createTempFile("sample_" + i + "_", ".exe"); + // Files.copy(originalFile.toPath(), tempFile.toPath(), + // StandardCopyOption.REPLACE_EXISTING); + + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID4); + // postData.put("mimeType", "application/exe"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, entityID4, srvpath, postData, tempFile); + + // String resultMessage = createResponse.get(0); + // System.out.println("Result message for attachment " + i + ": " + resultMessage); + + // String expectedResponse = + // "{\"error\":{\"code\":\"500\",\"message\":\"Cannot upload more than 4 + // attachments.\"}}"; + // if (resultMessage.equals(expectedResponse)) { + // ObjectMapper objectMapper = new ObjectMapper(); + // JsonNode actualJsonNode = objectMapper.readTree(resultMessage); + // JsonNode expectedJsonNode = objectMapper.readTree(expectedResponse); + // if (expectedJsonNode.equals(actualJsonNode)) { + // testStatus = true; + // } + // } else { + // testStatus = false; + // } + // tempFile.delete(); + // } + // if (!testStatus) { + // fail("5th attachment did not trigger the expected error."); + // } + // // Delete the newly created entity + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, entityID4); + // if (deleteEntityResponse != "Entity Deleted") { + // fail("Could not delete entity"); + // } else { + // System.out.println("Successfully deleted the test entity4"); + // } + // } + // } - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment"); - } + // @Test + // @Order(33) + // void testDiscardDraftWithoutAttachments() { + // System.out.println("Test (33) : Discard draft without adding attachments"); - String sourceAttachmentId = createResponse.get(1); + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - // Update attachment with notes field - String notesValue = "This attachment has both notes and secondary properties for testing"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + // if (response.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - copyCustomSourceEntity, - sourceAttachmentId, - updateNotesBody); + // response = api.deleteEntityDraft(appUrl, entityName, response); + // if (!response.equals("Entity Draft Deleted")) { + // fail("Draft was not discarded properly"); + // } + // } - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update attachment notes field"); - } + // @Test + // @Order(34) + // void testDiscardDraftWithAttachments() throws IOException { + // System.out.println("Test (34) : Discard draft with attachments"); + // boolean testStatus = false; + // String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!response.equals("Could not create entity")) { + // entityID7 = response; + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + + // Map postData1 = new HashMap<>(); + // postData1.put("up__ID", entityID7); + // postData1.put("mimeType", "application/pdf"); + // postData1.put("createdAt", new Date().toString()); + // postData1.put("createdBy", "test@test.com"); + // postData1.put("modifiedBy", "test@test.com"); + + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, entityID7, srvpath, postData1, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachmentID1 = createResponse.get(1); + // } + // String check = createResponse.get(0); + // if (check.equals("Attachment created")) { + // response = api.deleteEntityDraft(appUrl, entityName, entityID7); + // } + // if (response.equals("Entity Draft Deleted")) { + // testStatus = true; + // } + // } + // if (!testStatus) { + // fail("Draft was not discarded properly"); + // } + // } - // Update attachment with secondary properties - // DocumentInfoRecordBoolean : Set to true - RequestBody bodyBoolean = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); - String updateSecondaryPropertyResponse1 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyBoolean); - - if (!updateSecondaryPropertyResponse1.equals("Updated")) { - fail( - "Could not update attachment DocumentInfoRecordBoolean (customProperty6) field. Response: " - + updateSecondaryPropertyResponse1); - } + // @Test + // @Order(35) + // void testCopyAttachmentsSuccessNewEntity() throws IOException { + // System.out.println("Test (35): Copy attachments from one entity to another new entity"); + // List attachments = new ArrayList<>(); + // copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!copyAttachmentSourceEntity.equals("Could not create entity") + // && !copyAttachmentTargetEntity.equals("Could not create entity")) { + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample1.pdf").getFile())); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (String attachment : attachments) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadata( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } - // customProperty2 : Set to 99999 - Integer customProperty2Value = 99999; - RequestBody bodyInt = - RequestBody.create( - MediaType.parse("application/json"), - ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); - String updateSecondaryPropertyResponse2 = - api.updateSecondaryProperty( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); - - if (!updateSecondaryPropertyResponse2.equals("Updated")) { - fail( - "Could not update attachment customProperty2 field. Response: " - + updateSecondaryPropertyResponse2); - } + // if (sourceObjectIds.size() == 2) { + // String copyResponse; + // copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); + // if (copyResponse.equals("Attachments copied successfully")) { + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadata(appUrl, entityName, facetName, + // copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not create entities"); + // } + // } - // Save source entity - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity. Response: " + saveSourceResponse); - } + // @Test + // @Order(36) + // void testCopyAttachmentsUnsuccessfulNewEntity() throws IOException { + // System.out.println("Test (36): Copy attachments from one entity to another new entity"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // copyAttachmentTargetEntityEmpty = + // api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (editResponse1.equals("Entity in draft mode") + // && !copyAttachmentTargetEntityEmpty.equals("Could not create entity")) { + // sourceObjectIds.add("incorrectObjectId"); + // if (sourceObjectIds.size() == 3) { + // try { + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntityEmpty, sourceObjectIds); + // fail("Copy attachments did not throw an error"); + // } catch (IOException e) { + // String saveEntityResponse1 = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String saveEntityResponse2 = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntityEmpty); + // String deleteResponse = + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntityEmpty); + // if (!saveEntityResponse1.equals("Saved") + // || !saveEntityResponse2.equals("Saved") + // || !deleteResponse.equals("Entity Deleted")) { + // fail("Could not save entities"); + // } + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - // Fetch attachment metadata to get objectId and verify notes and secondary properties - Map sourceAttachmentMetadata = - api.fetchMetadata( - appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); + // @Test + // @Order(37) + // void testCopyAttachmentWithNotesField() throws IOException { + // System.out.println( + // "Test (37): Create entity with attachment containing notes, copy to new entity and verify + // notes field"); + // Boolean testStatus = false; + // // Create source entity + // copyCustomSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyCustomSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - if (!sourceAttachmentMetadata.containsKey("objectId")) { - fail("Source attachment metadata does not contain objectId"); - } + // // Create and upload attachment to source entity + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); - if (sourceObjectIds.size() < 3) { - sourceObjectIds.add(sourceObjectId); - } else { - sourceObjectIds.set(2, sourceObjectId); - } + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - String sourceNoteValue = - sourceAttachmentMetadata.get("note") != null - ? sourceAttachmentMetadata.get("note").toString() - : null; - - if (!notesValue.equals(sourceNoteValue)) { - fail( - "Notes field was not properly set in source attachment. Expected: " - + notesValue - + ", Got: " - + sourceNoteValue); - } + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment"); + // } - Boolean sourceCustomProperty6 = - sourceAttachmentMetadata.get("customProperty6") != null - ? (Boolean) sourceAttachmentMetadata.get("customProperty6") - : null; - Integer sourceCustomProperty2 = - sourceAttachmentMetadata.get("customProperty2") != null - ? (Integer) sourceAttachmentMetadata.get("customProperty2") - : null; - - if (sourceCustomProperty6 == null || !sourceCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly set in source attachment. Expected: true, Got: " - + sourceCustomProperty6); - } + // String sourceAttachmentId = createResponse.get(1); - if (!customProperty2Value.equals(sourceCustomProperty2)) { - fail( - "customProperty2 was not properly set in source attachment. Expected: " - + customProperty2Value - + ", Got: " - + sourceCustomProperty2); - } + // // Update attachment with notes field + // String notesValue = "This is a test note for copy attachment verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateBody = RequestBody.create(jsonPayload, mediaType); - String editTargetResponse = - api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!editTargetResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity"); - } + // String updateResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, + // updateBody); - // Copy attachment to target entity - List objectIdsToCopy = new ArrayList<>(); - objectIdsToCopy.add(sourceObjectIds.get(2)); // Use objectId from array + // if (!updateResponse.equals("Updated")) { + // fail("Could not update attachment notes field"); + // } - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, objectIdsToCopy); + // // Save source entity + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity"); + // } - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy attachment to target entity: " + copyResponse); - } + // // Fetch attachment metadata to get objectId + // Map sourceAttachmentMetadata = + // api.fetchMetadata( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); - // Save target entity - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity"); - } + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId"); + // } - // Fetch target entity attachments metadata - List> targetAttachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); + // // Store objectId in array + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // if (sourceObjectIds.isEmpty()) { + // sourceObjectIds.add(sourceObjectId); + // } else { + // sourceObjectIds.set(0, sourceObjectId); + // } - if (targetAttachmentsMetadata.isEmpty()) { - fail("No attachments found in target entity"); - } + // String sourceNoteValue = + // sourceAttachmentMetadata.get("note") != null + // ? sourceAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(sourceNoteValue)) { + // fail( + // "Notes field was not properly set in source attachment. Expected: " + // + notesValue + // + ", Got: " + // + sourceNoteValue); + // } - // Verify the copied attachment has the same notes and secondary properties - // Find the attachment we just copied by matching the filename - Map copiedAttachmentMetadata = - targetAttachmentsMetadata.stream() - .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) - .findFirst() - .orElse(null); + // // Create target entity + // copyCustomTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyCustomTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - if (copiedAttachmentMetadata == null) { - fail("Could not find the copied attachment with fil in target entity"); - } + // // Copy attachment to target entity + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(0)); // Use objectId from array - // Verify notes field was copied - String copiedNoteValue = - copiedAttachmentMetadata.get("note") != null - ? copiedAttachmentMetadata.get("note").toString() - : null; - - if (!notesValue.equals(copiedNoteValue)) { - fail( - "Notes field was not properly copied. Expected: " - + notesValue - + ", Got: " - + copiedNoteValue); - } + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, + // objectIdsToCopy); - // Verify secondary properties were copied - Boolean copiedCustomProperty6 = - copiedAttachmentMetadata.get("customProperty6") != null - ? (Boolean) copiedAttachmentMetadata.get("customProperty6") - : null; - Integer copiedCustomProperty2 = - copiedAttachmentMetadata.get("customProperty2") != null - ? (Integer) copiedAttachmentMetadata.get("customProperty2") - : null; - - // Verify DocumentInfoRecordBoolean - if (copiedCustomProperty6 == null || !copiedCustomProperty6) { - fail( - "DocumentInfoRecordBoolean was not properly copied. Expected: true, Got: " - + copiedCustomProperty6); - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity: " + copyResponse); + // } - // Verify customProperty2 - if (!customProperty2Value.equals(copiedCustomProperty2)) { - fail( - "customProperty2 was not properly copied. Expected: " - + customProperty2Value - + ", Got: " - + copiedCustomProperty2); - } + // // Save target entity + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity"); + // } - // Verify attachment content can be read from target entity - String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); - String readResponse = - api.readAttachment( - appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); + // // Fetch target entity attachments metadata + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - if (readResponse.equals("OK")) { - testStatus = true; - } - if (!testStatus) { - fail( - "Could not verify that notes field and all secondary properties were copied from source to target attachment"); - } - api.deleteEntity(appUrl, entityName, copyCustomSourceEntity); - api.deleteEntity(appUrl, entityName, copyCustomTargetEntity); - } + // if (targetAttachmentsMetadata.isEmpty()) { + // fail("No attachments found in target entity"); + // } - @Test - @Order(40) - void testCopyAttachmentsSuccessExistingEntity() throws IOException { - System.out.println("Test (40): Copy attachments from one entity to another existing entity"); - List attachments = new ArrayList<>(); - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - File file1 = new File(classLoader.getResource("sample.pdf").getFile()); - File file2 = new File(classLoader.getResource("sample1.pdf").getFile()); - File tempFile1 = new File(System.getProperty("java.io.tmpdir"), "sample_copy_existing_1.pdf"); - Files.copy(file1.toPath(), tempFile1.toPath(), StandardCopyOption.REPLACE_EXISTING); - File tempFile2 = new File(System.getProperty("java.io.tmpdir"), "sample_copy_existing_2.pdf"); - Files.copy(file2.toPath(), tempFile2.toPath(), StandardCopyOption.REPLACE_EXISTING); - files.add(tempFile1); - files.add(tempFile2); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String editResponse2 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (editResponse1.equals("Entity in draft mode") - && editResponse2.equals("Entity in draft mode")) { - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (String attachment : attachments) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadata( - appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Verify the copied attachment has the same notes value + // Map copiedAttachmentMetadata = targetAttachmentsMetadata.get(0); + // String copiedNoteValue = + // copiedAttachmentMetadata.get("note") != null + // ? copiedAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(copiedNoteValue)) { + // fail( + // "Notes field was not properly copied. Expected: " + // + notesValue + // + ", Got: " + // + copiedNoteValue); + // } - sourceObjectIds.clear(); - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } + // // Verify attachment content can be read from target entity + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - if (sourceObjectIds.size() == 2) { - String copyResponse; - copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); - if (copyResponse.equals("Attachments copied successfully")) { - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - if (targetAttachmentIds.size() == 4) { - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } - // api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); - // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // if (readResponse.equals("OK")) { + // testStatus = true; + // } + // if (!testStatus) { + // fail("Could not verify that notes field was copied from source to target attachment"); + // } + // } - @Test - @Order(41) - void testCopyAttachmentsUnsuccessfulExistingEntity() throws IOException { - System.out.println( - "Test (41): Copy attachments from one entity to another existing entity - unsuccessful"); - String editResponse1 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - String editResponse2 = - api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (editResponse1.equals("Entity in draft mode") - && editResponse2.equals("Entity in draft mode")) { - sourceObjectIds.add("incorrectObjectId"); - if (sourceObjectIds.size() == 3) { - try { - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); - fail("Copy attachments did not throw an error"); - } catch (IOException e) { - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not edit entities"); - } - } + // @Test + // @Order(38) + // void testCopyAttachmentWithSecondaryPropertiesField() throws IOException { + // System.out.println( + // "Test (38): Verify that secondary properties are preserved when copying attachments + // between entities"); + // Boolean testStatus = false; + + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyCustomSourceEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity"); + // } - @Test - @Order(42) - void testCreateLinkSuccess() throws IOException { - System.out.println("Test (42): Create link in entity"); - List attachments = new ArrayList<>(); - createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!createLinkEntity.equals("Could not create entity")) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse1 = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - String createLinkResponse2 = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName + "1", linkUrl); - if (createLinkResponse1.equals("Link created successfully") - && createLinkResponse2.equals("Link created successfully")) { - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (saveEntityResponse.equals("Saved")) { - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String openAttachmentResponse; - for (String attachment : attachments) { - openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, createLinkEntity, attachment); - System.out.println("openAttachmentResponse: " + openAttachmentResponse); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open created link"); - } - } - } else { - fail("Could not save entity"); - } - } else { - fail("Could not create link"); - } - } else { - fail("Could not create entity"); - } - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample1.pdf").getFile()); - @Test - @Order(43) - void testCreateLinkDifferentEntity() throws IOException { - System.out.println("Test (43): Create link with same name in different entity"); - String createLinkDifferentEntity = - api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!createLinkDifferentEntity.equals("Could not edit entity")) { - String linkName = "sample"; - String linkUrl = "https://example.com"; - String createResponse = - api.createLink( - appUrl, entityName, facetName, createLinkDifferentEntity, linkName, linkUrl); - if (!createResponse.equals("Link created successfully")) { - fail("Could not create link in different entity with same name"); - } - String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkDifferentEntity); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } - response = api.deleteEntity(appUrl, entityName, createLinkDifferentEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } else { - fail("Could not edit entity"); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - @Test - @Order(44) - void testCreateLinkFailure() throws IOException { - System.out.println("Test (44): Create link fails due to invalid URL and name"); - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Could not edit entity")) { - String linkName = "sample"; - String linkUrl = "example.com"; - try { - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - fail("Create link did not throw an error for invalid url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("400018", errorCode); - assertTrue( - errorMessage.equals("Enter a value that is within the expected pattern.") - || errorMessage.equals("Enter a value that matches the expected pattern."), - "Unexpected error message: " + errorMessage); - } - try { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName + "//", "https://" + linkUrl); - fail("Create link did not throw an error for invalid name"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = - "\"sample//\" contains unsupported characters (‘/’ or ‘\\’). Rename and try again."; - assertEquals("500", errorCode); - assertEquals( - expected.replaceAll("\\s+", " ").trim(), errorMessage.replaceAll("\\s+", " ").trim()); - } - try { - api.createLink(appUrl, entityName, facetName, createLinkEntity, "", ""); - fail("Create link did not throw an error for empty name and url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = "Provide the missing value."; - assertEquals("409008", errorCode); - assertEquals(expected, errorMessage); - } - try { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName, "https://" + linkUrl); - fail("Create link did not throw an error for duplicate name"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals( - "An object named \"sample\" already exists. Rename the object and try again.", - errorMessage); - } - try { - for (int i = 2; i < 5; i++) { - api.createLink( - appUrl, entityName, facetName, createLinkEntity, linkName + i, "https://" + linkUrl); - } - fail("More than 5 links were created in the same entity"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals("Cannot upload more than 4 attachments.", errorMessage); - } - String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } - response = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } else { - fail("Could not edit entity"); - } - } + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - @Test - @Order(45) - void testCreateLinkNoSDMRoles() throws IOException { - System.out.println("Test (45): Create link fails due to no SDM roles assigned"); - String createLinkEntityNoSDMRoles = - apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!createLinkEntityNoSDMRoles.equals("Could not edit entity")) { - String linkName = "sample27"; - String linkUrl = "https://example.com"; - try { - apiNoRoles.createLink( - appUrl, entityName, facetName, createLinkEntityNoSDMRoles, linkName, linkUrl); - fail("Link got created without SDM roles"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals( - "You do not have the required permissions to upload attachments. Please contact your administrator for access.", - errorMessage); - } - String response = - apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntityNoSDMRoles); - if (!response.equals("Saved")) { - fail("Could not save entity"); - } - response = api.deleteEntity(appUrl, entityName, createLinkEntityNoSDMRoles); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } else { - fail("Could not edit entity"); - } - } + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment"); + // } - @Test - @Order(46) - void testDeleteLink() throws IOException { - System.out.println("Test (46): Delete link in entity"); - List attachments = new ArrayList<>(); - String createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!createLinkEntity.equals("Could not create entity")) { - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (createLinkResponse.equals("Link created successfully")) { - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (saveEntityResponse.equals("Saved")) { - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String editEntityResponse = - api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } - String deleteLinkResponse = - api.deleteAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(0)); - if (!deleteLinkResponse.equals("Deleted")) { - fail("Could not delete created link"); - } else { - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - if (attachments.size() != 0) { - fail("Link wasn't deleted"); - } - String response = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!response.equals("Entity Deleted")) { - fail("Could not delete entity"); - } - } - } else { - fail("Could not save entity"); - } - } else { - fail("Could not create link"); - } - } else { - fail("Could not create entity"); - } - } + // String sourceAttachmentId = createResponse.get(1); + + // // Update attachment with secondary properties + // // DocumentInfoRecordBoolean : Set to true + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, + // bodyBoolean); + + // if (!updateSecondaryPropertyResponse1.equals("Updated")) { + // fail( + // "Could not update attachment DocumentInfoRecordBoolean field. Response: " + // + updateSecondaryPropertyResponse1); + // } - @Test - @Order(47) - void testRenameLinkSuccess() throws IOException { - System.out.println("Test (47): Rename link in entity"); - List attachments = new ArrayList<>(); + // // customProperty2 : Set to 12345 + // Integer customProperty2Value = 12345; + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); + + // if (!updateSecondaryPropertyResponse2.equals("Updated")) { + // fail( + // "Could not update attachment customProperty2 field. Response: " + // + updateSecondaryPropertyResponse2); + // } - createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (createLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } + // // Save source entity + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity. Response: " + saveSourceResponse); + // } - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } + // // Fetch attachment metadata to get objectId and verify secondary properties + // Map sourceAttachmentMetadata = + // api.fetchMetadata( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId"); + // } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // // Store objectId in array for reuse + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // if (sourceObjectIds.size() < 2) { + // sourceObjectIds.add(sourceObjectId); + // } else { + // sourceObjectIds.set(1, sourceObjectId); + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // // Verify all secondary properties in source attachment + // Boolean sourceCustomProperty6 = + // sourceAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) sourceAttachmentMetadata.get("customProperty6") + // : null; + // Integer sourceCustomProperty2 = + // sourceAttachmentMetadata.get("customProperty2") != null + // ? (Integer) sourceAttachmentMetadata.get("customProperty2") + // : null; + + // if (sourceCustomProperty6 == null || !sourceCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly set in source attachment. Expected: true, + // Got: " + // + sourceCustomProperty6); + // } - attachmentID9 = attachments.get(0); - String renameLinkResponse = - api.renameAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(0), "sampleRenamed"); - if (!renameLinkResponse.equals("Renamed")) fail("Could not Renamed created link"); + // if (!customProperty2Value.equals(sourceCustomProperty2)) { + // fail( + // "customProperty2 was not properly set in source attachment. Expected: " + // + customProperty2Value + // + ", Got: " + // + sourceCustomProperty2); + // } - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } - } + // String editTargetResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!editTargetResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity"); + // } - @Test - @Order(48) - void testRenameLinkDuplicate() throws IOException { - System.out.println("Test (48): Rename link in entity fails due to duplicate error"); - List attachments = new ArrayList<>(); - - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // // Copy attachment to target entity + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(1)); // Use objectId from array - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, + // objectIdsToCopy); - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity: " + copyResponse); + // } - editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // // Save target entity + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity"); + // } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - .filter(item -> !attachmentID9.equals(item.get("ID"))) // skip unwanted filename - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - attachmentID10 = attachments.get(0); - api.renameAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(0), "sampleRenamed"); - - String saveError = - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - String expectedWarning = - "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sampleRenamed\\\" already exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - ObjectMapper mapper = new ObjectMapper(); - assertEquals(mapper.readTree(expectedWarning), mapper.readTree(saveError)); - - String deleteEntityResponse = api.deleteEntityDraft(appUrl, entityName, createLinkEntity); - if (!deleteEntityResponse.equals("Entity Draft Deleted")) { - fail("Entity draft not deleted"); - } - } + // // Fetch target entity attachments metadata + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - @Test - @Order(49) - void testRenameLinkUnsupportedCharacters() throws IOException { - System.out.println( - "Test (49): Rename link in entity fails due to unsupported characters in name"); - List attachments = new ArrayList<>(); + // if (targetAttachmentsMetadata.isEmpty()) { + // fail("No attachments found in target entity"); + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // // Verify the copied attachment has the same secondary properties + // // Find the attachment we just copied by matching the filename + // Map copiedAttachmentMetadata = + // targetAttachmentsMetadata.stream() + // .filter(attachment -> "sample1.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - String linkName = "sample2"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } + // if (copiedAttachmentMetadata == null) { + // fail("Could not find the copied attachment with file in target entity"); + // } - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } + // Boolean copiedCustomProperty6 = + // copiedAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) copiedAttachmentMetadata.get("customProperty6") + // : null; + // Integer copiedCustomProperty2 = + // copiedAttachmentMetadata.get("customProperty2") != null + // ? (Integer) copiedAttachmentMetadata.get("customProperty2") + // : null; + + // // Verify DocumentInfoRecordBoolean + // if (copiedCustomProperty6 == null || !copiedCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean as not properly copied. Expected: true, Got: " + // + copiedCustomProperty6); + // } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() - // .filter(item -> "sample2".equals(item.get("filename"))) // skip unwanted filename - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - System.out.println("attachments: " + attachments); - - editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } + // // Verify customProperty2 + // if (!customProperty2Value.equals(copiedCustomProperty2)) { + // fail( + // "customProperty2 was not properly copied. Expected: " + // + customProperty2Value + // + ", Got: " + // + copiedCustomProperty2); + // } - api.renameAttachment( - appUrl, entityName, facetName, createLinkEntity, attachments.get(0), "sampleRenamed//"); - String warning = - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); - String expectedWarning = - "{\"error\":{\"code\":\"400\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: IntegrationTestEntity\"}}"; - ObjectMapper mapper = new ObjectMapper(); - assertEquals(mapper.readTree(expectedWarning), mapper.readTree(warning)); - - String deleteEntityResponse = api.deleteEntity(appUrl, entityName, createLinkEntity); - if (!deleteEntityResponse.equals("Entity Deleted")) { - fail("Entity draft not deleted"); - } - } + // // Verify attachment content can be read from target entity + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - @Test - @Order(50) - void testEditLinkSuccess() throws IOException { - System.out.println("Test (50): Edit existing link in entity"); + // if (readResponse.equals("OK")) { + // testStatus = true; + // } + // if (!testStatus) { + // fail( + // "Could not verify that all secondary properties were copied from source to target + // attachment"); + // } + // } - List attachments = new ArrayList<>(); - editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (editLinkEntity.equals("Could not create entity")) { - fail("Could not create entity"); - } - String linkName = "sample"; - String linkUrl = "https://www.example.com"; + // @Test + // @Order(39) + // void testCopyAttachmentWithNotesAndSecondaryPropertiesField() throws IOException { + // System.out.println( + // "Test (39): Verify that both notes field and secondary properties are preserved during + // attachment copy"); + // Boolean testStatus = false; + + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // copyCustomSourceEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity"); + // } - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link"); - } + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample2.pdf").getFile()); - String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - if (attachments.isEmpty()) { - fail("Could not edit link"); - } - String linkId = attachments.get(0); - String updatedUrl = "https://editedexample.com"; - String editLinkResponse = - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - if (!editLinkResponse.equals("Link edited successfully")) { - fail("Could not edit link"); - } - saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!saveEntityResponse.equals("Saved")) { - fail("Could not save entity"); - } - String openAttachmentResponse; - for (String attachment : attachments) { - openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, editLinkEntity, attachment); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open created link"); - } - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", copyCustomSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - @Test - @Order(51) - void testEditLinkFailureInvalidURL() throws IOException { - System.out.println("Test (51): Edit existing link with invalid url"); - Boolean testStatus = false; - List attachments = new ArrayList<>(); + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyCustomSourceEntity, srvpath, postData, file); - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - if (attachments.isEmpty()) { - fail("Could not edit link"); - } - String linkId = attachments.get(0); - String updatedUrl = "https://editedexample"; - try { - - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - fail("Create link did not throw an error for invalid url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("400018", errorCode); - assertTrue( - errorMessage.equals("Enter a value that is within the expected pattern.") - || errorMessage.equals("Enter a value that matches the expected pattern."), - "Unexpected error message: " + errorMessage); + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment"); + // } - testStatus = true; - } - api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!testStatus) { - fail("Could not edit link with an invalid URL"); - } - } + // String sourceAttachmentId = createResponse.get(1); + + // // Update attachment with notes field + // String notesValue = "This attachment has both notes and secondary properties for testing"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // copyCustomSourceEntity, + // sourceAttachmentId, + // updateNotesBody); + + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update attachment notes field"); + // } - @Test - @Order(52) - void testEditLinkFailureEmptyURL() throws IOException { - System.out.println("Test (52): Edit existing link with an empty url"); - Boolean testStatus = false; - List attachments = new ArrayList<>(); + // // Update attachment with secondary properties + // // DocumentInfoRecordBoolean : Set to true + // RequestBody bodyBoolean = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty6\" : " + true + "\n}")); + // String updateSecondaryPropertyResponse1 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, + // bodyBoolean); + + // if (!updateSecondaryPropertyResponse1.equals("Updated")) { + // fail( + // "Could not update attachment DocumentInfoRecordBoolean (customProperty6) field. + // Response: " + // + updateSecondaryPropertyResponse1); + // } - String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } - attachments = - api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - if (attachments.isEmpty()) { - fail("Could not edit link"); - } - String linkId = attachments.get(0); - String updatedUrl = ""; - try { - api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - fail("edit link did not throw an error for empty url"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - String expected = "Provide the missing value."; - assertEquals("409008", errorCode); - assertEquals(expected, errorMessage); - testStatus = true; - } - api.deleteEntityDraft(appUrl, entityName, editLinkEntity); - if (!testStatus) { - fail("Could not edit link with an empty URL"); - } - } + // // customProperty2 : Set to 99999 + // Integer customProperty2Value = 99999; + // RequestBody bodyInt = + // RequestBody.create( + // MediaType.parse("application/json"), + // ByteString.encodeUtf8("{\n \"customProperty2\" : " + customProperty2Value + "\n}")); + // String updateSecondaryPropertyResponse2 = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId, bodyInt); + + // if (!updateSecondaryPropertyResponse2.equals("Updated")) { + // fail( + // "Could not update attachment customProperty2 field. Response: " + // + updateSecondaryPropertyResponse2); + // } - @Test - @Order(53) - void testEditLinkNoSDMRoles() throws IOException { - System.out.println("Test (53): Edit link fails due to no SDM roles assigned"); + // // Save source entity + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity. Response: " + saveSourceResponse); + // } - Boolean testStatus = false; - List attachments = new ArrayList<>(); + // // Fetch attachment metadata to get objectId and verify notes and secondary properties + // Map sourceAttachmentMetadata = + // api.fetchMetadata( + // appUrl, entityName, facetName, copyCustomSourceEntity, sourceAttachmentId); - String editEntityResponse = - apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); - if (!editEntityResponse.equals("Entity in draft mode")) { - fail("Could not edit entity"); - } - attachments = - apiNoRoles.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - - if (attachments.isEmpty()) { - fail("Could not edit link"); - } - String linkId = attachments.get(0); - String updatedUrl = "https://www.example1.com"; - try { - apiNoRoles.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); - fail("Link got edited without SDM roles in facet: \" + facetName"); - } catch (IOException e) { - String message = e.getMessage(); - int jsonStart = message.indexOf("{"); - String jsonPart = message.substring(jsonStart); - JSONObject json = new JSONObject(jsonPart); - String errorCode = json.getJSONObject("error").getString("code"); - String errorMessage = json.getJSONObject("error").getString("message"); - assertEquals("500", errorCode); - assertEquals( - "You do not have the required permissions to update attachments. Kindly contact the admin", - errorMessage); - testStatus = true; - } - apiNoRoles.deleteEntity(appUrl, entityName, createLinkEntity); - if (!testStatus) { - fail("Link got edited without SDM roles"); - } - api.deleteEntity(appUrl, entityName, editLinkEntity); - } + // if (!sourceAttachmentMetadata.containsKey("objectId")) { + // fail("Source attachment metadata does not contain objectId"); + // } - @Test - @Order(54) - void testCopyLinkSuccessNewEntity() throws IOException { - System.out.println("Test (54): Copy link from one entity to another new entity"); - List> attachmentsMetadata = new ArrayList<>(); + // String sourceObjectId = sourceAttachmentMetadata.get("objectId").toString(); + // if (sourceObjectIds.size() < 3) { + // sourceObjectIds.add(sourceObjectId); + // } else { + // sourceObjectIds.set(2, sourceObjectId); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // String sourceNoteValue = + // sourceAttachmentMetadata.get("note") != null + // ? sourceAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(sourceNoteValue)) { + // fail( + // "Notes field was not properly set in source attachment. Expected: " + // + notesValue + // + ", Got: " + // + sourceNoteValue); + // } - if (copyLinkSourceEntity.equals("Could not create entity") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not create source or target entity"); - } + // Boolean sourceCustomProperty6 = + // sourceAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) sourceAttachmentMetadata.get("customProperty6") + // : null; + // Integer sourceCustomProperty2 = + // sourceAttachmentMetadata.get("customProperty2") != null + // ? (Integer) sourceAttachmentMetadata.get("customProperty2") + // : null; + + // if (sourceCustomProperty6 == null || !sourceCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly set in source attachment. Expected: true, + // Got: " + // + sourceCustomProperty6); + // } - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link in source entity"); - } + // if (!customProperty2Value.equals(sourceCustomProperty2)) { + // fail( + // "customProperty2 was not properly set in source attachment. Expected: " + // + customProperty2Value + // + ", Got: " + // + sourceCustomProperty2); + // } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // String editTargetResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!editTargetResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity"); + // } - List sourceObjectIds = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // // Copy attachment to target entity + // List objectIdsToCopy = new ArrayList<>(); + // objectIdsToCopy.add(sourceObjectIds.get(2)); // Use objectId from array - if (sourceObjectIds.isEmpty()) { - fail("Could not fetch object Id for link"); - } + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyCustomTargetEntity, + // objectIdsToCopy); - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy link: " + copyResponse); - } + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy attachment to target entity: " + copyResponse); + // } - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveResponse.equals("Saved")) { - fail("Could not save target entity after copying link"); - } + // // Save target entity + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyCustomTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity"); + // } - attachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // // Fetch target entity attachments metadata + // List> targetAttachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyCustomTargetEntity); - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch. Expected '" - + expectedType - + "' but got '" - + receivedType - + "'."); - - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); - - System.out.println("Attachment type and URL validated successfully."); - - String attachmentId = (String) copiedAttachment.get("ID"); - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open the attachment"); - } + // if (targetAttachmentsMetadata.isEmpty()) { + // fail("No attachments found in target entity"); + // } - String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - if (!deleteSourceResponse.equals("Entity Deleted") - || !deleteTargetResponse.equals("Entity Deleted")) { - fail("could not delete source or target entity"); - } - } + // // Verify the copied attachment has the same notes and secondary properties + // // Find the attachment we just copied by matching the filename + // Map copiedAttachmentMetadata = + // targetAttachmentsMetadata.stream() + // .filter(attachment -> "sample2.pdf".equals(attachment.get("fileName"))) + // .findFirst() + // .orElse(null); - @Test - @Order(55) - void testCopyLinkUnsuccessfulNewEntity() throws IOException { - System.out.println( - "Test (55): Copy invalid type of link from one entity to another new entity"); + // if (copiedAttachmentMetadata == null) { + // fail("Could not find the copied attachment with fil in target entity"); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // // Verify notes field was copied + // String copiedNoteValue = + // copiedAttachmentMetadata.get("note") != null + // ? copiedAttachmentMetadata.get("note").toString() + // : null; + + // if (!notesValue.equals(copiedNoteValue)) { + // fail( + // "Notes field was not properly copied. Expected: " + // + notesValue + // + ", Got: " + // + copiedNoteValue); + // } - if (copyLinkSourceEntity.equals("Could not create entity") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not create source or target entity"); - } + // // Verify secondary properties were copied + // Boolean copiedCustomProperty6 = + // copiedAttachmentMetadata.get("customProperty6") != null + // ? (Boolean) copiedAttachmentMetadata.get("customProperty6") + // : null; + // Integer copiedCustomProperty2 = + // copiedAttachmentMetadata.get("customProperty2") != null + // ? (Integer) copiedAttachmentMetadata.get("customProperty2") + // : null; + + // // Verify DocumentInfoRecordBoolean + // if (copiedCustomProperty6 == null || !copiedCustomProperty6) { + // fail( + // "DocumentInfoRecordBoolean was not properly copied. Expected: true, Got: " + // + copiedCustomProperty6); + // } - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - List invalidObjectIds = Collections.singletonList("incorrectObjectId"); + // // Verify customProperty2 + // if (!customProperty2Value.equals(copiedCustomProperty2)) { + // fail( + // "customProperty2 was not properly copied. Expected: " + // + customProperty2Value + // + ", Got: " + // + copiedCustomProperty2); + // } - try { - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, invalidObjectIds); - fail("Copy attachments did not throw error for invalid ID"); - } catch (IOException e) { - System.out.println("Caught expected error: " + e.getMessage()); - } + // // Verify attachment content can be read from target entity + // String targetAttachmentId = (String) copiedAttachmentMetadata.get("ID"); + // String readResponse = + // api.readAttachment( + // appUrl, entityName, facetName, copyCustomTargetEntity, targetAttachmentId); - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveResponse.equals("Saved")) { - fail("Could not save target entity after unsuccessful copy"); - } + // if (readResponse.equals("OK")) { + // testStatus = true; + // } + // if (!testStatus) { + // fail( + // "Could not verify that notes field and all secondary properties were copied from source + // to target attachment"); + // } + // api.deleteEntity(appUrl, entityName, copyCustomSourceEntity); + // api.deleteEntity(appUrl, entityName, copyCustomTargetEntity); + // } - String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - if (!deleteSourceResponse.equals("Entity Deleted")) { - fail("Could not delete source entity"); - } - } + // @Test + // @Order(40) + // void testCopyAttachmentsSuccessExistingEntity() throws IOException { + // System.out.println("Test (40): Copy attachments from one entity to another existing entity"); + // List attachments = new ArrayList<>(); + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // File file1 = new File(classLoader.getResource("sample.pdf").getFile()); + // File file2 = new File(classLoader.getResource("sample1.pdf").getFile()); + // File tempFile1 = new File(System.getProperty("java.io.tmpdir"), + // "sample_copy_existing_1.pdf"); + // Files.copy(file1.toPath(), tempFile1.toPath(), StandardCopyOption.REPLACE_EXISTING); + // File tempFile2 = new File(System.getProperty("java.io.tmpdir"), + // "sample_copy_existing_2.pdf"); + // Files.copy(file2.toPath(), tempFile2.toPath(), StandardCopyOption.REPLACE_EXISTING); + // files.add(tempFile1); + // files.add(tempFile2); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String editResponse2 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (editResponse1.equals("Entity in draft mode") + // && editResponse2.equals("Entity in draft mode")) { + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (String attachment : attachments) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadata( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - @Test - @Order(56) - void testCopyLinkFromNewEntityToExistingEntity() throws IOException { - System.out.println("Test (56): Copy link from a new entity to an existing target entity"); - List> attachmentsMetadata = new ArrayList<>(); - - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyLinkSourceEntity.equals("Could not create entity")) { - fail("Could not create new source entity"); - } + // sourceObjectIds.clear(); + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } - String linkName = "Sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link in new source entity"); - } + // if (sourceObjectIds.size() == 2) { + // String copyResponse; + // copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); + // if (copyResponse.equals("Attachments copied successfully")) { + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadata(appUrl, entityName, facetName, + // copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // if (targetAttachmentIds.size() == 4) { + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } + // // api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); + // // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save new source entity"); - } + // @Test + // @Order(41) + // void testCopyAttachmentsUnsuccessfulExistingEntity() throws IOException { + // System.out.println( + // "Test (41): Copy attachments from one entity to another existing entity - unsuccessful"); + // String editResponse1 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // String editResponse2 = + // api.editEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (editResponse1.equals("Entity in draft mode") + // && editResponse2.equals("Entity in draft mode")) { + // sourceObjectIds.add("incorrectObjectId"); + // if (sourceObjectIds.size() == 3) { + // try { + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); + // fail("Copy attachments did not throw an error"); + // } catch (IOException e) { + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentSourceEntity); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentSourceEntity); + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not edit entities"); + // } + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } + // @Test + // @Order(42) + // void testCreateLinkSuccess() throws IOException { + // System.out.println("Test (42): Create link in entity"); + // List attachments = new ArrayList<>(); + // createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!createLinkEntity.equals("Could not create entity")) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse1 = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // String createLinkResponse2 = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName + "1", + // linkUrl); + // if (createLinkResponse1.equals("Link created successfully") + // && createLinkResponse2.equals("Link created successfully")) { + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (saveEntityResponse.equals("Saved")) { + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String openAttachmentResponse; + // for (String attachment : attachments) { + // openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, createLinkEntity, attachment); + // System.out.println("openAttachmentResponse: " + openAttachmentResponse); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open created link"); + // } + // } + // } else { + // fail("Could not save entity"); + // } + // } else { + // fail("Could not create link"); + // } + // } else { + // fail("Could not create entity"); + // } + // } - List sourceObjectIds = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // @Test + // @Order(43) + // void testCreateLinkDifferentEntity() throws IOException { + // System.out.println("Test (43): Create link with same name in different entity"); + // String createLinkDifferentEntity = + // api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!createLinkDifferentEntity.equals("Could not edit entity")) { + // String linkName = "sample"; + // String linkUrl = "https://example.com"; + // String createResponse = + // api.createLink( + // appUrl, entityName, facetName, createLinkDifferentEntity, linkName, linkUrl); + // if (!createResponse.equals("Link created successfully")) { + // fail("Could not create link in different entity with same name"); + // } + // String response = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkDifferentEntity); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } + // response = api.deleteEntity(appUrl, entityName, createLinkDifferentEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } else { + // fail("Could not edit entity"); + // } + // } - if (sourceObjectIds.isEmpty()) { - fail("Could not fetch objectId from new source entity"); - } + // @Test + // @Order(44) + // void testCreateLinkFailure() throws IOException { + // System.out.println("Test (44): Create link fails due to invalid URL and name"); + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Could not edit entity")) { + // String linkName = "sample"; + // String linkUrl = "example.com"; + // try { + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // fail("Create link did not throw an error for invalid url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("400018", errorCode); + // assertTrue( + // errorMessage.equals("Enter a value that is within the expected pattern.") + // || errorMessage.equals("Enter a value that matches the expected pattern."), + // "Unexpected error message: " + errorMessage); + // } + // try { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName + "//", "https://" + + // linkUrl); + // fail("Create link did not throw an error for invalid name"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = + // "\"sample//\" contains unsupported characters (‘/’ or ‘\\’). Rename and try again."; + // assertEquals("500", errorCode); + // assertEquals( + // expected.replaceAll("\\s+", " ").trim(), errorMessage.replaceAll("\\s+", " + // ").trim()); + // } + // try { + // api.createLink(appUrl, entityName, facetName, createLinkEntity, "", ""); + // fail("Create link did not throw an error for empty name and url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = "Provide the missing value."; + // assertEquals("409008", errorCode); + // assertEquals(expected, errorMessage); + // } + // try { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName, "https://" + linkUrl); + // fail("Create link did not throw an error for duplicate name"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals( + // "An object named \"sample\" already exists. Rename the object and try again.", + // errorMessage); + // } + // try { + // for (int i = 2; i < 5; i++) { + // api.createLink( + // appUrl, entityName, facetName, createLinkEntity, linkName + i, "https://" + + // linkUrl); + // } + // fail("More than 5 links were created in the same entity"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals("Cannot upload more than 4 attachments.", errorMessage); + // } + // String response = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } + // response = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } else { + // fail("Could not edit entity"); + // } + // } - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy link from new source entity to existing target entity: " + copyResponse); - } + // @Test + // @Order(45) + // void testCreateLinkNoSDMRoles() throws IOException { + // System.out.println("Test (45): Create link fails due to no SDM roles assigned"); + // String createLinkEntityNoSDMRoles = + // apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!createLinkEntityNoSDMRoles.equals("Could not edit entity")) { + // String linkName = "sample27"; + // String linkUrl = "https://example.com"; + // try { + // apiNoRoles.createLink( + // appUrl, entityName, facetName, createLinkEntityNoSDMRoles, linkName, linkUrl); + // fail("Link got created without SDM roles"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals( + // "You do not have the required permissions to upload attachments. Please contact your + // administrator for access.", + // errorMessage); + // } + // String response = + // apiNoRoles.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntityNoSDMRoles); + // if (!response.equals("Saved")) { + // fail("Could not save entity"); + // } + // response = api.deleteEntity(appUrl, entityName, createLinkEntityNoSDMRoles); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } else { + // fail("Could not edit entity"); + // } + // } - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // @Test + // @Order(46) + // void testDeleteLink() throws IOException { + // System.out.println("Test (46): Delete link in entity"); + // List attachments = new ArrayList<>(); + // String createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!createLinkEntity.equals("Could not create entity")) { + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (createLinkResponse.equals("Link created successfully")) { + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (saveEntityResponse.equals("Saved")) { + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String editEntityResponse = + // api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } + // String deleteLinkResponse = + // api.deleteAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(0)); + // if (!deleteLinkResponse.equals("Deleted")) { + // fail("Could not delete created link"); + // } else { + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // if (attachments.size() != 0) { + // fail("Link wasn't deleted"); + // } + // String response = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!response.equals("Entity Deleted")) { + // fail("Could not delete entity"); + // } + // } + // } else { + // fail("Could not save entity"); + // } + // } else { + // fail("Could not create link"); + // } + // } else { + // fail("Could not create entity"); + // } + // } - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity after copying link"); - } + // @Test + // @Order(47) + // void testRenameLinkSuccess() throws IOException { + // System.out.println("Test (47): Rename link in entity"); + // List attachments = new ArrayList<>(); - attachmentsMetadata = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // createLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (createLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch. Expected '" - + expectedType - + "' but got '" - + receivedType - + "'."); + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - System.out.println("Attachment type and URL validated successfully."); + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - String attachmentId = (String) copiedAttachment.get("ID"); - assertNotNull(attachmentId, "Could not find 'ID' in the copied attachment metadata."); + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open the attachment"); - } + // attachmentID9 = attachments.get(0); + // String renameLinkResponse = + // api.renameAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(0), + // "sampleRenamed"); + // if (!renameLinkResponse.equals("Renamed")) fail("Could not Renamed created link"); - String deleteResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - if (!deleteResponse.equals("Entity Deleted")) { - fail("Could not delete new source entity"); - } - } + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } + // } - @Test - @Order(57) - void testCopyInvalidLinkFromNewEntityToExistingEntity() throws IOException { - System.out.println( - "Test (57): Copy invalid type of link from new entity to existing target entity"); + // @Test + // @Order(48) + // void testRenameLinkDuplicate() throws IOException { + // System.out.println("Test (48): Rename link in entity fails due to duplicate error"); + // List attachments = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (copyLinkSourceEntity.equals("Could not create entity")) { - fail("Could not create new source entity"); - } + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } - String linkName = "Sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link in new source entity"); - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - String saveSourceResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save new source entity"); - } + // editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!editResponse.equals("Entity in draft mode")) { - fail("Could not edit target entity draft"); - } + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // .filter(item -> !attachmentID9.equals(item.get("ID"))) // skip unwanted filename + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // attachmentID10 = attachments.get(0); + // api.renameAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(0), "sampleRenamed"); + + // String saveError = + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // String expectedWarning = + // "{\"error\":{\"code\":\"400\",\"message\":\"An object named \\\"sampleRenamed\\\" already + // exists. Rename the object and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // ObjectMapper mapper = new ObjectMapper(); + // assertEquals(mapper.readTree(expectedWarning), mapper.readTree(saveError)); + + // String deleteEntityResponse = api.deleteEntityDraft(appUrl, entityName, createLinkEntity); + // if (!deleteEntityResponse.equals("Entity Draft Deleted")) { + // fail("Entity draft not deleted"); + // } + // } - List invalidObjectIds = Collections.singletonList("invalidObjectId123"); + // @Test + // @Order(49) + // void testRenameLinkUnsupportedCharacters() throws IOException { + // System.out.println( + // "Test (49): Rename link in entity fails due to unsupported characters in name"); + // List attachments = new ArrayList<>(); - try { - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, invalidObjectIds); - fail("Copy did not throw error for invalid link ID"); - } catch (IOException e) { - System.out.println("Caught expected error while copying invalid link: " + e.getMessage()); - } + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - // No need to wait for upload completion as copy failed, but ensure clean state - String saveTargetResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity after unsuccessful copy"); - } + // String linkName = "sample2"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, createLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } - String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); - String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - if (!deleteSourceResponse.equals("Entity Deleted") - || !deleteTargetResponse.equals("Entity Deleted")) { - fail("Could not delete new source entity or target entity"); - } - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // createLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } - @Test - @Order(58) - void testCopyLinkSuccessNewEntityDraft() throws IOException { - System.out.println("Test (58): Copy link from one entity to another new entity draft mode"); + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, createLinkEntity).stream() + // // .filter(item -> "sample2".equals(item.get("filename"))) // skip unwanted filename + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // System.out.println("attachments: " + attachments); + + // editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } - copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // api.renameAttachment( + // appUrl, entityName, facetName, createLinkEntity, attachments.get(0), "sampleRenamed//"); + // String warning = + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, createLinkEntity); + // String expectedWarning = + // "{\"error\":{\"code\":\"400\",\"message\":\"\\\"sampleRenamed//\\\" contains unsupported + // characters (‘/’ or ‘\\\\’). Rename and try again.\\n\\nTable: attachments\\nPage: + // IntegrationTestEntity\"}}"; + // ObjectMapper mapper = new ObjectMapper(); + // assertEquals(mapper.readTree(expectedWarning), mapper.readTree(warning)); + + // String deleteEntityResponse = api.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!deleteEntityResponse.equals("Entity Deleted")) { + // fail("Entity draft not deleted"); + // } + // } - if (copyLinkSourceEntity.equals("Could not create entity") - || copyLinkTargetEntity.equals("Could not create entity")) { - fail("Could not create source or target entity"); - } + // @Test + // @Order(50) + // void testEditLinkSuccess() throws IOException { + // System.out.println("Test (50): Edit existing link in entity"); - String linkName = "sample"; - String linkUrl = "https://www.example.com"; - String createLinkResponse = - api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); - if (!createLinkResponse.equals("Link created successfully")) { - fail("Could not create link in source entity"); - } + // List attachments = new ArrayList<>(); + // editLinkEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (editLinkEntity.equals("Could not create entity")) { + // fail("Could not create entity"); + // } + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; - List sourceObjectIds = - api.fetchEntityMetadataDraft(appUrl, entityName, facetName, copyLinkSourceEntity).stream() - .map(item -> (String) item.get("objectId")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, editLinkEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link"); + // } - if (sourceObjectIds.isEmpty()) { - fail("Could not fetch object Id for link"); - } + // String saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // if (attachments.isEmpty()) { + // fail("Could not edit link"); + // } + // String linkId = attachments.get(0); + // String updatedUrl = "https://editedexample.com"; + // String editLinkResponse = + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // if (!editLinkResponse.equals("Link edited successfully")) { + // fail("Could not edit link"); + // } + // saveEntityResponse = api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!saveEntityResponse.equals("Saved")) { + // fail("Could not save entity"); + // } + // String openAttachmentResponse; + // for (String attachment : attachments) { + // openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, editLinkEntity, attachment); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open created link"); + // } + // } + // } - String copyResponse = - api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); - if (!copyResponse.equals("Attachments copied successfully")) { - fail("Could not copy link: " + copyResponse); - } + // @Test + // @Order(51) + // void testEditLinkFailureInvalidURL() throws IOException { + // System.out.println("Test (51): Edit existing link with invalid url"); + // Boolean testStatus = false; + // List attachments = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // if (attachments.isEmpty()) { + // fail("Could not edit link"); + // } + // String linkId = attachments.get(0); + // String updatedUrl = "https://editedexample"; + // try { + + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // fail("Create link did not throw an error for invalid url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("400018", errorCode); + // assertTrue( + // errorMessage.equals("Enter a value that is within the expected pattern.") + // || errorMessage.equals("Enter a value that matches the expected pattern."), + // "Unexpected error message: " + errorMessage); + + // testStatus = true; + // } + // api.saveEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!testStatus) { + // fail("Could not edit link with an invalid URL"); + // } + // } - List> attachmentsMetadata = new ArrayList<>(); - attachmentsMetadata = - api.fetchEntityMetadataDraft(appUrl, entityName, facetName, copyLinkTargetEntity); - Map copiedAttachment = attachmentsMetadata.get(0); - String receivedType = (String) copiedAttachment.get("type"); - String receivedUrl = (String) copiedAttachment.get("linkUrl"); + // @Test + // @Order(52) + // void testEditLinkFailureEmptyURL() throws IOException { + // System.out.println("Test (52): Edit existing link with an empty url"); + // Boolean testStatus = false; + // List attachments = new ArrayList<>(); + + // String editEntityResponse = api.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } + // attachments = + // api.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // if (attachments.isEmpty()) { + // fail("Could not edit link"); + // } + // String linkId = attachments.get(0); + // String updatedUrl = ""; + // try { + // api.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // fail("edit link did not throw an error for empty url"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // String expected = "Provide the missing value."; + // assertEquals("409008", errorCode); + // assertEquals(expected, errorMessage); + // testStatus = true; + // } + // api.deleteEntityDraft(appUrl, entityName, editLinkEntity); + // if (!testStatus) { + // fail("Could not edit link with an empty URL"); + // } + // } - String expectedType = "sap-icon://internet-browser"; - assertTrue( - expectedType.equalsIgnoreCase(receivedType), - "Attachment type mismatch. Expected '" - + expectedType - + "' but got '" - + receivedType - + "'."); + // @Test + // @Order(53) + // void testEditLinkNoSDMRoles() throws IOException { + // System.out.println("Test (53): Edit link fails due to no SDM roles assigned"); - assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); + // Boolean testStatus = false; + // List attachments = new ArrayList<>(); - System.out.println("Attachment type and URL validated successfully."); + // String editEntityResponse = + // apiNoRoles.editEntityDraft(appUrl, entityName, srvpath, editLinkEntity); + // if (!editEntityResponse.equals("Entity in draft mode")) { + // fail("Could not edit entity"); + // } + // attachments = + // apiNoRoles.fetchEntityMetadata(appUrl, entityName, facetName, editLinkEntity).stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + + // if (attachments.isEmpty()) { + // fail("Could not edit link"); + // } + // String linkId = attachments.get(0); + // String updatedUrl = "https://www.example1.com"; + // try { + // apiNoRoles.editLink(appUrl, entityName, facetName, editLinkEntity, linkId, updatedUrl); + // fail("Link got edited without SDM roles in facet: \" + facetName"); + // } catch (IOException e) { + // String message = e.getMessage(); + // int jsonStart = message.indexOf("{"); + // String jsonPart = message.substring(jsonStart); + // JSONObject json = new JSONObject(jsonPart); + // String errorCode = json.getJSONObject("error").getString("code"); + // String errorMessage = json.getJSONObject("error").getString("message"); + // assertEquals("500", errorCode); + // assertEquals( + // "You do not have the required permissions to update attachments. Kindly contact the + // admin", + // errorMessage); + // testStatus = true; + // } + // apiNoRoles.deleteEntity(appUrl, entityName, createLinkEntity); + // if (!testStatus) { + // fail("Link got edited without SDM roles"); + // } + // api.deleteEntity(appUrl, entityName, editLinkEntity); + // } - String attachmentId = (String) copiedAttachment.get("ID"); - assertNotNull(attachmentId, "Could not find 'ID' in the copied attachment metadata."); + // @Test + // @Order(54) + // void testCopyLinkSuccessNewEntity() throws IOException { + // System.out.println("Test (54): Copy link from one entity to another new entity"); + // List> attachmentsMetadata = new ArrayList<>(); - String openAttachmentResponse = - api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); - if (!openAttachmentResponse.equals("Attachment opened successfully")) { - fail("Could not open the attachment"); - } + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - if (!saveResponse.equals("Saved")) { - fail("Could not save target entity after copying link"); - } - api.deleteEntityDraft(appUrl, entityName, copyLinkSourceEntity); - api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); - } + // if (copyLinkSourceEntity.equals("Could not create entity") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not create source or target entity"); + // } - @Test - @Order(59) - void testCopyAttachmentsSuccessNewEntityDraft() throws IOException { - System.out.println( - "Test (59): Copy attachments from one entity to another new entity draft mode"); - List attachments = new ArrayList<>(); - copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (!copyAttachmentSourceEntity.equals("Could not create entity") - && !copyAttachmentTargetEntity.equals("Could not create entity")) { - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample1.pdf").getFile())); - Map postData = new HashMap<>(); - postData.put("up__ID", entityID7); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); - - sourceObjectIds.clear(); - - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - attachments.add(createResponse.get(1)); - } else { - fail("Could not create attachment"); - } - } + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link in source entity"); + // } - List> attachmentsMetadata = new ArrayList<>(); - Map fetchAttachmentMetadataResponse; - for (String attachment : attachments) { - try { - fetchAttachmentMetadataResponse = - api.fetchMetadataDraft( - appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); - attachmentsMetadata.add(fetchAttachmentMetadataResponse); - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } - for (Map metadata : attachmentsMetadata) { - if (metadata.containsKey("objectId")) { - sourceObjectIds.add(metadata.get("objectId").toString()); - } else { - fail("Attachment metadata does not contain objectId"); - } - } + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); - if (sourceObjectIds.size() == 2) { - String copyResponse; - copyResponse = - api.copyAttachment( - appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); - if (copyResponse.equals("Attachments copied successfully")) { - String saveEntityResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); - if (saveEntityResponse.equals("Saved")) { - List> fetchEntityMetadataResponse; - fetchEntityMetadataResponse = - api.fetchEntityMetadata(appUrl, entityName, facetName, copyAttachmentTargetEntity); - targetAttachmentIds = - fetchEntityMetadataResponse.stream() - .map(item -> (String) item.get("ID")) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - String readResponse; - for (String targetAttachmentId : targetAttachmentIds) { - readResponse = - api.readAttachment( - appUrl, - entityName, - facetName, - copyAttachmentTargetEntity, - targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read copied attachment"); - } - } - } else { - fail("Could not save entity after copying attachments: " + saveEntityResponse); - } - } else { - fail("Could not copy attachments: " + copyResponse); - } - } else { - fail("Could not fetch objects Ids for all attachments"); - } - } else { - fail("Could not create entities"); - } - api.deleteEntityDraft(appUrl, entityName, copyAttachmentSourceEntity); - api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); - } + // List sourceObjectIds = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - @Test - @Order(60) - void testViewChangelogForNewlyCreatedAttachment() throws IOException { - System.out.println("Test (60): View changelog for newly created attachment"); + // if (sourceObjectIds.isEmpty()) { + // fail("Could not fetch object Id for link"); + // } - // Create a new entity for changelog test - changelogEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(changelogEntityID, "Failed to create changelog test entity"); - assertNotEquals("Could not create entity", changelogEntityID); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy link: " + copyResponse); + // } - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.txt").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveResponse.equals("Saved")) { + // fail("Could not save target entity after copying link"); + // } - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", changelogEntityID); - postData.put("mimeType", "text/plain"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // attachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); + + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch. Expected '" + // + expectedType + // + "' but got '" + // + receivedType + // + "'."); + + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); + + // System.out.println("Attachment type and URL validated successfully."); + + // String attachmentId = (String) copiedAttachment.get("ID"); + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open the attachment"); + // } - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, changelogEntityID, srvpath, postData, file); + // String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // if (!deleteSourceResponse.equals("Entity Deleted") + // || !deleteTargetResponse.equals("Entity Deleted")) { + // fail("could not delete source or target entity"); + // } + // } - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - changelogAttachmentID = createResponse.get(1); + // @Test + // @Order(55) + // void testCopyLinkUnsuccessfulNewEntity() throws IOException { + // System.out.println( + // "Test (55): Copy invalid type of link from one entity to another new entity"); - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(changelogAttachmentID, "Attachment ID should not be null"); - assertNotEquals("", changelogAttachmentID, "Attachment ID should not be empty"); + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - // Fetch changelog for the newly created attachment - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID); + // if (copyLinkSourceEntity.equals("Could not create entity") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not create source or target entity"); + // } - assertNotNull(changelogResponse, "Changelog response should not be null"); + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // List invalidObjectIds = Collections.singletonList("incorrectObjectId"); - // Verify changelog structure - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - "sample.txt", changelogResponse.get("filename"), "Filename should match uploaded file"); - assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); - assertEquals(1, changelogResponse.get("numItems"), "Should have 1 changelog entry"); - - // Verify the changelog entry - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); - - Map logEntry = changeLogs.get(0); - assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); - assertNotNull(logEntry.get("time"), "Time should not be null"); - assertNotNull(logEntry.get("user"), "User should not be null"); - assertFalse( - logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); - } + // try { + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, invalidObjectIds); + // fail("Copy attachments did not throw error for invalid ID"); + // } catch (IOException e) { + // System.out.println("Caught expected error: " + e.getMessage()); + // } - @Test - @Order(61) - void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { - System.out.println( - "Test (61): Modify note field and custom property, then verify changelog shows created + 3 updated entries"); + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveResponse.equals("Saved")) { + // fail("Could not save target entity after unsuccessful copy"); + // } - // Update attachment with notes field (entity is already in draft mode from test 60) - String notesValue = "Test note for changelog verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + // String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // if (!deleteSourceResponse.equals("Entity Deleted")) { + // fail("Could not delete source entity"); + // } + // } - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - changelogEntityID, - changelogAttachmentID, - updateNotesBody); - assertEquals("Updated", updateNotesResponse, "Should successfully update notes field"); - - // Update attachment with custom property - Integer customProperty2Value = 12345; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID, bodyInt); - assertEquals( - "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + // @Test + // @Order(56) + // void testCopyLinkFromNewEntityToExistingEntity() throws IOException { + // System.out.println("Test (56): Copy link from a new entity to an existing target entity"); + // List> attachmentsMetadata = new ArrayList<>(); + + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyLinkSourceEntity.equals("Could not create entity")) { + // fail("Could not create new source entity"); + // } - // Save the entity - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // String linkName = "Sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link in new source entity"); + // } - // Edit entity again to fetch changelog - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save new source entity"); + // } - // Fetch changelog after modifications - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID); + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } - assertNotNull(changelogResponse, "Changelog response should not be null"); + // List sourceObjectIds = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - // Verify changelog content - should have 1 created + 3 updated (note, customProperty2, and - // internal update) - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - 4, - changelogResponse.get("numItems"), - "Should have 4 changelog entries (1 created + 3 updated)"); + // if (sourceObjectIds.isEmpty()) { + // fail("Could not fetch objectId from new source entity"); + // } - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(4, changeLogs.size(), "Should have exactly 4 changelog entries"); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy link from new source entity to existing target entity: " + + // copyResponse); + // } - // Verify first entry is 'created' - Map createdEntry = changeLogs.get(0); - assertEquals( - "created", createdEntry.get("operation"), "First entry should be 'created' operation"); - - // Verify remaining entries are 'updated' - long updatedCount = - changeLogs.stream().filter(log -> "updated".equals(log.get("operation"))).count(); - assertEquals(3, updatedCount, "Should have 3 'updated' operations"); - - // Verify that changeDetail exists in updated entries for note field - boolean hasNoteUpdate = - changeLogs.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .anyMatch( - log -> { - @SuppressWarnings("unchecked") - Map changeDetail = (Map) log.get("changeDetail"); - return changeDetail != null - && "cmis:description".equals(changeDetail.get("field")); - }); - assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); - assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); - - // Save the entity so test 62 can edit it - String saveResponseFinal = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Saved", saveResponseFinal, "Entity should be saved successfully"); - } + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); - @Test - @Order(62) - void testChangelogAfterRenamingAttachment() throws IOException { - System.out.println( - "Test (62): Rename attachment and verify changelog increases with rename entry"); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity after copying link"); + // } - // Edit entity to put it in draft mode (entity was saved at end of test 61) - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // attachmentsMetadata = + // api.fetchEntityMetadata(appUrl, entityName, facetName, copyLinkTargetEntity); + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); - // Rename the attachment - String newFileName = "renamed_sample.txt"; - String renameResponse = - api.renameAttachment( - appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID, newFileName); - assertEquals("Renamed", renameResponse, "Should successfully rename attachment"); + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch. Expected '" + // + expectedType + // + "' but got '" + // + receivedType + // + "'."); - // Save entity after rename - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully after rename"); + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); - // Edit entity again and fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // System.out.println("Attachment type and URL validated successfully."); - // Fetch changelog after rename - Map changelogAfterRename = - api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID); + // String attachmentId = (String) copiedAttachment.get("ID"); + // assertNotNull(attachmentId, "Could not find 'ID' in the copied attachment metadata."); - assertNotNull(changelogAfterRename, "Changelog response should not be null after rename"); + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open the attachment"); + // } - // Verify changelog has increased (rename operation adds 1 entry for cmis:name change) - // Expected: 1 created + 3 initial updates + 1 rename update = 5 total - assertEquals( - 5, changelogAfterRename.get("numItems"), "Should have 5 changelog entries after rename"); + // String deleteResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // if (!deleteResponse.equals("Entity Deleted")) { + // fail("Could not delete new source entity"); + // } + // } - @SuppressWarnings("unchecked") - List> changeLogsAfterRename = - (List>) changelogAfterRename.get("changeLogs"); - assertEquals( - 5, changeLogsAfterRename.size(), "Should have exactly 5 changelog entries after rename"); - - // Verify updated count is 4 (3 initial + 1 from rename operation) - long updatedCountAfterRename = - changeLogsAfterRename.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .count(); - assertEquals(4, updatedCountAfterRename, "Should have 4 'updated' operations after rename"); - - // Verify filename change in changelog - boolean hasFilenameUpdate = - changeLogsAfterRename.stream() - .filter(log -> "updated".equals(log.get("operation"))) - .anyMatch( - log -> { - @SuppressWarnings("unchecked") - Map changeDetail = (Map) log.get("changeDetail"); - return changeDetail != null && "cmis:name".equals(changeDetail.get("field")); - }); - assertTrue(hasFilenameUpdate, "Should have an update entry for filename (cmis:name)"); - - // Cleanup - entity was saved after rename, so delete the active entity - api.deleteEntity(appUrl, entityName, changelogEntityID); - } + // @Test + // @Order(57) + // void testCopyInvalidLinkFromNewEntityToExistingEntity() throws IOException { + // System.out.println( + // "Test (57): Copy invalid type of link from new entity to existing target entity"); - @Test - @Order(63) - void testChangelogWithCustomPropertyEditSave() throws IOException { - System.out.println( - "Test (63): Create entity with custom property, save, edit and save again - verify changelog remains at 3 entries"); + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (copyLinkSourceEntity.equals("Could not create entity")) { + // fail("Could not create new source entity"); + // } - // Create a new entity - String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(newEntityID, "Failed to create new entity"); - assertNotEquals("Could not create entity", newEntityID); + // String linkName = "Sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link in new source entity"); + // } - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // String saveSourceResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save new source entity"); + // } - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", newEntityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!editResponse.equals("Entity in draft mode")) { + // fail("Could not edit target entity draft"); + // } - List createResponse = - api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, file); + // List invalidObjectIds = Collections.singletonList("invalidObjectId123"); - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - String attachmentID = createResponse.get(1); - - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(attachmentID, "Attachment ID should not be null"); - assertNotEquals("", attachmentID, "Attachment ID should not be empty"); - - // Add a custom property - Integer customPropertyValue = 99999; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customPropertyValue + "}", - MediaType.parse("application/json")); - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, newEntityID, attachmentID, bodyInt); - assertEquals( - "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + // try { + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, invalidObjectIds); + // fail("Copy did not throw error for invalid link ID"); + // } catch (IOException e) { + // System.out.println("Caught expected error while copying invalid link: " + e.getMessage()); + // } - // Save the entity - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // // No need to wait for upload completion as copy failed, but ensure clean state + // String saveTargetResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity after unsuccessful copy"); + // } - // Edit entity to fetch initial changelog - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // String deleteSourceResponse = api.deleteEntity(appUrl, entityName, copyLinkSourceEntity); + // String deleteTargetResponse = api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // if (!deleteSourceResponse.equals("Entity Deleted") + // || !deleteTargetResponse.equals("Entity Deleted")) { + // fail("Could not delete new source entity or target entity"); + // } + // } - // Fetch changelog after initial save - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + // @Test + // @Order(58) + // void testCopyLinkSuccessNewEntityDraft() throws IOException { + // System.out.println("Test (58): Copy link from one entity to another new entity draft mode"); - assertNotNull(changelogResponse, "Changelog response should not be null"); + // copyLinkSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyLinkTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - // Verify changelog has 3 entries: 1 created + 2 updated (cmis:secondaryObjectTypeIds + - // customProperty2) - assertEquals(3, changelogResponse.get("numItems"), "Should have 3 changelog entries initially"); + // if (copyLinkSourceEntity.equals("Could not create entity") + // || copyLinkTargetEntity.equals("Could not create entity")) { + // fail("Could not create source or target entity"); + // } - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(3, changeLogs.size(), "Should have exactly 3 changelog entries"); + // String linkName = "sample"; + // String linkUrl = "https://www.example.com"; + // String createLinkResponse = + // api.createLink(appUrl, entityName, facetName, copyLinkSourceEntity, linkName, linkUrl); + // if (!createLinkResponse.equals("Link created successfully")) { + // fail("Could not create link in source entity"); + // } - // Save entity again without any modifications - saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + // List sourceObjectIds = + // api.fetchEntityMetadataDraft(appUrl, entityName, facetName, + // copyLinkSourceEntity).stream() + // .map(item -> (String) item.get("objectId")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); - // Edit entity again and fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // if (sourceObjectIds.isEmpty()) { + // fail("Could not fetch object Id for link"); + // } - // Fetch changelog after second save - Map changelogAfterSecondSave = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + // String copyResponse = + // api.copyAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, sourceObjectIds); + // if (!copyResponse.equals("Attachments copied successfully")) { + // fail("Could not copy link: " + copyResponse); + // } - assertNotNull( - changelogAfterSecondSave, "Changelog response should not be null after second save"); + // List> attachmentsMetadata = new ArrayList<>(); + // attachmentsMetadata = + // api.fetchEntityMetadataDraft(appUrl, entityName, facetName, copyLinkTargetEntity); + // Map copiedAttachment = attachmentsMetadata.get(0); + // String receivedType = (String) copiedAttachment.get("type"); + // String receivedUrl = (String) copiedAttachment.get("linkUrl"); + + // String expectedType = "sap-icon://internet-browser"; + // assertTrue( + // expectedType.equalsIgnoreCase(receivedType), + // "Attachment type mismatch. Expected '" + // + expectedType + // + "' but got '" + // + receivedType + // + "'."); + + // assertEquals(linkUrl, receivedUrl, "Attachment URL mismatch."); + + // System.out.println("Attachment type and URL validated successfully."); + + // String attachmentId = (String) copiedAttachment.get("ID"); + // assertNotNull(attachmentId, "Could not find 'ID' in the copied attachment metadata."); + + // String openAttachmentResponse = + // api.openAttachment(appUrl, entityName, facetName, copyLinkTargetEntity, attachmentId); + // if (!openAttachmentResponse.equals("Attachment opened successfully")) { + // fail("Could not open the attachment"); + // } - // Verify changelog still has only 3 entries (no new entries added) - assertEquals( - 3, - changelogAfterSecondSave.get("numItems"), - "Should still have only 3 changelog entries after edit-save without modifications"); + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, copyLinkTargetEntity); + // if (!saveResponse.equals("Saved")) { + // fail("Could not save target entity after copying link"); + // } + // api.deleteEntityDraft(appUrl, entityName, copyLinkSourceEntity); + // api.deleteEntity(appUrl, entityName, copyLinkTargetEntity); + // } - @SuppressWarnings("unchecked") - List> changeLogsAfterSecondSave = - (List>) changelogAfterSecondSave.get("changeLogs"); - assertEquals( - 3, - changeLogsAfterSecondSave.size(), - "Should still have exactly 3 changelog entries after second save"); + // @Test + // @Order(59) + // void testCopyAttachmentsSuccessNewEntityDraft() throws IOException { + // System.out.println( + // "Test (59): Copy attachments from one entity to another new entity draft mode"); + // List attachments = new ArrayList<>(); + // copyAttachmentSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // copyAttachmentTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (!copyAttachmentSourceEntity.equals("Could not create entity") + // && !copyAttachmentTargetEntity.equals("Could not create entity")) { + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample1.pdf").getFile())); + // Map postData = new HashMap<>(); + // postData.put("up__ID", entityID7); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); + + // sourceObjectIds.clear(); + + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, srvpath, postData, + // file); + // if (createResponse.get(0).equals("Attachment created")) { + // attachments.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment"); + // } + // } - // Clean up the entity - api.deleteEntity(appUrl, entityName, newEntityID); - } + // List> attachmentsMetadata = new ArrayList<>(); + // Map fetchAttachmentMetadataResponse; + // for (String attachment : attachments) { + // try { + // fetchAttachmentMetadataResponse = + // api.fetchMetadataDraft( + // appUrl, entityName, facetName, copyAttachmentSourceEntity, attachment); + // attachmentsMetadata.add(fetchAttachmentMetadataResponse); + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } + // for (Map metadata : attachmentsMetadata) { + // if (metadata.containsKey("objectId")) { + // sourceObjectIds.add(metadata.get("objectId").toString()); + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } - @Test - @Order(64) - void testChangelogForSavedAttachmentWithoutModification() throws IOException { - System.out.println( - "Test (64): Create entity, upload attachment, save, edit and save again - verify changelog still has only 'created' entry"); + // if (sourceObjectIds.size() == 2) { + // String copyResponse; + // copyResponse = + // api.copyAttachment( + // appUrl, entityName, facetName, copyAttachmentTargetEntity, sourceObjectIds); + // if (copyResponse.equals("Attachments copied successfully")) { + // String saveEntityResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, copyAttachmentTargetEntity); + // if (saveEntityResponse.equals("Saved")) { + // List> fetchEntityMetadataResponse; + // fetchEntityMetadataResponse = + // api.fetchEntityMetadata(appUrl, entityName, facetName, + // copyAttachmentTargetEntity); + // targetAttachmentIds = + // fetchEntityMetadataResponse.stream() + // .map(item -> (String) item.get("ID")) + // .filter(Objects::nonNull) + // .collect(Collectors.toList()); + // String readResponse; + // for (String targetAttachmentId : targetAttachmentIds) { + // readResponse = + // api.readAttachment( + // appUrl, + // entityName, + // facetName, + // copyAttachmentTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read copied attachment"); + // } + // } + // } else { + // fail("Could not save entity after copying attachments: " + saveEntityResponse); + // } + // } else { + // fail("Could not copy attachments: " + copyResponse); + // } + // } else { + // fail("Could not fetch objects Ids for all attachments"); + // } + // } else { + // fail("Could not create entities"); + // } + // api.deleteEntityDraft(appUrl, entityName, copyAttachmentSourceEntity); + // api.deleteEntity(appUrl, entityName, copyAttachmentTargetEntity); + // } - // Create a new entity - String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - assertNotNull(newEntityID, "Failed to create new entity"); - assertNotEquals("Could not create entity", newEntityID); + // @Test + // @Order(60) + // void testViewChangelogForNewlyCreatedAttachment() throws IOException { + // System.out.println("Test (60): View changelog for newly created attachment"); - // Prepare a sample file to upload - ClassLoader classLoader = getClass().getClassLoader(); - File file = new File(classLoader.getResource("sample.pdf").getFile()); - assertTrue(file.exists(), "Sample file should exist"); + // // Create a new entity for changelog test + // changelogEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(changelogEntityID, "Failed to create changelog test entity"); + // assertNotEquals("Could not create entity", changelogEntityID); - // Create attachment - Map postData = new HashMap<>(); - postData.put("up__ID", newEntityID); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.txt").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - List createResponse = - api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, file); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", changelogEntityID); + // postData.put("mimeType", "text/plain"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertEquals(2, createResponse.size(), "Should return status and attachment ID"); - String status = createResponse.get(0); - String newAttachmentID = createResponse.get(1); + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, changelogEntityID, srvpath, postData, file); + + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // changelogAttachmentID = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(changelogAttachmentID, "Attachment ID should not be null"); + // assertNotEquals("", changelogAttachmentID, "Attachment ID should not be empty"); + + // // Fetch changelog for the newly created attachment + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, + // changelogAttachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog structure + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // "sample.txt", changelogResponse.get("filename"), "Filename should match uploaded file"); + // assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); + // assertEquals(1, changelogResponse.get("numItems"), "Should have 1 changelog entry"); + + // // Verify the changelog entry + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); + + // Map logEntry = changeLogs.get(0); + // assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); + // assertNotNull(logEntry.get("time"), "Time should not be null"); + // assertNotNull(logEntry.get("user"), "User should not be null"); + // assertFalse( + // logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); + // } - assertEquals("Attachment created", status, "Attachment should be created successfully"); - assertNotNull(newAttachmentID, "Attachment ID should not be null"); - assertNotEquals("", newAttachmentID, "Attachment ID should not be empty"); + // @Test + // @Order(61) + // void testChangelogAfterModifyingNoteAndCustomProperty() throws IOException { + // System.out.println( + // "Test (61): Modify note field and custom property, then verify changelog shows created + + // 3 updated entries"); + + // // Update attachment with notes field (entity is already in draft mode from test 60) + // String notesValue = "Test note for changelog verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // changelogEntityID, + // changelogAttachmentID, + // updateNotesBody); + // assertEquals("Updated", updateNotesResponse, "Should successfully update notes field"); + + // // Update attachment with custom property + // Integer customProperty2Value = 12345; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID, bodyInt); + // assertEquals( + // "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + + // // Save the entity + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity again to fetch changelog + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after modifications + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, + // changelogAttachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog content - should have 1 created + 3 updated (note, customProperty2, and + // // internal update) + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // 4, + // changelogResponse.get("numItems"), + // "Should have 4 changelog entries (1 created + 3 updated)"); + + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(4, changeLogs.size(), "Should have exactly 4 changelog entries"); + + // // Verify first entry is 'created' + // Map createdEntry = changeLogs.get(0); + // assertEquals( + // "created", createdEntry.get("operation"), "First entry should be 'created' operation"); + + // // Verify remaining entries are 'updated' + // long updatedCount = + // changeLogs.stream().filter(log -> "updated".equals(log.get("operation"))).count(); + // assertEquals(3, updatedCount, "Should have 3 'updated' operations"); + + // // Verify that changeDetail exists in updated entries for note field + // boolean hasNoteUpdate = + // changeLogs.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .anyMatch( + // log -> { + // @SuppressWarnings("unchecked") + // Map changeDetail = (Map) + // log.get("changeDetail"); + // return changeDetail != null + // && "cmis:description".equals(changeDetail.get("field")); + // }); + // assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); + // assertTrue(hasNoteUpdate, "Should have an update entry for note field (cmis:description)"); + + // // Save the entity so test 62 can edit it + // String saveResponseFinal = api.saveEntityDraft(appUrl, entityName, srvpath, + // changelogEntityID); + // assertEquals("Saved", saveResponseFinal, "Entity should be saved successfully"); + // } - // Save the entity immediately without any modifications - String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + // @Test + // @Order(62) + // void testChangelogAfterRenamingAttachment() throws IOException { + // System.out.println( + // "Test (62): Rename attachment and verify changelog increases with rename entry"); + + // // Edit entity to put it in draft mode (entity was saved at end of test 61) + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Rename the attachment + // String newFileName = "renamed_sample.txt"; + // String renameResponse = + // api.renameAttachment( + // appUrl, entityName, facetName, changelogEntityID, changelogAttachmentID, + // newFileName); + // assertEquals("Renamed", renameResponse, "Should successfully rename attachment"); + + // // Save entity after rename + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, changelogEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully after rename"); + + // // Edit entity again and fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, changelogEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after rename + // Map changelogAfterRename = + // api.fetchChangelog(appUrl, entityName, facetName, changelogEntityID, + // changelogAttachmentID); + + // assertNotNull(changelogAfterRename, "Changelog response should not be null after rename"); + + // // Verify changelog has increased (rename operation adds 1 entry for cmis:name change) + // // Expected: 1 created + 3 initial updates + 1 rename update = 5 total + // assertEquals( + // 5, changelogAfterRename.get("numItems"), "Should have 5 changelog entries after rename"); + + // @SuppressWarnings("unchecked") + // List> changeLogsAfterRename = + // (List>) changelogAfterRename.get("changeLogs"); + // assertEquals( + // 5, changeLogsAfterRename.size(), "Should have exactly 5 changelog entries after rename"); + + // // Verify updated count is 4 (3 initial + 1 from rename operation) + // long updatedCountAfterRename = + // changeLogsAfterRename.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .count(); + // assertEquals(4, updatedCountAfterRename, "Should have 4 'updated' operations after rename"); + + // // Verify filename change in changelog + // boolean hasFilenameUpdate = + // changeLogsAfterRename.stream() + // .filter(log -> "updated".equals(log.get("operation"))) + // .anyMatch( + // log -> { + // @SuppressWarnings("unchecked") + // Map changeDetail = (Map) + // log.get("changeDetail"); + // return changeDetail != null && "cmis:name".equals(changeDetail.get("field")); + // }); + // assertTrue(hasFilenameUpdate, "Should have an update entry for filename (cmis:name)"); + + // // Cleanup - entity was saved after rename, so delete the active entity + // api.deleteEntity(appUrl, entityName, changelogEntityID); + // } - // Edit entity again without making any changes to the attachment - String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // @Test + // @Order(63) + // void testChangelogWithCustomPropertyEditSave() throws IOException { + // System.out.println( + // "Test (63): Create entity with custom property, save, edit and save again - verify + // changelog remains at 3 entries"); - // Save entity again without modifying the attachment - saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + // // Create a new entity + // String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(newEntityID, "Failed to create new entity"); + // assertNotEquals("Could not create entity", newEntityID); - // Edit entity to fetch changelog - editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); - assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - // Fetch changelog for the attachment - Map changelogResponse = - api.fetchChangelog(appUrl, entityName, facetName, newEntityID, newAttachmentID); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", newEntityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertNotNull(changelogResponse, "Changelog response should not be null"); + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, + // file); + + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // String attachmentID = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(attachmentID, "Attachment ID should not be null"); + // assertNotEquals("", attachmentID, "Attachment ID should not be empty"); + + // // Add a custom property + // Integer customPropertyValue = 99999; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customPropertyValue + "}", + // MediaType.parse("application/json")); + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, newEntityID, attachmentID, bodyInt); + // assertEquals( + // "Updated", updateCustomPropertyResponse, "Should successfully update custom property"); + + // // Save the entity + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity to fetch initial changelog + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after initial save + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog has 3 entries: 1 created + 2 updated (cmis:secondaryObjectTypeIds + + // // customProperty2) + // assertEquals(3, changelogResponse.get("numItems"), "Should have 3 changelog entries + // initially"); + + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(3, changeLogs.size(), "Should have exactly 3 changelog entries"); + + // // Save entity again without any modifications + // saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + + // // Edit entity again and fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog after second save + // Map changelogAfterSecondSave = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, attachmentID); + + // assertNotNull( + // changelogAfterSecondSave, "Changelog response should not be null after second save"); + + // // Verify changelog still has only 3 entries (no new entries added) + // assertEquals( + // 3, + // changelogAfterSecondSave.get("numItems"), + // "Should still have only 3 changelog entries after edit-save without modifications"); + + // @SuppressWarnings("unchecked") + // List> changeLogsAfterSecondSave = + // (List>) changelogAfterSecondSave.get("changeLogs"); + // assertEquals( + // 3, + // changeLogsAfterSecondSave.size(), + // "Should still have exactly 3 changelog entries after second save"); + + // // Clean up the entity + // api.deleteEntity(appUrl, entityName, newEntityID); + // } - // Verify changelog content - should only have 'created' entry even after edit and save - assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); - assertEquals( - "sample.pdf", changelogResponse.get("filename"), "Filename should match uploaded file"); - assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); - assertEquals(1, changelogResponse.get("numItems"), "Should have only 1 changelog entry"); - - // Verify the changelog entry - @SuppressWarnings("unchecked") - List> changeLogs = - (List>) changelogResponse.get("changeLogs"); - assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); - - Map logEntry = changeLogs.get(0); - assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); - assertNotNull(logEntry.get("time"), "Time should not be null"); - assertNotNull(logEntry.get("user"), "User should not be null"); - assertFalse( - logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); - - // Clean up the new entity - api.deleteEntity(appUrl, entityName, newEntityID); - } + // @Test + // @Order(64) + // void testChangelogForSavedAttachmentWithoutModification() throws IOException { + // System.out.println( + // "Test (64): Create entity, upload attachment, save, edit and save again - verify + // changelog still has only 'created' entry"); - @Test - @Order(65) - void testMoveAttachmentsWithSourceFacet() throws IOException { - System.out.println( - "Test (65): Move attachments from Source Entity to Target Entity with sourceFacet"); + // // Create a new entity + // String newEntityID = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // assertNotNull(newEntityID, "Failed to create new entity"); + // assertNotEquals("Could not create entity", newEntityID); - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Prepare a sample file to upload + // ClassLoader classLoader = getClass().getClassLoader(); + // File file = new File(classLoader.getResource("sample.pdf").getFile()); + // assertTrue(file.exists(), "Sample file should exist"); - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // // Create attachment + // Map postData = new HashMap<>(); + // postData.put("up__ID", newEntityID); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // List createResponse = + // api.createAttachment(appUrl, entityName, facetName, newEntityID, srvpath, postData, + // file); + + // assertEquals(2, createResponse.size(), "Should return status and attachment ID"); + // String status = createResponse.get(0); + // String newAttachmentID = createResponse.get(1); + + // assertEquals("Attachment created", status, "Attachment should be created successfully"); + // assertNotNull(newAttachmentID, "Attachment ID should not be null"); + // assertNotEquals("", newAttachmentID, "Attachment ID should not be empty"); + + // // Save the entity immediately without any modifications + // String saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully"); + + // // Edit entity again without making any changes to the attachment + // String editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Save entity again without modifying the attachment + // saveResponse = api.saveEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Saved", saveResponse, "Entity should be saved successfully again"); + + // // Edit entity to fetch changelog + // editResponse = api.editEntityDraft(appUrl, entityName, srvpath, newEntityID); + // assertEquals("Entity in draft mode", editResponse, "Entity should be in draft mode"); + + // // Fetch changelog for the attachment + // Map changelogResponse = + // api.fetchChangelog(appUrl, entityName, facetName, newEntityID, newAttachmentID); + + // assertNotNull(changelogResponse, "Changelog response should not be null"); + + // // Verify changelog content - should only have 'created' entry even after edit and save + // assertEquals(false, changelogResponse.get("hasMoreItems"), "hasMoreItems should be false"); + // assertEquals( + // "sample.pdf", changelogResponse.get("filename"), "Filename should match uploaded file"); + // assertNotNull(changelogResponse.get("objectId"), "ObjectId should not be null"); + // assertEquals(1, changelogResponse.get("numItems"), "Should have only 1 changelog entry"); + + // // Verify the changelog entry + // @SuppressWarnings("unchecked") + // List> changeLogs = + // (List>) changelogResponse.get("changeLogs"); + // assertEquals(1, changeLogs.size(), "Should have exactly 1 changelog entry"); + + // Map logEntry = changeLogs.get(0); + // assertEquals("created", logEntry.get("operation"), "Operation should be 'created'"); + // assertNotNull(logEntry.get("time"), "Time should not be null"); + // assertNotNull(logEntry.get("user"), "User should not be null"); + // assertFalse( + // logEntry.containsKey("changeDetail"), "Created operation should not have changeDetail"); + + // // Clean up the new entity + // api.deleteEntity(appUrl, entityName, newEntityID); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // @Test + // @Order(65) + // void testMoveAttachmentsWithSourceFacet() throws IOException { + // System.out.println( + // "Test (65): Move attachments from Source Entity to Target Entity with sourceFacet"); - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } else { - fail("Attachment metadata does not contain objectId"); - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity: " + saveTargetBeforeMoveResponse); - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Move attachments from source to target with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - // All attachments moved to target entity in SDM & UI - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals( - sourceAttachmentIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all attachments after move"); - - // Verify attachments can be read from target entity - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - String readResponse = - api.readAttachment(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read moved attachment from target entity"); - } - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - // All attachments removed from source entity in SDM & UI - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - 0, sourceMetadataAfterMove.size(), "Source entity should have 0 attachments after move"); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - @Test - @Order(66) - public void testMoveAttachmentsToEntityWithDuplicateWithSourceFacet() throws Exception { - System.out.println( - "Test (66): Move attachments to entity with duplicate attachment with sourceFacet"); + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity: " + saveTargetBeforeMoveResponse); + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Move attachments from source to target with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // // All attachments moved to target entity in SDM & UI + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals( + // sourceAttachmentIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all attachments after move"); + + // // Verify attachments can be read from target entity + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // String readResponse = + // api.readAttachment(appUrl, entityName, facetName, moveTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read moved attachment from target entity"); + // } + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // // All attachments removed from source entity in SDM & UI + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // 0, sourceMetadataAfterMove.size(), "Source entity should have 0 attachments after move"); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // @Test + // @Order(66) + // public void testMoveAttachmentsToEntityWithDuplicateWithSourceFacet() throws Exception { + // System.out.println( + // "Test (66): Move attachments to entity with duplicate attachment with sourceFacet"); - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Create target entity and add attachment - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - Map targetPostData = new HashMap<>(); - targetPostData.put("up__ID", moveTargetEntity); - targetPostData.put("mimeType", "application/pdf"); - targetPostData.put("createdAt", new Date().toString()); - targetPostData.put("createdBy", "test@test.com"); - targetPostData.put("modifiedBy", "test@test.com"); + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - File duplicateFile = new File(classLoader.getResource("sample.pdf").getFile()); - List targetCreateResponse = - api.createAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - srvpath, - targetPostData, - duplicateFile); + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - if (!targetCreateResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment on target entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - // Save target entity to persist the attachment - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse); - } + // // Create target entity and add attachment + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // Fetch target metadata before move (target entity is now saved with 1 attachment) - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - int targetCountBeforeMove = targetMetadataBeforeMove.size(); - - // Move attachments from source to target with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - // Verify target has duplicate skipped, other attachments moved - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - - // Expected: original attachments + non-duplicate moved attachments - int expectedTargetCount = targetCountBeforeMove + (sourceAttachmentIds.size() - 1); - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target should have duplicate skipped, other attachments moved"); - - // Verify source entity has only the duplicate attachment remaining - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - // Calculate expected source count: number of duplicates that couldn't be moved - int expectedSourceCount = - sourceAttachmentIds.size() - (targetMetadataAfterMove.size() - targetCountBeforeMove); - assertEquals( - expectedSourceCount, - sourceMetadataAfterMove.size(), - "Source should have duplicate attachment remaining"); + // Map targetPostData = new HashMap<>(); + // targetPostData.put("up__ID", moveTargetEntity); + // targetPostData.put("mimeType", "application/pdf"); + // targetPostData.put("createdAt", new Date().toString()); + // targetPostData.put("createdBy", "test@test.com"); + // targetPostData.put("modifiedBy", "test@test.com"); - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // File duplicateFile = new File(classLoader.getResource("sample.pdf").getFile()); + // List targetCreateResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // srvpath, + // targetPostData, + // duplicateFile); + + // if (!targetCreateResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment on target entity"); + // } - @Test - @Order(67) - public void testMoveAttachmentsWithNotesAndSecondaryProperties() throws Exception { - System.out.println( - "Test (67): Move attachments with notes and secondary properties with sourceFacet"); + // // Save target entity to persist the attachment + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse); + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Fetch target metadata before move (target entity is now saved with 1 attachment) + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // int targetCountBeforeMove = targetMetadataBeforeMove.size(); + + // // Move attachments from source to target with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // // Verify target has duplicate skipped, other attachments moved + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + + // // Expected: original attachments + non-duplicate moved attachments + // int expectedTargetCount = targetCountBeforeMove + (sourceAttachmentIds.size() - 1); + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target should have duplicate skipped, other attachments moved"); + + // // Verify source entity has only the duplicate attachment remaining + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // // Calculate expected source count: number of duplicates that couldn't be moved + // int expectedSourceCount = + // sourceAttachmentIds.size() - (targetMetadataAfterMove.size() - targetCountBeforeMove); + // assertEquals( + // expectedSourceCount, + // sourceMetadataAfterMove.size(), + // "Source should have duplicate attachment remaining"); + + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // @Test + // @Order(67) + // public void testMoveAttachmentsWithNotesAndSecondaryProperties() throws Exception { + // System.out.println( + // "Test (67): Move attachments with notes and secondary properties with sourceFacet"); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - // Add notes to attachments - String notesValue = "Test note for verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); - - for (String attachmentId : sourceAttachmentIds) { - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, attachmentId, updateNotesBody); - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update notes for attachment: " + attachmentId); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Add custom property to attachments - Integer customProperty2Value = 54321; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - - for (String attachmentId : sourceAttachmentIds) { - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, attachmentId, bodyInt); - if (!updateCustomPropertyResponse.equals("Updated")) { - fail("Could not update custom property for attachment: " + attachmentId); - } - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Add notes to attachments + // String notesValue = "Test note for verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, attachmentId, updateNotesBody); + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update notes for attachment: " + attachmentId); + // } + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // // Add custom property to attachments + // Integer customProperty2Value = 54321; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, attachmentId, bodyInt); + // if (!updateCustomPropertyResponse.equals("Updated")) { + // fail("Could not update custom property for attachment: " + attachmentId); + // } + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - // Move attachments from source to target with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // Verify all attachments moved to target - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals( - sourceAttachmentIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all attachments after move"); - - // Verify notes and secondary properties are preserved - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); - - // Verify notes are preserved - if (detailedMetadata.containsKey("note")) { - assertEquals( - notesValue, - detailedMetadata.get("note"), - "Notes should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Notes property missing after move for attachment: " + targetAttachmentId); - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse); + // } - // Verify custom property is preserved - if (detailedMetadata.containsKey("customProperty2")) { - assertEquals( - customProperty2Value, - detailedMetadata.get("customProperty2"), - "Custom property should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Custom property missing after move for attachment: " + targetAttachmentId); - } - } + // // Move attachments from source to target with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - // Verify source entity has no attachments (all moved with sourceFacet) - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals(0, sourceMetadataAfterMove.size(), "Source entity has no attachments after move"); + // // Verify all attachments moved to target + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals( + // sourceAttachmentIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all attachments after move"); + + // // Verify notes and secondary properties are preserved + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); + + // // Verify notes are preserved + // if (detailedMetadata.containsKey("note")) { + // assertEquals( + // notesValue, + // detailedMetadata.get("note"), + // "Notes should be preserved after move for attachment: " + targetAttachmentId); + // } else { + // fail("Notes property missing after move for attachment: " + targetAttachmentId); + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Verify custom property is preserved + // if (detailedMetadata.containsKey("customProperty2")) { + // assertEquals( + // customProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Custom property should be preserved after move for attachment: " + + // targetAttachmentId); + // } else { + // fail("Custom property missing after move for attachment: " + targetAttachmentId); + // } + // } - @Test - @Order(68) - public void testMoveAttachmentsWithoutSourceFacet() throws Exception { - System.out.println( - "Test (68): Move valid attachments from Source Entity to Target Entity without sourceFacet"); + // // Verify source entity has no attachments (all moved with sourceFacet) + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals(0, sourceMetadataAfterMove.size(), "Source entity has no attachments after + // move"); - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // @Test + // @Order(68) + // public void testMoveAttachmentsWithoutSourceFacet() throws Exception { + // System.out.println( + // "Test (68): Move valid attachments from Source Entity to Target Entity without + // sourceFacet"); - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID from first attachment - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } else { - fail("Attachment metadata does not contain objectId"); - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID from first attachment + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Move attachments without sourceFacet (pass null for sourceFacet parameter) - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // Verify attachments are in target entity - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals( - moveObjectIds.size(), - targetMetadataAfterMove.size(), - "Target entity should have all moved attachments"); - - // Verify attachments can be read from target entity - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - String readResponse = - api.readAttachment(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); - if (!readResponse.equals("OK")) { - fail("Could not read moved attachment from target entity"); - } - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - // Expected Behavior: Attachments remain in source entity UI (without sourceFacet) - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - moveObjectIds.size(), - sourceMetadataAfterMove.size(), - "Source entity should still have attachments in UI when sourceFacet is not specified"); + // // Move attachments without sourceFacet (pass null for sourceFacet parameter) + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - // Verify the same objectIds are still visible in source - for (Map metadata : sourceMetadataAfterMove) { - String objectId = (String) metadata.get("objectId"); - assertTrue( - moveObjectIds.contains(objectId), - "Source entity should still show attachment with objectId: " + objectId); - } + // // Verify attachments are in target entity + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals( + // moveObjectIds.size(), + // targetMetadataAfterMove.size(), + // "Target entity should have all moved attachments"); + + // // Verify attachments can be read from target entity + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // String readResponse = + // api.readAttachment(appUrl, entityName, facetName, moveTargetEntity, + // targetAttachmentId); + // if (!readResponse.equals("OK")) { + // fail("Could not read moved attachment from target entity"); + // } + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Expected Behavior: Attachments remain in source entity UI (without sourceFacet) + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // moveObjectIds.size(), + // sourceMetadataAfterMove.size(), + // "Source entity should still have attachments in UI when sourceFacet is not specified"); + + // // Verify the same objectIds are still visible in source + // for (Map metadata : sourceMetadataAfterMove) { + // String objectId = (String) metadata.get("objectId"); + // assertTrue( + // moveObjectIds.contains(objectId), + // "Source entity should still show attachment with objectId: " + objectId); + // } - @Test - @Order(69) - public void testMoveAttachmentsToEntityWithDuplicateWithoutSourceFacet() throws Exception { - System.out.println( - "Test (69): Move attachments into existing Target Entity when duplicate exists without sourceFacet"); + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // @Test + // @Order(69) + // public void testMoveAttachmentsToEntityWithDuplicateWithoutSourceFacet() throws Exception { + // System.out.println( + // "Test (69): Move attachments into existing Target Entity when duplicate exists without + // sourceFacet"); - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID from first attachment - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } else { - fail("Attachment metadata does not contain objectId"); - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID from first attachment + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } else { + // fail("Attachment metadata does not contain objectId"); + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - // Create target entity and add duplicate attachment (sample.pdf) - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Add the same first file (sample.pdf) to target entity to create duplicate - Map targetPostData = new HashMap<>(); - targetPostData.put("up__ID", moveTargetEntity); - targetPostData.put("mimeType", "application/pdf"); - targetPostData.put("createdAt", new Date().toString()); - targetPostData.put("createdBy", "test@test.com"); - targetPostData.put("modifiedBy", "test@test.com"); + // // Create target entity and add duplicate attachment (sample.pdf) + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - List createTargetResponse = - api.createAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - srvpath, - targetPostData, - files.get(0)); // Add same file (sample.pdf) - if (!createTargetResponse.get(0).equals("Attachment created")) { - fail("Could not create duplicate attachment in target entity"); - } + // // Add the same first file (sample.pdf) to target entity to create duplicate + // Map targetPostData = new HashMap<>(); + // targetPostData.put("up__ID", moveTargetEntity); + // targetPostData.put("mimeType", "application/pdf"); + // targetPostData.put("createdAt", new Date().toString()); + // targetPostData.put("createdBy", "test@test.com"); + // targetPostData.put("modifiedBy", "test@test.com"); - // Save target entity before move - String saveTargetResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity: " + saveTargetResponse); - } + // List createTargetResponse = + // api.createAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // srvpath, + // targetPostData, + // files.get(0)); // Add same file (sample.pdf) + // if (!createTargetResponse.get(0).equals("Attachment created")) { + // fail("Could not create duplicate attachment in target entity"); + // } - // Get initial target metadata count - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - int initialTargetCount = targetMetadataBeforeMove.size(); + // // Save target entity before move + // String saveTargetResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity: " + saveTargetResponse); + // } - // Step 3: Move attachments without sourceFacet (duplicate should be skipped) - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Get initial target metadata count + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // int initialTargetCount = targetMetadataBeforeMove.size(); + + // // Step 3: Move attachments without sourceFacet (duplicate should be skipped) + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - // Expected Behavior - Verify duplicate was skipped, other attachments moved - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // // Expected Behavior - Verify duplicate was skipped, other attachments moved + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + + // int nonDuplicateCount = moveObjectIds.size() - 1; + // int expectedTargetCount = initialTargetCount + nonDuplicateCount; + + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target entity should have initial attachments plus non-duplicate moved attachments"); + + // // Verify at least one non-duplicate attachment was moved + // assertTrue( + // targetMetadataAfterMove.size() > initialTargetCount, + // "Target should have more attachments after move (non-duplicates added)"); + + // // Verify all attachments still remain in source entity UI (without sourceFacet) + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // moveObjectIds.size(), + // sourceMetadataAfterMove.size(), + // "Source entity should still have all attachments in UI when sourceFacet is not + // specified"); + + // // Verify all original objectIds are still visible in source + // List sourceObjectIds = new ArrayList<>(); + // for (Map metadata : sourceMetadataAfterMove) { + // sourceObjectIds.add((String) metadata.get("objectId")); + // } + // for (String objectId : moveObjectIds) { + // assertTrue( + // sourceObjectIds.contains(objectId), + // "Source entity should still show attachment with objectId: " + objectId); + // } - int nonDuplicateCount = moveObjectIds.size() - 1; - int expectedTargetCount = initialTargetCount + nonDuplicateCount; + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target entity should have initial attachments plus non-duplicate moved attachments"); + // @Test + // @Order(70) + // public void testMoveAttachmentsWithNotesAndSecondaryPropertiesWithoutSourceFacet() + // throws Exception { + // System.out.println( + // "Test (70): Move attachments with notes and secondary properties without sourceFacet"); - // Verify at least one non-duplicate attachment was moved - assertTrue( - targetMetadataAfterMove.size() > initialTargetCount, - "Target should have more attachments after move (non-duplicates added)"); + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Verify all attachments still remain in source entity UI (without sourceFacet) - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - moveObjectIds.size(), - sourceMetadataAfterMove.size(), - "Source entity should still have all attachments in UI when sourceFacet is not specified"); - - // Verify all original objectIds are still visible in source - List sourceObjectIds = new ArrayList<>(); - for (Map metadata : sourceMetadataAfterMove) { - sourceObjectIds.add((String) metadata.get("objectId")); - } - for (String objectId : moveObjectIds) { - assertTrue( - sourceObjectIds.contains(objectId), - "Source entity should still show attachment with objectId: " + objectId); - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - @Test - @Order(70) - public void testMoveAttachmentsWithNotesAndSecondaryPropertiesWithoutSourceFacet() - throws Exception { - System.out.println( - "Test (70): Move attachments with notes and secondary properties without sourceFacet"); + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Add notes to attachments + // String notesValue = "Test note for migration verification"; + // MediaType mediaType = MediaType.parse("application/json"); + // String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; + // RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateNotesResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, attachmentId, updateNotesBody); + // if (!updateNotesResponse.equals("Updated")) { + // fail("Could not update notes for attachment: " + attachmentId); + // } + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // // Add custom property to attachments + // Integer customProperty2Value = 54321; + // RequestBody bodyInt = + // RequestBody.create( + // "{\"customProperty2\": " + customProperty2Value + "}", + // MediaType.parse("application/json")); + + // for (String attachmentId : sourceAttachmentIds) { + // String updateCustomPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, attachmentId, bodyInt); + // if (!updateCustomPropertyResponse.equals("Updated")) { + // fail("Could not update custom property for attachment: " + attachmentId); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - // Add notes to attachments - String notesValue = "Test note for migration verification"; - MediaType mediaType = MediaType.parse("application/json"); - String jsonPayload = "{\"note\": \"" + notesValue + "\"}"; - RequestBody updateNotesBody = RequestBody.create(jsonPayload, mediaType); - - for (String attachmentId : sourceAttachmentIds) { - String updateNotesResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, attachmentId, updateNotesBody); - if (!updateNotesResponse.equals("Updated")) { - fail("Could not update notes for attachment: " + attachmentId); - } - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - // Add custom property to attachments - Integer customProperty2Value = 54321; - RequestBody bodyInt = - RequestBody.create( - "{\"customProperty2\": " + customProperty2Value + "}", - MediaType.parse("application/json")); - - for (String attachmentId : sourceAttachmentIds) { - String updateCustomPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, attachmentId, bodyInt); - if (!updateCustomPropertyResponse.equals("Updated")) { - fail("Could not update custom property for attachment: " + attachmentId); - } - } + // // Get source attachment count before move + // List> sourceMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // // Get target attachment count before move + // List> targetMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // int targetCountBeforeMove = targetMetadataBeforeMove.size(); + + // // Move attachments from source to target WITHOUT sourceFacet + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - // Get source attachment count before move - List> sourceMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); + // // Verify expected number of attachments moved to target + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // int expectedTargetCount = targetCountBeforeMove + sourceAttachmentIds.size(); + // assertEquals( + // expectedTargetCount, + // targetMetadataAfterMove.size(), + // "Target entity should have " + expectedTargetCount + " attachments after move"); + + // // Verify notes and secondary properties are preserved + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); + + // // Verify notes are preserved + // if (detailedMetadata.containsKey("note")) { + // assertEquals( + // notesValue, + // detailedMetadata.get("note"), + // "Notes should be preserved after move for attachment: " + targetAttachmentId); + // } else { + // fail("Notes property missing after move for attachment: " + targetAttachmentId); + // } - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Verify custom property is preserved + // if (detailedMetadata.containsKey("customProperty2")) { + // assertEquals( + // customProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Custom property should be preserved after move for attachment: " + + // targetAttachmentId); + // } else { + // fail("Custom property missing after move for attachment: " + targetAttachmentId); + // } + // } - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // // Verify source entity still has all attachments (without sourceFacet) + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // sourceCountBeforeMove, + // sourceMetadataAfterMove.size(), + // "Source entity should still have " + // + sourceCountBeforeMove + // + " attachments (without sourceFacet)"); + + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Get target attachment count before move - List> targetMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - int targetCountBeforeMove = targetMetadataBeforeMove.size(); + // @Test + // @Order(71) + // public void testMoveAttachmentsWithInvalidOrUndefinedSecondaryProperties() throws Exception { + // System.out.println( + // "Test (71): Move attachments with invalid or undefined secondary properties"); - // Move attachments from source to target WITHOUT sourceFacet - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Verify expected number of attachments moved to target - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - int expectedTargetCount = targetCountBeforeMove + sourceAttachmentIds.size(); - assertEquals( - expectedTargetCount, - targetMetadataAfterMove.size(), - "Target entity should have " + expectedTargetCount + " attachments after move"); - - // Verify notes and secondary properties are preserved - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); - - // Verify notes are preserved - if (detailedMetadata.containsKey("note")) { - assertEquals( - notesValue, - detailedMetadata.get("note"), - "Notes should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Notes property missing after move for attachment: " + targetAttachmentId); - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); + // files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); - // Verify custom property is preserved - if (detailedMetadata.containsKey("customProperty2")) { - assertEquals( - customProperty2Value, - detailedMetadata.get("customProperty2"), - "Custom property should be preserved after move for attachment: " + targetAttachmentId); - } else { - fail("Custom property missing after move for attachment: " + targetAttachmentId); - } - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Verify source entity still has all attachments (without sourceFacet) - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - sourceCountBeforeMove, - sourceMetadataAfterMove.size(), - "Source entity should still have " - + sourceCountBeforeMove - + " attachments (without sourceFacet)"); - - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - @Test - @Order(71) - public void testMoveAttachmentsWithInvalidOrUndefinedSecondaryProperties() throws Exception { - System.out.println( - "Test (71): Move attachments with invalid or undefined secondary properties"); + // // Add valid secondary properties to first attachment (customProperty2) + // String validAttachmentId = sourceAttachmentIds.get(0); + // Integer validCustomProperty2Value = 12345; + // RequestBody validPropertyBody = + // RequestBody.create( + // "{\"customProperty2\": " + validCustomProperty2Value + "}", + // MediaType.parse("application/json")); + + // String validPropertyResponse = + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, validAttachmentId, + // validPropertyBody); + // if (!validPropertyResponse.equals("Updated")) { + // fail("Could not update valid property for attachment: " + validAttachmentId); + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // add invalid secondary properties to second attachment (non-existent property) + // String invalidAttachmentId = sourceAttachmentIds.get(1); + // RequestBody invalidPropertyBody = + // RequestBody.create( + // "{\"nonExistentProperty\": \"invalid\"}", MediaType.parse("application/json")); + + // api.updateSecondaryProperty( + // appUrl, entityName, facetName, moveSourceEntity, invalidAttachmentId, + // invalidPropertyBody); + + // // add undefined properties to third attachment + // String undefinedAttachmentId = sourceAttachmentIds.get(2); + // RequestBody undefinedPropertyBody = + // RequestBody.create( + // "{\"undefinedField\": \"test\", \"anotherUndefined\": 999}", + // MediaType.parse("application/json")); + + // api.updateSecondaryProperty( + // appUrl, + // entityName, + // facetName, + // moveSourceEntity, + // undefinedAttachmentId, + // undefinedPropertyBody); + + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); - files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (Exception e) { + // fail("Could not fetch metadata for attachment: " + attachmentId); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch all objectIds from source entity"); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Get source attachment count before move + // List> sourceMetadataBeforeMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); - // Add valid secondary properties to first attachment (customProperty2) - String validAttachmentId = sourceAttachmentIds.get(0); - Integer validCustomProperty2Value = 12345; - RequestBody validPropertyBody = - RequestBody.create( - "{\"customProperty2\": " + validCustomProperty2Value + "}", - MediaType.parse("application/json")); - - String validPropertyResponse = - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, validAttachmentId, validPropertyBody); - if (!validPropertyResponse.equals("Updated")) { - fail("Could not update valid property for attachment: " + validAttachmentId); - } + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // add invalid secondary properties to second attachment (non-existent property) - String invalidAttachmentId = sourceAttachmentIds.get(1); - RequestBody invalidPropertyBody = - RequestBody.create( - "{\"nonExistentProperty\": \"invalid\"}", MediaType.parse("application/json")); - - api.updateSecondaryProperty( - appUrl, entityName, facetName, moveSourceEntity, invalidAttachmentId, invalidPropertyBody); - - // add undefined properties to third attachment - String undefinedAttachmentId = sourceAttachmentIds.get(2); - RequestBody undefinedPropertyBody = - RequestBody.create( - "{\"undefinedField\": \"test\", \"anotherUndefined\": 999}", - MediaType.parse("application/json")); - - api.updateSecondaryProperty( - appUrl, - entityName, - facetName, - moveSourceEntity, - undefinedAttachmentId, - undefinedPropertyBody); - - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Save target before move + // String saveTargetBeforeMoveResponse68 = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse68.equals("Saved")) { + // fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse68); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (Exception e) { - fail("Could not fetch metadata for attachment: " + attachmentId); - } - } + // // Move attachments from source to target with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch all objectIds from source entity"); - } + // // Verify attachments moved to target + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + + // assertTrue( + // targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); + // assertEquals( + // sourceCountBeforeMove, + // targetMetadataAfterMove.size(), + // "All attachments should move (invalid properties are ignored)"); + + // // Verify only allowed properties are populated in target + // for (Map metadata : targetMetadataAfterMove) { + // String targetAttachmentId = (String) metadata.get("ID"); + // assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); + + // // Fetch detailed metadata to verify properties + // Map detailedMetadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); + + // // Check if this is the attachment with valid customProperty2 + // if (detailedMetadata.containsKey("customProperty2") + // && detailedMetadata.get("customProperty2") != null) { + // assertEquals( + // validCustomProperty2Value, + // detailedMetadata.get("customProperty2"), + // "Valid customProperty2 should be preserved"); + // } + // } - // Get source attachment count before move - List> sourceMetadataBeforeMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - int sourceCountBeforeMove = sourceMetadataBeforeMove.size(); + // // Verify source entity has no attachments + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterMove.size(), + // "Source entity should have no attachments after move with sourceFacet"); + + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // @Test + // @Order(72) + // public void testMoveAttachmentsFromSourceEntityInDraftMode() throws Exception { + // System.out.println( + // "Test (72): Move attachments from Source Entity when Source Entity is in draft mode"); - // Save target before move - String saveTargetBeforeMoveResponse68 = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse68.equals("Saved")) { - fail("Could not save target entity before move: " + saveTargetBeforeMoveResponse68); - } + // // Create source entity and keep it in draft mode + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Move attachments from source to target with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); + // files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); - // Verify attachments moved to target - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertTrue( - targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); - assertEquals( - sourceCountBeforeMove, - targetMetadataAfterMove.size(), - "All attachments should move (invalid properties are ignored)"); - - // Verify only allowed properties are populated in target - for (Map metadata : targetMetadataAfterMove) { - String targetAttachmentId = (String) metadata.get("ID"); - assertNotNull(targetAttachmentId, "Target attachment ID should not be null"); - - // Fetch detailed metadata to verify properties - Map detailedMetadata = - api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, targetAttachmentId); - - // Check if this is the attachment with valid customProperty2 - if (detailedMetadata.containsKey("customProperty2") - && detailedMetadata.get("customProperty2") != null) { - assertEquals( - validCustomProperty2Value, - detailedMetadata.get("customProperty2"), - "Valid customProperty2 should be preserved"); - } - } + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Verify source entity has no attachments - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterMove.size(), - "Source entity should have no attachments after move with sourceFacet"); + // // Verify attachments are added to source entity + // int sourceCountBeforeMove = sourceAttachmentIds.size(); + // assertTrue(sourceCountBeforeMove > 0, "Source entity should have attachments before move"); + // assertEquals( + // files.size(), sourceCountBeforeMove, "Source should have " + files.size() + " + // attachments"); + + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID from first attachment + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - @Test - @Order(72) - public void testMoveAttachmentsFromSourceEntityInDraftMode() throws Exception { - System.out.println( - "Test (72): Move attachments from Source Entity when Source Entity is in draft mode"); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Create source entity and keep it in draft mode - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); - files.add(new File(classLoader.getResource("WDIRSCodeList.csv").getFile())); + // String editSourceResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!editSourceResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity back to draft mode"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Save target before move + // String saveTargetResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveTargetEntity); + // if (!saveTargetResponse.equals("Saved")) { + // fail("Could not save target entity: " + saveTargetResponse); + // } - // Verify attachments are added to source entity - int sourceCountBeforeMove = sourceAttachmentIds.size(); - assertTrue(sourceCountBeforeMove > 0, "Source entity should have attachments before move"); - assertEquals( - files.size(), sourceCountBeforeMove, "Source should have " + files.size() + " attachments"); + // // Move attachments from draft source to target using sourceFacet + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // null); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Verify attachments moved to target + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertTrue( + // targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); + // assertEquals( + // sourceCountBeforeMove, + // targetMetadataAfterMove.size(), + // "Target should have " + sourceCountBeforeMove + " attachments after move"); + + // // Verify all expected attachments are in target + // Set targetFileNames = + // targetMetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // targetFileNames.contains(file.getName()), + // "Target should contain attachment: " + file.getName()); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID from first attachment - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Now save the source entity + // String saveSourceAfterMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceAfterMoveResponse.equals("Saved")) { + // fail("Could not save source entity after move: " + saveSourceAfterMoveResponse); + // } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // sourceCountBeforeMove, + // sourceMetadataAfterMove.size(), + // "Source entity in draft mode retains attachments after move (copy behavior)"); + + // Set sourceFileNamesAfterMove = + // sourceMetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // sourceFileNamesAfterMove.contains(file.getName()), + // "Source (draft) should still contain attachment: " + file.getName()); + // } - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - String editSourceResponse = api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!editSourceResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity back to draft mode"); - } + // @Test + // @Order(73) + // public void testEditAttachmentFileNameAndMoveToTarget() throws Exception { + // System.out.println( + // "Test (73): Edit attachment file name in Source Entity and move it to Target Entity"); - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // // Create source entity and add attachment + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Save target before move - String saveTargetResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetResponse.equals("Saved")) { - fail("Could not save target entity: " + saveTargetResponse); - } + // // Add attachment with original name (sample.txt) + // ClassLoader classLoader = getClass().getClassLoader(); + // File originalFile = new File(classLoader.getResource("sample.txt").getFile()); - // Move attachments from draft source to target using sourceFacet - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - null); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "text/plain"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - // Verify attachments moved to target - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertTrue( - targetMetadataAfterMove.size() > 0, "Target entity should have attachments after move"); - assertEquals( - sourceCountBeforeMove, - targetMetadataAfterMove.size(), - "Target should have " + sourceCountBeforeMove + " attachments after move"); + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, originalFile); + // if (!createResponse.get(0).equals("Attachment created")) { + // fail("Could not create attachment in source entity"); + // } - // Verify all expected attachments are in target - Set targetFileNames = - targetMetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); + // String attachmentId = createResponse.get(1); + // assertNotNull(attachmentId, "Attachment ID should not be null"); - for (File file : files) { - assertTrue( - targetFileNames.contains(file.getName()), - "Target should contain attachment: " + file.getName()); - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Now save the source entity - String saveSourceAfterMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceAfterMoveResponse.equals("Saved")) { - fail("Could not save source entity after move: " + saveSourceAfterMoveResponse); - } + // // Verify original filename + // List> metadataBeforeRename = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals(1, metadataBeforeRename.size(), "Source should have 1 attachment"); + // assertEquals( + // "sample.txt", + // metadataBeforeRename.get(0).get("fileName"), + // "Original filename should be sample.txt"); + + // // Edit source entity back to draft mode + // String editSourceResponse = api.editEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!editSourceResponse.equals("Entity in draft mode")) { + // fail("Could not edit source entity to draft mode"); + // } - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - sourceCountBeforeMove, - sourceMetadataAfterMove.size(), - "Source entity in draft mode retains attachments after move (copy behavior)"); + // // Rename the attachment to testEdited.txt + // String newFileName = "testEdited.txt"; + // String renameResponse = + // api.renameAttachment( + // appUrl, entityName, facetName, moveSourceEntity, attachmentId, newFileName); + // assertEquals("Renamed", renameResponse, "Attachment should be renamed successfully"); + + // // Save source entity after rename + // saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity after rename: " + saveSourceResponse); + // } - Set sourceFileNamesAfterMove = - sourceMetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); + // // Verify renamed filename in source + // List> metadataAfterRename = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals(1, metadataAfterRename.size(), "Source should still have 1 attachment"); + // assertEquals( + // newFileName, + // metadataAfterRename.get(0).get("fileName"), + // "Filename should be updated to " + newFileName); + + // // Get objectId and folderId for move operation + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // String objectId = metadata.get("objectId").toString(); + // moveSourceFolderId = metadata.get("folderId").toString(); + // assertNotNull(objectId, "Object ID should not be null"); + // assertNotNull(moveSourceFolderId, "Folder ID should not be null"); + + // moveObjectIds.clear(); + // moveObjectIds.add(objectId); + + // // Create target entity + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity"); + // } - for (File file : files) { - assertTrue( - sourceFileNamesAfterMove.contains(file.getName()), - "Source (draft) should still contain attachment: " + file.getName()); - } + // // Save target before move + // String saveTargetBeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTargetBeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity before move"); + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Move attachment from source to target with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // fail("Move operation returned null result"); + // } - @Test - @Order(73) - public void testEditAttachmentFileNameAndMoveToTarget() throws Exception { - System.out.println( - "Test (73): Edit attachment file name in Source Entity and move it to Target Entity"); + // // Verify attachment moved to target with renamed filename + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals(1, targetMetadataAfterMove.size(), "Target should have 1 attachment after + // move"); + // assertEquals( + // newFileName, + // targetMetadataAfterMove.get(0).get("fileName"), + // "Target should have attachment with renamed filename: " + newFileName); + + // // Verify attachment removed from source + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterMove.size(), + // "Source entity should have no attachments after move with sourceFacet"); + + // // Clean up - delete both entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Create source entity and add attachment - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // @Test + // @Order(74) + // public void testChainMoveAttachmentsFromSourceToTarget1ToTarget2() throws Exception { + // System.out.println( + // "Test (74): Move attachments from Source Entity to Target Entity 1 and then to Target + // Entity 2"); - // Add attachment with original name (sample.txt) - ClassLoader classLoader = getClass().getClassLoader(); - File originalFile = new File(classLoader.getResource("sample.txt").getFile()); + // // Create source entity and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "text/plain"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, originalFile); - if (!createResponse.get(0).equals("Attachment created")) { - fail("Could not create attachment in source entity"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - String attachmentId = createResponse.get(1); - assertNotNull(attachmentId, "Attachment ID should not be null"); + // // Create attachments in source entity + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Save source entity + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Verify original filename - List> metadataBeforeRename = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals(1, metadataBeforeRename.size(), "Source should have 1 attachment"); - assertEquals( - "sample.txt", - metadataBeforeRename.get(0).get("fileName"), - "Original filename should be sample.txt"); - - // Edit source entity back to draft mode - String editSourceResponse = api.editEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!editSourceResponse.equals("Entity in draft mode")) { - fail("Could not edit source entity to draft mode"); - } + // // Get count of attachments in source + // int sourceCountInitial = sourceAttachmentIds.size(); + // assertTrue(sourceCountInitial > 0, "Source should have attachments"); - // Rename the attachment to testEdited.txt - String newFileName = "testEdited.txt"; - String renameResponse = - api.renameAttachment( - appUrl, entityName, facetName, moveSourceEntity, attachmentId, newFileName); - assertEquals("Renamed", renameResponse, "Attachment should be renamed successfully"); + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID from first attachment + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - // Save source entity after rename - saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity after rename: " + saveSourceResponse); - } + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Verify renamed filename in source - List> metadataAfterRename = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals(1, metadataAfterRename.size(), "Source should still have 1 attachment"); - assertEquals( - newFileName, - metadataAfterRename.get(0).get("fileName"), - "Filename should be updated to " + newFileName); - - // Get objectId and folderId for move operation - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - String objectId = metadata.get("objectId").toString(); - moveSourceFolderId = metadata.get("folderId").toString(); - assertNotNull(objectId, "Object ID should not be null"); - assertNotNull(moveSourceFolderId, "Folder ID should not be null"); - - moveObjectIds.clear(); - moveObjectIds.add(objectId); - - // Create target entity - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity"); - } + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - // Save target before move - String saveTargetBeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTargetBeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity before move"); - } + // // Create Target Entity 1 + // moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity 1"); + // } - // Move attachment from source to target with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - fail("Move operation returned null result"); - } + // // Save target1 before move + // String saveTarget1BeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); + // if (!saveTarget1BeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity 1 before move"); + // } - // Verify attachment moved to target with renamed filename - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals(1, targetMetadataAfterMove.size(), "Target should have 1 attachment after move"); - assertEquals( - newFileName, - targetMetadataAfterMove.get(0).get("fileName"), - "Target should have attachment with renamed filename: " + newFileName); + // // Move attachments from source to Target Entity 1 with sourceFacet + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult1 = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult1 == null) { + // fail("Move operation from source to target 1 returned null result"); + // } - // Verify attachment removed from source - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterMove.size(), - "Source entity should have no attachments after move with sourceFacet"); + // // Verify attachments moved to Target Entity 1 + // List> target1MetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertTrue( + // target1MetadataAfterMove.size() > 0, "Target entity 1 should have attachments after + // move"); + // assertEquals( + // sourceCountInitial, + // target1MetadataAfterMove.size(), + // "Target 1 should have " + sourceCountInitial + " attachments"); + + // // Verify all expected files are in Target Entity 1 + // Set target1FileNames = + // target1MetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // target1FileNames.contains(file.getName()), + // "Target 1 should contain attachment: " + file.getName()); + // } - // Clean up - delete both entities - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); - } + // // Verify attachments removed from source + // List> sourceMetadataAfterFirstMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // 0, + // sourceMetadataAfterFirstMove.size(), + // "Source entity should have no attachments after move to target 1"); + + // // Create Target Entity 2 + // String moveTargetEntity2 = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity2.equals("Could not create entity")) { + // fail("Could not create target entity 2"); + // } - @Test - @Order(74) - public void testChainMoveAttachmentsFromSourceToTarget1ToTarget2() throws Exception { - System.out.println( - "Test (74): Move attachments from Source Entity to Target Entity 1 and then to Target Entity 2"); + // // Save target2 before move + // String saveTarget2BeforeMoveResponse = + // api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity2); + // if (!saveTarget2BeforeMoveResponse.equals("Saved")) { + // fail("Could not save target entity 2 before move"); + // } - // Create source entity and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); - } + // // Get new object IDs and folder ID from Target Entity 1 for second move + // List target1AttachmentIds = new ArrayList<>(); + // for (Map metadata : target1MetadataAfterMove) { + // String attachmentId = metadata.get("ID").toString(); + // target1AttachmentIds.add(attachmentId); + // } - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // moveObjectIds.clear(); + // String target1FolderId = null; + // for (String attachmentId : target1AttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get folder ID from first attachment + // if (target1FolderId == null && metadata.containsKey("folderId")) { + // target1FolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata from target 1: " + e.getMessage()); + // } + // } - Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); - postData.put("createdAt", new Date().toString()); - postData.put("createdBy", "test@test.com"); - postData.put("modifiedBy", "test@test.com"); + // assertNotNull(target1FolderId, "Target 1 folder ID should not be null"); + + // // Move attachments from Target Entity 1 to Target Entity 2 with sourceFacet + // Map moveResult2 = + // api.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity2, + // target1FolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult2 == null) { + // fail("Move operation from target 1 to target 2 returned null result"); + // } - // Create attachments in source entity - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } + // // Verify attachments moved to Target Entity 2 + // List> target2MetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity2); + // assertTrue( + // target2MetadataAfterMove.size() > 0, "Target entity 2 should have attachments after + // move"); + // assertEquals( + // sourceCountInitial, + // target2MetadataAfterMove.size(), + // "Target 2 should have " + sourceCountInitial + " attachments"); + + // // Verify all expected files are in Target Entity 2 + // Set target2FileNames = + // target2MetadataAfterMove.stream() + // .map(m -> (String) m.get("fileName")) + // .collect(java.util.stream.Collectors.toSet()); + + // for (File file : files) { + // assertTrue( + // target2FileNames.contains(file.getName()), + // "Target 2 should contain attachment: " + file.getName()); + // } - // Save source entity - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } + // // Verify attachments removed from Target Entity 1 + // List> target1MetadataAfterSecondMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals( + // 0, + // target1MetadataAfterSecondMove.size(), + // "Target entity 1 should have no attachments after move to target 2"); + + // // Clean up - delete all three entities + // api.deleteEntity(appUrl, entityName, moveTargetEntity2); + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Get count of attachments in source - int sourceCountInitial = sourceAttachmentIds.size(); - assertTrue(sourceCountInitial > 0, "Source should have attachments"); + // @Test + // @Order(75) + // public void testMoveAttachmentsWithoutSDMRole() throws Exception { + // System.out.println("Test (75): Move attachments when user does not have SDM Role"); + + // // Create source entity with SDM role and add attachments + // moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveSourceEntity.equals("Could not create entity")) { + // fail("Could not create source entity"); + // } - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID from first attachment - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } - } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); - } - } + // // Prepare sample files + // ClassLoader classLoader = getClass().getClassLoader(); + // List files = new ArrayList<>(); + // files.add(new File(classLoader.getResource("sample.pdf").getFile())); + // files.add(new File(classLoader.getResource("sample.txt").getFile())); - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } + // Map postData = new HashMap<>(); + // postData.put("up__ID", moveSourceEntity); + // postData.put("mimeType", "application/pdf"); + // postData.put("createdAt", new Date().toString()); + // postData.put("createdBy", "test@test.com"); + // postData.put("modifiedBy", "test@test.com"); - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); + // // Create attachments in source entity with SDM role + // List sourceAttachmentIds = new ArrayList<>(); + // for (File file : files) { + // List createResponse = + // api.createAttachment( + // appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); + // if (createResponse.get(0).equals("Attachment created")) { + // sourceAttachmentIds.add(createResponse.get(1)); + // } else { + // fail("Could not create attachment in source entity"); + // } + // } - // Create Target Entity 1 - moveTargetEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity 1"); - } + // // Save source entity with SDM role + // String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, + // moveSourceEntity); + // if (!saveSourceResponse.equals("Saved")) { + // fail("Could not save source entity: " + saveSourceResponse); + // } - // Save target1 before move - String saveTarget1BeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity); - if (!saveTarget1BeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity 1 before move"); - } + // // Get count of attachments in source + // int sourceCountInitial = sourceAttachmentIds.size(); + // assertTrue(sourceCountInitial > 0, "Source should have attachments"); - // Move attachments from source to Target Entity 1 with sourceFacet - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult1 = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult1 == null) { - fail("Move operation from source to target 1 returned null result"); - } + // // Fetch object IDs from source entity + // moveObjectIds.clear(); + // for (String attachmentId : sourceAttachmentIds) { + // try { + // Map metadata = + // api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); + // if (metadata.containsKey("objectId")) { + // moveObjectIds.add(metadata.get("objectId").toString()); + // // Get source folder ID from first attachment + // if (moveSourceFolderId == null && metadata.containsKey("folderId")) { + // moveSourceFolderId = metadata.get("folderId").toString(); + // } + // } + // } catch (IOException e) { + // fail("Could not fetch attachment metadata: " + e.getMessage()); + // } + // } - // Verify attachments moved to Target Entity 1 - List> target1MetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertTrue( - target1MetadataAfterMove.size() > 0, "Target entity 1 should have attachments after move"); - assertEquals( - sourceCountInitial, - target1MetadataAfterMove.size(), - "Target 1 should have " + sourceCountInitial + " attachments"); + // if (moveObjectIds.size() != sourceAttachmentIds.size()) { + // fail("Could not fetch object IDs for all attachments"); + // } - // Verify all expected files are in Target Entity 1 - Set target1FileNames = - target1MetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); + // assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - for (File file : files) { - assertTrue( - target1FileNames.contains(file.getName()), - "Target 1 should contain attachment: " + file.getName()); - } + // // Create target entity with no SDM role + // moveTargetEntity = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); + // if (moveTargetEntity.equals("Could not create entity")) { + // fail("Could not create target entity with no SDM role"); + // } - // Verify attachments removed from source - List> sourceMetadataAfterFirstMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - 0, - sourceMetadataAfterFirstMove.size(), - "Source entity should have no attachments after move to target 1"); - - // Create Target Entity 2 - String moveTargetEntity2 = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity2.equals("Could not create entity")) { - fail("Could not create target entity 2"); - } + // // Try to move attachments from source to target using user without SDM role + // String sourceFacet = serviceName + "." + entityName + "." + facetName; + // String targetFacet = serviceName + "." + entityName + "." + facetName; + // Map moveResult = null; + // boolean moveOperationFailed = false; + // String errorMessage = null; + + // try { + // moveResult = + // apiNoRoles.moveAttachment( + // appUrl, + // entityName, + // facetName, + // moveTargetEntity, + // moveSourceFolderId, + // moveObjectIds, + // targetFacet, + // sourceFacet); + + // if (moveResult == null) { + // moveOperationFailed = true; + // errorMessage = "Move operation returned null"; + // } else if (moveResult.containsKey("error")) { + // moveOperationFailed = true; + // errorMessage = moveResult.get("error").toString(); + // } + // } catch (Exception e) { + // moveOperationFailed = true; + // errorMessage = e.getMessage(); + // } - // Save target2 before move - String saveTarget2BeforeMoveResponse = - api.saveEntityDraft(appUrl, entityName, srvpath, moveTargetEntity2); - if (!saveTarget2BeforeMoveResponse.equals("Saved")) { - fail("Could not save target entity 2 before move"); - } + // // Verify move operation failed + // assertTrue(moveOperationFailed, "Move operation should fail when user does not have SDM + // role"); + // assertNotNull(errorMessage, "Error message should be present when move operation fails"); + // System.out.println("Move operation failed as expected. Error: " + errorMessage); + + // // Verify attachments are still in source entity (not moved) + // List> sourceMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); + // assertEquals( + // sourceCountInitial, + // sourceMetadataAfterMove.size(), + // "Source should still have all attachments after failed move"); + + // // Verify target entity has no attachments + // List> targetMetadataAfterMove = + // api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); + // assertEquals( + // 0, targetMetadataAfterMove.size(), "Target should have no attachments after failed + // move"); + + // // Clean up - delete both entities using SDM role + // api.deleteEntity(appUrl, entityName, moveTargetEntity); + // api.deleteEntity(appUrl, entityName, moveSourceEntity); + // } - // Get new object IDs and folder ID from Target Entity 1 for second move - List target1AttachmentIds = new ArrayList<>(); - for (Map metadata : target1MetadataAfterMove) { - String attachmentId = metadata.get("ID").toString(); - target1AttachmentIds.add(attachmentId); + @Test + @Order(76) + void testReadCmisMetadataCreatedBy() { + System.out.println("Test (76) : Read CMIS metadata and verify createdBy field"); + String createdBy = CmisDocumentHelper.getCmisProperty(entityID, "sample.pdf", "cmis:createdBy"); + System.out.println("cmis:createdBy value: " + createdBy); + String tokenFlowFlag = System.getProperty("tokenFlow"); + if ("namedUser".equals(tokenFlowFlag)) { + assertEquals(username, createdBy, "cmis:createdBy should match username from credentials"); + } else { + assertNotNull(createdBy, "cmis:createdBy should not be null for technical user"); + assertFalse(createdBy.isEmpty(), "cmis:createdBy should not be empty for technical user"); } + } - moveObjectIds.clear(); - String target1FolderId = null; - for (String attachmentId : target1AttachmentIds) { + private boolean waitForUploadCompletion( + String entityId, String attachmentId, int timeoutSeconds) { + int maxIterations = timeoutSeconds / 2; + for (int i = 0; i < maxIterations; i++) { try { Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveTargetEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get folder ID from first attachment - if (target1FolderId == null && metadata.containsKey("folderId")) { - target1FolderId = metadata.get("folderId").toString(); - } + api.fetchMetadata(appUrl, entityName, facetName, entityId, attachmentId); + String uploadStatus = (String) metadata.get("uploadStatus"); + + if ("Success".equals(uploadStatus)) { + return true; + } else if ("Failed".equals(uploadStatus)) { + System.err.println("Upload failed for attachment: " + attachmentId); + return false; } - } catch (IOException e) { - fail("Could not fetch attachment metadata from target 1: " + e.getMessage()); - } - } - - assertNotNull(target1FolderId, "Target 1 folder ID should not be null"); - - // Move attachments from Target Entity 1 to Target Entity 2 with sourceFacet - Map moveResult2 = - api.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity2, - target1FolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult2 == null) { - fail("Move operation from target 1 to target 2 returned null result"); - } - - // Verify attachments moved to Target Entity 2 - List> target2MetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity2); - assertTrue( - target2MetadataAfterMove.size() > 0, "Target entity 2 should have attachments after move"); - assertEquals( - sourceCountInitial, - target2MetadataAfterMove.size(), - "Target 2 should have " + sourceCountInitial + " attachments"); - - // Verify all expected files are in Target Entity 2 - Set target2FileNames = - target2MetadataAfterMove.stream() - .map(m -> (String) m.get("fileName")) - .collect(java.util.stream.Collectors.toSet()); - for (File file : files) { - assertTrue( - target2FileNames.contains(file.getName()), - "Target 2 should contain attachment: " + file.getName()); + Thread.sleep(2000); + } catch (Exception e) { + System.err.println( + "Error checking upload status for attachment " + attachmentId + ": " + e.getMessage()); + return false; + } } - // Verify attachments removed from Target Entity 1 - List> target1MetadataAfterSecondMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals( - 0, - target1MetadataAfterSecondMove.size(), - "Target entity 1 should have no attachments after move to target 2"); - - // Clean up - delete all three entities - api.deleteEntity(appUrl, entityName, moveTargetEntity2); - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); + System.err.println("Upload timed out for attachment: " + attachmentId); + return false; } @Test - @Order(75) - public void testMoveAttachmentsWithoutSDMRole() throws Exception { - System.out.println("Test (75): Move attachments when user does not have SDM Role"); - - // Create source entity with SDM role and add attachments - moveSourceEntity = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveSourceEntity.equals("Could not create entity")) { - fail("Could not create source entity"); + @Order(77) + void testUploadVirusFileInScanDisabledRepo() throws IOException { + System.out.println( + "Test (77) : Upload EICAR virus file in virus scan disabled repo — expect upload to succeed"); + + boolean testStatus = false; + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + if (response.equals("Could not create entity")) { + fail("Could not create entity"); } + String testEntityID = response; - // Prepare sample files - ClassLoader classLoader = getClass().getClassLoader(); - List files = new ArrayList<>(); - files.add(new File(classLoader.getResource("sample.pdf").getFile())); - files.add(new File(classLoader.getResource("sample.txt").getFile())); + // Use EICAR test virus file + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } Map postData = new HashMap<>(); - postData.put("up__ID", moveSourceEntity); - postData.put("mimeType", "application/pdf"); + postData.put("up__ID", testEntityID); + postData.put("mimeType", "text/plain"); postData.put("createdAt", new Date().toString()); postData.put("createdBy", "test@test.com"); postData.put("modifiedBy", "test@test.com"); - // Create attachments in source entity with SDM role - List sourceAttachmentIds = new ArrayList<>(); - for (File file : files) { - List createResponse = - api.createAttachment( - appUrl, entityName, facetName, moveSourceEntity, srvpath, postData, file); - if (createResponse.get(0).equals("Attachment created")) { - sourceAttachmentIds.add(createResponse.get(1)); - } else { - fail("Could not create attachment in source entity"); - } - } - - // Save source entity with SDM role - String saveSourceResponse = api.saveEntityDraft(appUrl, entityName, srvpath, moveSourceEntity); - if (!saveSourceResponse.equals("Saved")) { - fail("Could not save source entity: " + saveSourceResponse); - } - - // Get count of attachments in source - int sourceCountInitial = sourceAttachmentIds.size(); - assertTrue(sourceCountInitial > 0, "Source should have attachments"); - - // Fetch object IDs from source entity - moveObjectIds.clear(); - for (String attachmentId : sourceAttachmentIds) { - try { - Map metadata = - api.fetchMetadata(appUrl, entityName, facetName, moveSourceEntity, attachmentId); - if (metadata.containsKey("objectId")) { - moveObjectIds.add(metadata.get("objectId").toString()); - // Get source folder ID from first attachment - if (moveSourceFolderId == null && metadata.containsKey("folderId")) { - moveSourceFolderId = metadata.get("folderId").toString(); - } + List createResponse = + api.createAttachment(appUrl, entityName, facetName, testEntityID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.equals("Attachment created")) { + String testAttachmentID = createResponse.get(1); + response = api.saveEntityDraft(appUrl, entityName, srvpath, testEntityID); + if (response.equals("Saved")) { + boolean uploadCompleted = waitForUploadCompletion(testEntityID, testAttachmentID, 120); + if (uploadCompleted) { + // Verify attachment is readable (upload succeeded despite being a virus file) + response = + api.readAttachment(appUrl, entityName, facetName, testEntityID, testAttachmentID); + assertEquals("OK", response, "Virus file should be readable in scan-disabled repository"); + testStatus = true; } - } catch (IOException e) { - fail("Could not fetch attachment metadata: " + e.getMessage()); } } - if (moveObjectIds.size() != sourceAttachmentIds.size()) { - fail("Could not fetch object IDs for all attachments"); - } - - assertNotNull(moveSourceFolderId, "Source folder ID should not be null"); - - // Create target entity with no SDM role - moveTargetEntity = apiNoRoles.createEntityDraft(appUrl, entityName, entityName2, srvpath); - if (moveTargetEntity.equals("Could not create entity")) { - fail("Could not create target entity with no SDM role"); - } + // Clean up + api.deleteEntity(appUrl, entityName, testEntityID); - // Try to move attachments from source to target using user without SDM role - String sourceFacet = serviceName + "." + entityName + "." + facetName; - String targetFacet = serviceName + "." + entityName + "." + facetName; - Map moveResult = null; - boolean moveOperationFailed = false; - String errorMessage = null; - - try { - moveResult = - apiNoRoles.moveAttachment( - appUrl, - entityName, - facetName, - moveTargetEntity, - moveSourceFolderId, - moveObjectIds, - targetFacet, - sourceFacet); - - if (moveResult == null) { - moveOperationFailed = true; - errorMessage = "Move operation returned null"; - } else if (moveResult.containsKey("error")) { - moveOperationFailed = true; - errorMessage = moveResult.get("error").toString(); - } - } catch (Exception e) { - moveOperationFailed = true; - errorMessage = e.getMessage(); + if (!testStatus) { + fail("Virus file upload should succeed in a virus scan disabled repository"); } - - // Verify move operation failed - assertTrue(moveOperationFailed, "Move operation should fail when user does not have SDM role"); - assertNotNull(errorMessage, "Error message should be present when move operation fails"); - System.out.println("Move operation failed as expected. Error: " + errorMessage); - - // Verify attachments are still in source entity (not moved) - List> sourceMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveSourceEntity); - assertEquals( - sourceCountInitial, - sourceMetadataAfterMove.size(), - "Source should still have all attachments after failed move"); - - // Verify target entity has no attachments - List> targetMetadataAfterMove = - api.fetchEntityMetadata(appUrl, entityName, facetName, moveTargetEntity); - assertEquals( - 0, targetMetadataAfterMove.size(), "Target should have no attachments after failed move"); - - // Clean up - delete both entities using SDM role - api.deleteEntity(appUrl, entityName, moveTargetEntity); - api.deleteEntity(appUrl, entityName, moveSourceEntity); } @Test @@ -6999,7 +7255,7 @@ void testDownloadButtonWithPdfAndLinkInDraftState() throws IOException { } // @Test - // @Order(76) + // @Order(78) // void testUploadAttachmentExceedingMaximumFileSize() throws IOException { // System.out.println( // "Test (76) : Upload attachment exceeding maximum file size in references facet"); diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_RepoSpecific.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_RepoSpecific.java new file mode 100644 index 000000000..e1e637e1c --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_RepoSpecific.java @@ -0,0 +1,597 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.utils.ShellScriptRunner; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +/** + * Integration tests for "Displaying Attachments Specific To Repository". Verifies that attachments + * created under one repository are not visible when the application switches to a different + * repository, and that duplicate file names across repositories are allowed. + */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_SingleFacet_RepoSpecific { + + private static final String UPDATE_ENV_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh"; + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String bookEntityName = "Books"; + private static String chapterEntityName = "Chapters"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String facetName = "attachments"; + private static String tenancyModel; + private static String defaultRepositoryID; + private static String virusScanRepositoryID; + private static ApiInterface api; + + // Entity IDs used across tests + private static String bookID1; // Book for top-level tests (create duplicate) + private static String attachmentID1; // Attachment created under defaultRepositoryID + private static String bookID_rename; // Separate book for rename duplicate test + private static String bookID2; // Book for chapter-level tests (create duplicate) + private static String chapterID1; // Chapter for nested entity tests (create duplicate) + private static String chapterAttachmentID1; // Attachment on chapter under defaultRepositoryID + private static String bookID_chapterRename; // Separate book for chapter rename test + private static String chapterID_rename; // Separate chapter for rename test + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryID"); + virusScanRepositoryID = credentialsProperties.getProperty("virusScanRepositoryID"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + defaultRepositoryID = credentialsProperties.getProperty("defaultRepositoryIDMT"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + System.out.println("Named user token flow"); + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + private static int runUpdateEnv(String value) throws Exception { + if (tenancyModel.equals("multi")) { + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--app", "bookshop-mt-srv", "--value", value); + } + return ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--value", value); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 1 – Setup: Switch to defaultRepositoryID, create entity, upload attachment + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(1) + void testSetupRepo1AndCreateAttachments() throws Exception { + System.out.println( + "Test (1) : Setup — switch to defaultRepositoryID (" + + defaultRepositoryID + + "), create entity with attachment"); + + // Switch to defaultRepositoryID + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create a book entity + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID1 = response; + + // Upload an attachment (sample.pdf) under defaultRepositoryID + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", bookID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, bookEntityName, facetName, bookID1, srvpath, postData, file); + assertEquals("Attachment created", createResponse.get(0), "Attachment creation should succeed"); + attachmentID1 = createResponse.get(1); + + // Save the entity + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Saved", response, "Entity save should succeed"); + + // Verify attachment is readable + response = api.readAttachment(appUrl, bookEntityName, facetName, bookID1, attachmentID1); + assertEquals("OK", response, "Attachment should be readable under defaultRepositoryID"); + + // Verify attachment count is 1 + List> attachments = + api.fetchEntityMetadata(appUrl, bookEntityName, facetName, bookID1); + assertEquals( + 1, attachments.size(), "Entity should have exactly 1 attachment under defaultRepositoryID"); + System.out.println("Setup complete: entity " + bookID1 + " with attachment " + attachmentID1); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 2 – Switch to virusScanRepositoryID, verify previous attachments are not visible + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(2) + void testSwitchToRepo2AttachmentsNotVisible() throws Exception { + System.out.println( + "Test (2) : Switch to virusScanRepositoryID (" + + virusScanRepositoryID + + "), verify attachments from defaultRepositoryID are not visible"); + + // Switch to virusScanRepositoryID + int exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + // The entity should still exist but have 0 attachments + String response = api.checkEntity(appUrl, bookEntityName, bookID1); + assertEquals("Entity exists", response, "Entity should still be visible after repo switch"); + + List> attachments = + api.fetchEntityMetadata(appUrl, bookEntityName, facetName, bookID1); + assertEquals( + 0, + attachments.size(), + "Entity should have 0 attachments after switching to virusScanRepositoryID"); + System.out.println( + "Verified: entity " + bookID1 + " has no attachments visible under virusScanRepositoryID"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 3 – Duplicate attachment name across repos (create) + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(3) + void testDuplicateAttachmentCreateAcrossRepos() throws Exception { + System.out.println( + "Test (3) : Create attachment with same name (sample.pdf) under virusScanRepositoryID — should succeed"); + + // Still on virusScanRepositoryID from previous test + // Edit the entity to draft + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Entity in draft mode", response, "Edit entity should succeed"); + + // Upload same file name (sample.pdf) under virusScanRepositoryID + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", bookID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, bookEntityName, facetName, bookID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Creating attachment with duplicate name across repos should succeed"); + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID1); + assertEquals("Saved", response, "Entity save should succeed"); + System.out.println( + "Duplicate attachment (sample.pdf) created successfully under virusScanRepositoryID"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 4 – Duplicate attachment name via rename across repos + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(4) + void testDuplicateAttachmentRenameAcrossRepos() throws Exception { + System.out.println( + "Test (4) : Create new entity with sample.pdf in defaultRepositoryID, switch to virusScanRepositoryID, upload" + + " sample1.pdf, rename to sample.pdf — should succeed"); + + // Switch to defaultRepositoryID to create a fresh entity with sample.pdf + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create a new entity under defaultRepositoryID + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID_rename = response; + + // Upload sample.pdf under defaultRepositoryID + ClassLoader classLoader = getClass().getClassLoader(); + File pdfFile = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", bookID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, bookEntityName, facetName, bookID_rename, srvpath, postData, pdfFile); + assertEquals("Attachment created", createResponse.get(0), "Attachment creation should succeed"); + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Saved", response, "Entity save should succeed under defaultRepositoryID"); + + // Switch to virusScanRepositoryID + exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + // Edit the entity and upload sample1.pdf (same extension, different name), then rename to + // sample.pdf + response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Entity in draft mode", response, "Edit entity should succeed"); + + File pdfFile2 = new File(classLoader.getResource("sample1.pdf").getFile()); + postData = new HashMap<>(); + postData.put("up__ID", bookID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + createResponse = + api.createAttachment( + appUrl, bookEntityName, facetName, bookID_rename, srvpath, postData, pdfFile2); + assertEquals("Attachment created", createResponse.get(0), "Upload sample1.pdf should succeed"); + String attachmentID2 = createResponse.get(1); + + response = + api.renameAttachment( + appUrl, bookEntityName, facetName, bookID_rename, attachmentID2, "sample.pdf"); + assertEquals("Renamed", response, "Renaming to duplicate name across repos should succeed"); + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_rename); + assertEquals("Saved", response, "Entity save after rename should succeed"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 5 – Nested entities: repeat scenarios for Chapters + // ─────────────────────────────────────────────────────────────────────────── + + @Test + @Order(5) + void testNestedEntitySetupRepo1() throws Exception { + System.out.println( + "Test (5a) : Switch to defaultRepositoryID (" + + defaultRepositoryID + + "), create book+chapter with attachment on chapter"); + + // Switch to defaultRepositoryID + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create a book + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID2 = response; + + // Create a chapter inside the book + String chapterResponse = + api.createEntityDraft(appUrl, chapterEntityName, entityName2, srvpath, bookID2); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + chapterID1 = chapterResponse; + + // Upload attachment to chapter + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facetName, chapterID1, srvpath, postData, file); + assertEquals( + "Attachment created", createResponse.get(0), "Chapter attachment creation should succeed"); + chapterAttachmentID1 = createResponse.get(1); + + // Save the book (saves chapter too) + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID2); + assertEquals("Saved", response, "Book save should succeed"); + + // Verify chapter attachment is readable + response = + api.readAttachment(appUrl, chapterEntityName, facetName, chapterID1, chapterAttachmentID1); + assertEquals("OK", response, "Chapter attachment should be readable under defaultRepositoryID"); + + List> attachments = + api.fetchEntityMetadata(appUrl, chapterEntityName, facetName, chapterID1); + assertEquals( + 1, + attachments.size(), + "Chapter should have exactly 1 attachment under defaultRepositoryID"); + System.out.println( + "Nested setup complete: book " + + bookID2 + + ", chapter " + + chapterID1 + + ", attachment " + + chapterAttachmentID1); + } + + @Test + @Order(6) + void testNestedEntitySwitchToRepo2() throws Exception { + System.out.println( + "Test (5b) : Switch to virusScanRepositoryID, verify chapter attachments from defaultRepositoryID are not visible"); + + // Switch to virusScanRepositoryID + int exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + // Chapter should still exist but have 0 attachments + String response = api.checkEntity(appUrl, chapterEntityName, chapterID1); + assertEquals("Entity exists", response, "Chapter should still be visible after repo switch"); + + List> attachments = + api.fetchEntityMetadata(appUrl, chapterEntityName, facetName, chapterID1); + assertEquals( + 0, + attachments.size(), + "Chapter should have 0 attachments after switching to virusScanRepositoryID"); + System.out.println( + "Verified: chapter " + + chapterID1 + + " has no attachments visible under virusScanRepositoryID"); + } + + @Test + @Order(7) + void testNestedEntityDuplicateCreate() throws Exception { + System.out.println( + "Test (5c) : Create attachment with same name on chapter under virusScanRepositoryID — should succeed"); + + // Still on virusScanRepositoryID + String response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID2); + assertEquals("Entity in draft mode", response, "Edit book should succeed"); + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID1); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facetName, chapterID1, srvpath, postData, file); + assertEquals( + "Attachment created", + createResponse.get(0), + "Duplicate chapter attachment across repos should succeed"); + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID2); + assertEquals("Saved", response, "Book save should succeed"); + System.out.println( + "Duplicate attachment (sample.pdf) created on chapter under virusScanRepositoryID — success"); + } + + @Test + @Order(8) + void testNestedEntityDuplicateRename() throws Exception { + System.out.println( + "Test (5d) : Create new book+chapter with sample.pdf in defaultRepositoryID, switch to virusScanRepositoryID, upload" + + " sample1.pdf on chapter, rename to sample.pdf — should succeed"); + + // Switch to defaultRepositoryID to create a fresh book+chapter with sample.pdf on chapter + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for defaultRepositoryID"); + + // Create a new book + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + bookID_chapterRename = response; + + // Create a chapter inside the book + String chapterResponse = + api.createEntityDraft( + appUrl, chapterEntityName, entityName2, srvpath, bookID_chapterRename); + assertNotEquals("Could not create entity", chapterResponse, "Chapter creation should succeed"); + chapterID_rename = chapterResponse; + + // Upload sample.pdf to chapter under defaultRepositoryID + ClassLoader classLoader = getClass().getClassLoader(); + File pdfFile = new File(classLoader.getResource("sample.pdf").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", chapterID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment( + appUrl, chapterEntityName, facetName, chapterID_rename, srvpath, postData, pdfFile); + assertEquals( + "Attachment created", createResponse.get(0), "Chapter attachment creation should succeed"); + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_chapterRename); + assertEquals("Saved", response, "Book save should succeed under defaultRepositoryID"); + + // Switch to virusScanRepositoryID + exitCode = runUpdateEnv(virusScanRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0 for virusScanRepositoryID"); + + // Edit the book, upload sample1.pdf (same extension, different name) to chapter, rename to + // sample.pdf + response = api.editEntityDraft(appUrl, bookEntityName, srvpath, bookID_chapterRename); + assertEquals("Entity in draft mode", response, "Edit book should succeed"); + + File pdfFile2 = new File(classLoader.getResource("sample1.pdf").getFile()); + postData = new HashMap<>(); + postData.put("up__ID", chapterID_rename); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + createResponse = + api.createAttachment( + appUrl, chapterEntityName, facetName, chapterID_rename, srvpath, postData, pdfFile2); + assertEquals( + "Attachment created", + createResponse.get(0), + "Upload sample1.pdf to chapter should succeed"); + String chapterAttachmentID2 = createResponse.get(1); + + response = + api.renameAttachment( + appUrl, + chapterEntityName, + facetName, + chapterID_rename, + chapterAttachmentID2, + "sample.pdf"); + assertEquals( + "Renamed", response, "Renaming to duplicate name on chapter across repos should succeed"); + + response = api.saveEntityDraft(appUrl, bookEntityName, srvpath, bookID_chapterRename); + assertEquals("Saved", response, "Book save after chapter rename should succeed"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 9 – Create attachment with non-existent repository ID → error + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(9) + void testCreateAttachment_NonExistentRepo_FailsWithRepoInfoError() throws Exception { + String fakeRepoId = "non-existent-repo-" + UUID.randomUUID(); + System.out.println( + "Test (9) : Switch to non-existent repo (" + + fakeRepoId + + ") and attempt attachment creation — expect failure"); + + // Switch to a random non-existent repository ID + int exitCode = runUpdateEnv(fakeRepoId); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + + // Create a book entity (draft creation should still succeed) + String response = api.createEntityDraft(appUrl, bookEntityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Book creation should succeed"); + String bookId = response; + + // Upload an attachment + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.txt").getFile()); + Map postData = new HashMap<>(); + postData.put("up__ID", bookId); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, bookEntityName, facetName, bookId, srvpath, postData, file); + + // Attachment content upload should fail because the repo doesn't exist + String status = createResponse.get(0); + assertNotEquals( + "Attachment created", status, "Attachment should fail with non-existent repository"); + assertTrue( + status.toLowerCase().contains("repository") + || status.toLowerCase().contains("error") + || status.toLowerCase().contains("not found") + || status.toLowerCase().contains("failed"), + "Error should indicate repository issue. Got: " + status); + System.out.println("Expected error received: " + status); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 10 – Revert REPOSITORY_ID back to default + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(10) + void testRevertToDefaultRepository() throws Exception { + System.out.println( + "Test (10) : Revert REPOSITORY_ID to default repository: " + defaultRepositoryID); + int exitCode = runUpdateEnv(defaultRepositoryID); + assertEquals(0, exitCode, "cf-update-env.sh should exit with code 0"); + System.out.println("Reverted to default repository: " + defaultRepositoryID); + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_VersionedRepository.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_VersionedRepository.java new file mode 100644 index 000000000..0007f7000 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_VersionedRepository.java @@ -0,0 +1,144 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +class IntegrationTest_SingleFacet_VersionedRepository { + + private static String token; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String serviceName = "AdminService"; + private static String entityName = "Books"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static String facetName = "attachments"; + private static String tenancyModel; + private static ApiInterface api; + private static String entityID; + + @BeforeAll + static void setup() throws IOException { + Properties credentialsProperties = Credentials.getCredentials(); + tenancyModel = System.getProperty("tenancyModel"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + + if (tenancyModel.equals("single")) { + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + + String tokenFlowFlag = System.getProperty("tokenFlow"); + Request request; + if (tokenFlowFlag.equals("namedUser")) { + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + String responseBody = response.body().string(); + response.close(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + System.out.println("Error body: " + responseBody); + fail("Token generation failed with response code: " + response.code()); + } + token = new ObjectMapper().readTree(responseBody).get("access_token").asText(); + + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else { + config.put("serviceName", serviceName); + api = new Api(config); + } + } + + @Test + void testCreateEntityAndUploadAttachmentShouldFail() throws IOException { + System.out.println( + "Test (2) : Create entity and upload attachment on versioned repository — expect error"); + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + assertNotEquals("Could not create entity", response, "Entity creation should succeed"); + entityID = response; + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + List createResponse = + api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + String check = createResponse.get(0); + + if (check.equals("Attachment created")) { + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + assertNotEquals("Saved", response, "Save should fail on versioned repository"); + System.out.println("Save failed as expected: " + response); + } else { + System.out.println("Operation failed as expected: " + check); + assertTrue( + check.contains("error") || check.contains("Error"), + "Response should contain an error message"); + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_Virus.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_Virus.java new file mode 100644 index 000000000..57831e50d --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_SingleFacet_Virus.java @@ -0,0 +1,292 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.*; +import okhttp3.*; +import org.junit.jupiter.api.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_SingleFacet_Virus { + private static String token; + private static String entityID; + private static String facetName = "attachments"; + private static String clientId; + private static String clientSecret; + private static String appUrl; + private static String authUrl; + private static String username; + private static String password; + private static String noSDMRoleUsername; + private static String noSDMRoleUserPassword; + private static String serviceName = "AdminService"; + private static String entityName = "Books"; + private static String entityName2 = "author"; + private static String srvpath = "AdminService"; + private static ApiInterface api; + private static String attachmentID1 = ""; + private static String attachmentID2 = ""; + + @BeforeAll + static void setup() throws IOException { + // Define your clientId and clientSecret + Properties credentialsProperties = Credentials.getCredentials(); + String tenancyModel = System.getProperty("tenancyModel"); + String tenant = System.getProperty("tenant"); + + username = credentialsProperties.getProperty("username"); + password = credentialsProperties.getProperty("password"); + noSDMRoleUsername = credentialsProperties.getProperty("noSDMRoleUsername"); + noSDMRoleUserPassword = credentialsProperties.getProperty("noSDMRoleUserPassword"); + if (tenancyModel.equals("single")) { + System.out.println("Running integration tests | Single tenant Scenario"); + clientId = credentialsProperties.getProperty("clientID"); + clientSecret = credentialsProperties.getProperty("clientSecret"); + appUrl = credentialsProperties.getProperty("appUrl"); + authUrl = credentialsProperties.getProperty("authUrl"); + } else if (tenancyModel.equals("multi")) { + clientId = credentialsProperties.getProperty("clientIDMT"); + clientSecret = credentialsProperties.getProperty("clientSecretMT"); + appUrl = credentialsProperties.getProperty("appUrlMT"); + if (tenant.equals("TENANT1")) { + System.out.println("Running integration tests | Multitenant Scenario | SDM DEV Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT1"); + } else if (tenant.equals("TENANT2")) { + System.out.println( + "Running integration tests | Multitenant Scenario | Googleworkspace Consumer"); + authUrl = credentialsProperties.getProperty("authUrlMT2"); + } else { + throw new IllegalArgumentException("Invalid tenant specified: " + tenant); + } + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + + // Encode clientId:clientSecret to Base64 + String credentials = clientId + ":" + clientSecret; + String basicAuth = + "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8)); + + OkHttpClient client = + new OkHttpClient.Builder() + .connectTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .writeTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .readTimeout(120, java.util.concurrent.TimeUnit.SECONDS) + .build(); + MediaType mediaType = MediaType.parse("text/plain"); + RequestBody body = RequestBody.create(mediaType, ""); + Request request; + + String tokenFlowFlag = System.getProperty("tokenFlow"); + if (tokenFlowFlag.equals("namedUser")) { + System.out.println("Named user token flow"); + request = + new Request.Builder() + .url( + authUrl + + "/oauth/token?grant_type=password&username=" + + username + + "&password=" + + password) + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else if (tokenFlowFlag.equals("technicalUser")) { + System.out.println("Technical user token flow"); + request = + new Request.Builder() + .url(authUrl + "/oauth/token?grant_type=client_credentials") + .method("POST", body) + .addHeader("Authorization", basicAuth) + .build(); + } else { + throw new IllegalArgumentException("Invalid token flow specified: " + tokenFlowFlag); + } + + Response response = client.newCall(request).execute(); + if (response.code() != 200) { + System.out.println("Token generation failed. Response code: " + response.code()); + String errorBody = response.body().string(); + System.out.println("Error body: " + errorBody); + } + token = new ObjectMapper().readTree(response.body().string()).get("access_token").asText(); + response.close(); + Map config = new HashMap<>(); + config.put("Authorization", "Bearer " + token); + if (tenancyModel.equals("multi")) { + api = new ApiMT(config); + } else if (tenancyModel.equals("single")) { + config.put("serviceName", serviceName); + api = new Api(config); + } else { + throw new IllegalArgumentException("Invalid tenancy model specified: " + tenancyModel); + } + } + + /** + * Helper method to wait for attachment upload completion. + * + * @param entityId The ID of the entity containing the attachment + * @param attachmentId The ID of the attachment to check + * @param timeoutSeconds Maximum time to wait in seconds + * @return true if upload completed successfully, false if failed or timed out + */ + private boolean waitForUploadCompletion( + String entityId, String attachmentId, int timeoutSeconds) { + int maxIterations = timeoutSeconds / 2; // Check every 2 seconds + for (int i = 0; i < maxIterations; i++) { + try { + Map metadata = + api.fetchMetadataDraft(appUrl, entityName, facetName, entityId, attachmentId); + String uploadStatus = (String) metadata.get("uploadStatus"); + + if ("Success".equals(uploadStatus)) { + return true; + } else if ("Failed".equals(uploadStatus)) { + System.err.println("Upload failed for attachment: " + attachmentId); + return false; + } + + // Still uploading, wait before checking again + Thread.sleep(2000); + } catch (Exception e) { + System.err.println( + "Error checking upload status for attachment " + attachmentId + ": " + e.getMessage()); + return false; + } + } + + System.err.println("Upload timed out for attachment: " + attachmentId); + return false; + } + + @Test + @Order(1) + void testCreateEntityAndCheck() { + System.out.println("Test (1) : Create entity and check if it exists"); + boolean testStatus = false; + String response = api.createEntityDraft(appUrl, entityName, entityName2, srvpath); + if (response != "Could not create entity") { + entityID = response; + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Saved") { + response = api.checkEntity(appUrl, entityName, entityID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + if (!testStatus) { + fail("Could not create entity"); + } + } + + @Test + @Order(2) + void testUpdateEmptyEntity() { + System.out.println("Test (2) : Update an existing entity"); + boolean testStatus = false; + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Entity in draft mode") { + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Saved") { + response = api.checkEntity(appUrl, entityName, entityID); + if (response.equals("Entity exists")) { + testStatus = true; + } + } + } + if (!testStatus) { + fail("Could not update entity"); + } + } + + @Test + @Order(3) + void testUploadSingleAttachmentPDF() throws IOException { + System.out.println("Test (3) : Upload pdf"); + boolean testStatus = false; + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("sample.pdf").getFile()); + + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "application/pdf"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Entity in draft mode") { + List createResponse = + api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.equals("Attachment created")) { + attachmentID1 = createResponse.get(1); + response = api.readAttachmentDraft(appUrl, entityName, facetName, entityID, attachmentID1); + if (response.equals("OK")) { + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response.equals("Saved")) { + response = api.readAttachment(appUrl, entityName, facetName, entityID, attachmentID1); + + if (response.equals("OK")) { + testStatus = true; + } + } + } + } + } + if (!testStatus) { + fail("Could not upload sample.pdf " + response); + } + } + + @Test + @Order(4) + void testUploadVirusFileInScannedRepo() throws IOException { + System.out.println("Test (4) : Upload EICAR virus file — expect virus scan to reject the file"); + + boolean testStatus = false; + + String eicarFilePath = System.getProperty("eicar.file.path", "eicar.com.txt"); + File file = new File(eicarFilePath); + if (!file.exists()) { + fail("EICAR virus test file not found at: " + file.getAbsolutePath()); + } + + Map postData = new HashMap<>(); + postData.put("up__ID", entityID); + postData.put("mimeType", "text/plain"); + postData.put("createdAt", new Date().toString()); + postData.put("createdBy", "test@test.com"); + postData.put("modifiedBy", "test@test.com"); + + String response = api.editEntityDraft(appUrl, entityName, srvpath, entityID); + if (response == "Entity in draft mode") { + List createResponse = + api.createAttachment(appUrl, entityName, facetName, entityID, srvpath, postData, file); + String check = createResponse.get(0); + if (check.contains("malware") || check.contains("potential malware")) { + testStatus = true; + } else if (check.equals("Attachment created")) { + attachmentID2 = createResponse.get(1); + response = api.saveEntityDraft(appUrl, entityName, srvpath, entityID); + if (response.equals("Saved")) { + boolean uploadSucceeded = waitForUploadCompletion(entityID, attachmentID2, 120); + if (!uploadSucceeded) { + testStatus = true; + } else { + fail("Virus file should have been rejected by the virus scanner but upload succeeded"); + } + } + } + } + if (!testStatus) { + fail("Could not verify virus file rejection"); + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Subscription.java b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Subscription.java new file mode 100644 index 000000000..2ec8dc3f1 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/IntegrationTest_Subscription.java @@ -0,0 +1,378 @@ +package integration.com.sap.cds.sdm; + +import static org.junit.jupiter.api.Assertions.*; + +import integration.com.sap.cds.sdm.utils.ShellScriptRunner; +import java.util.Map; +import java.util.Properties; +import org.junit.jupiter.api.*; + +/** + * Integration tests for subscription lifecycle — verifies that subscribing and unsubscribing + * correctly onboards/offboards SDM repositories. + * + *

Test scenarios: + * + *

    + *
  1. Create subscription without existing repo → repo gets onboarded + *
  2. Subscribe when already subscribed → handled gracefully, repo intact + *
  3. Delete subscription with other repos → only subscription repo is offboarded + *
  4. Delete subscription with only the correct repo → repo is offboarded + *
  5. Delete subscription when repo doesn't exist → logs indicate 404 from DI + *
+ */ +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IntegrationTest_Subscription { + + private static final String SUBSCRIBE_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-subscribe.sh"; + private static final String UNSUBSCRIBE_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-unsubscribe.sh"; + private static final String REPO_MANAGE_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/sdm-repo-manage.sh"; + private static final String CF_LOGS_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-logs.sh"; + + private static final String SUBSCRIPTION_REPO_EXTERNAL_ID = "MULTITENANT-TEST-REPO"; + private static final String MT_APP_NAME = "bookshop-mt-srv"; + private static final Map TENANT_ENV = + Map.of("ACTIVE_TENANT", System.getProperty("tenant", "TENANT1").replace("TENANT", "")); + + private static Properties credentials; + private static String consumerSubdomain; + + @BeforeAll + static void setup() throws Exception { + credentials = Credentials.getCredentials(System.getProperty("tenant", "TENANT1")); + consumerSubdomain = credentials.getProperty("consumerSubdomainMT"); + assertNotNull(consumerSubdomain, "consumerSubdomainMT must be set in credentials.properties"); + + // Ensure subscription is active before tests run + System.out.println("BeforeAll: Ensuring app is subscribed..."); + int subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + assertEquals(0, subscribeExit, "Initial subscription should succeed"); + Thread.sleep(15_000); + + // Verify repo exists after subscription; if not, onboard it + System.out.println("BeforeAll: Checking if repo exists..."); + ShellScriptRunner.Result repoResult = + ShellScriptRunner.runAndCaptureAll( + REPO_MANAGE_SCRIPT, + "check", + "--externalId", + SUBSCRIPTION_REPO_EXTERNAL_ID, + "--subdomain", + consumerSubdomain); + if (repoResult.getExitCode() != 0) { + System.out.println("BeforeAll: Repo not found — onboarding..."); + int onboardExit = + ShellScriptRunner.run( + REPO_MANAGE_SCRIPT, + "onboard", + "--externalId", + SUBSCRIPTION_REPO_EXTERNAL_ID, + "--subdomain", + consumerSubdomain); + assertEquals(0, onboardExit, "Repo onboard should succeed"); + Thread.sleep(10_000); + } + System.out.println("BeforeAll: Subscription active and repo verified."); + } + + /** Check if a repo exists in the consumer scope. Returns the Result. */ + private ShellScriptRunner.Result repoCheck(String externalId) throws Exception { + return ShellScriptRunner.runAndCaptureAll( + REPO_MANAGE_SCRIPT, "check", "--externalId", externalId, "--subdomain", consumerSubdomain); + } + + /** Onboard a repo in the consumer scope. Returns exit code. */ + private int repoOnboard(String externalId) throws Exception { + return ShellScriptRunner.run( + REPO_MANAGE_SCRIPT, + "onboard", + "--externalId", + externalId, + "--subdomain", + consumerSubdomain); + } + + /** Offboard a repo in the consumer scope. Returns the Result. */ + private ShellScriptRunner.Result repoOffboard(String externalId) throws Exception { + return ShellScriptRunner.runAndCaptureAll( + REPO_MANAGE_SCRIPT, + "offboard", + "--externalId", + externalId, + "--subdomain", + consumerSubdomain); + } + + /** Check if a repo exists in provider scope (no --subdomain). Returns the Result. */ + private ShellScriptRunner.Result repoCheckProviderScope(String externalId) throws Exception { + return ShellScriptRunner.runAndCaptureAll( + REPO_MANAGE_SCRIPT, "check", "--externalId", externalId); + } + + /** Onboard a repo in provider scope (no --subdomain). Returns exit code. */ + private int repoOnboardProviderScope(String externalId) throws Exception { + return ShellScriptRunner.run(REPO_MANAGE_SCRIPT, "onboard", "--externalId", externalId); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 1 — Subscribe when already subscribed → handled gracefully, repo intact + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(1) + void testCreateSubscription_ExistingRepo_OnboardingSkipped() throws Exception { + System.out.println("Test (1) : Subscribe when already subscribed — expect graceful handling"); + + // Pre-condition: @BeforeAll left us subscribed with the repo onboarded. + // Verify repo exists in consumer scope. + System.out.println(" Verifying repo exists from setup subscription..."); + ShellScriptRunner.Result checkResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals( + 0, checkResult.getExitCode(), "Repo should exist in consumer scope from @BeforeAll"); + + // Act: Subscribe again (should detect 'Already subscribed' and exit 0) + System.out.println(" Re-subscribing..."); + ShellScriptRunner.Result subscribeResult = + ShellScriptRunner.runAndCaptureAll(TENANT_ENV, SUBSCRIBE_SCRIPT); + assertEquals(0, subscribeResult.getExitCode(), "Re-subscription should succeed"); + assertTrue( + subscribeResult.containsIgnoreCase("Already subscribed") + || subscribeResult.containsIgnoreCase("Subscription is active"), + "Subscribe output should indicate already subscribed or active. Output:\n" + + subscribeResult.getOutput()); + + // Verify: repo should still exist (subscription didn't break anything) + ShellScriptRunner.Result verifyResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals(0, verifyResult.getExitCode(), "Repository should still exist"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 2 — Delete subscription with other repos → only subscription repo offboarded + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(2) + void testDeleteSubscription_MultipleRepos_OnlyCorrectRepoOffboarded() throws Exception { + System.out.println( + "Test (2) : Unsubscribe with multiple repos — only correct repo should be offboarded"); + + // Pre-condition: subscription is active (from test 2), subscription repo exists. + // Ensure a second repo exists in provider scope (not tied to consumer subscription). + String otherRepo = credentials.getProperty("defaultRepositoryID"); + assertNotNull(otherRepo, "defaultRepositoryID should be defined in credentials.properties"); + ShellScriptRunner.Result checkOther = repoCheckProviderScope(otherRepo); + if (checkOther.getExitCode() != 0) { + System.out.println(" Onboarding other repo '" + otherRepo + "' in provider scope..."); + int onboardExit = repoOnboardProviderScope(otherRepo); + assertEquals(0, onboardExit, "Provider-scope onboard of other repo should succeed"); + } + + // Act: Unsubscribe + System.out.println(" Unsubscribing..."); + int unsubscribeExit = ShellScriptRunner.run(TENANT_ENV, UNSUBSCRIBE_SCRIPT); + assertEquals(0, unsubscribeExit, "Unsubscription should succeed"); + + // Allow time for async offboarding + Thread.sleep(15_000); + + // After unsubscribing, consumer-scoped token is no longer valid, so we + // verify the offboard via CF logs instead of checking consumer scope. + System.out.println(" Fetching CF logs to verify repo offboard..."); + ShellScriptRunner.Result logResult = + ShellScriptRunner.runAndCaptureAll(CF_LOGS_SCRIPT, "--app", MT_APP_NAME); + String logOutput = logResult.getOutput(); + boolean offboarded = + logResult.containsIgnoreCase("Offboarded") || logResult.containsIgnoreCase("offboard"); + assertTrue( + offboarded, + "CF logs should indicate repo was offboarded. Logs:\n" + + logOutput.substring(0, Math.min(logOutput.length(), 2000))); + + // Verify: The other repo (provider scope) should still exist + ShellScriptRunner.Result verifyOther = repoCheckProviderScope(otherRepo); + assertEquals( + 0, + verifyOther.getExitCode(), + "Other repo '" + otherRepo + "' should still exist after unsubscription"); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 3 — Delete subscription with only correct repo → repo offboarded + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(3) + void testDeleteSubscription_OnlyCorrectRepo_RepoOffboarded() throws Exception { + System.out.println( + "Test (3) : Unsubscribe with only the subscription repo — expect repo offboarded"); + + // Pre-condition: Subscribe and ensure only the subscription repo exists + // Wait for test 2's unsubscribe to fully complete + Thread.sleep(30_000); + + System.out.println(" Subscribing to set up precondition..."); + int subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + if (subscribeExit != 0) { + System.out.println( + " First subscribe attempt failed (exit " + subscribeExit + ") — retrying after 30s..."); + Thread.sleep(30_000); + subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + } + assertEquals(0, subscribeExit, "Subscription should succeed"); + + // Wait for repo to be onboarded + Thread.sleep(15_000); + + // Verify precondition — repo exists in consumer scope + ShellScriptRunner.Result checkResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals(0, checkResult.getExitCode(), "Subscription repo should exist before unsubscribe"); + + // Act: Unsubscribe + System.out.println(" Unsubscribing..."); + int unsubscribeExit = ShellScriptRunner.run(TENANT_ENV, UNSUBSCRIBE_SCRIPT); + assertEquals(0, unsubscribeExit, "Unsubscription should succeed"); + + // Allow time for offboarding + Thread.sleep(15_000); + + // After unsubscribing, consumer-scoped token is no longer valid. + // Verify offboard via CF logs. + System.out.println(" Fetching CF logs to verify repo offboard..."); + ShellScriptRunner.Result logResult = + ShellScriptRunner.runAndCaptureAll(CF_LOGS_SCRIPT, "--app", MT_APP_NAME); + String logOutput = logResult.getOutput(); + boolean offboarded = + logResult.containsIgnoreCase("Offboarded") || logResult.containsIgnoreCase("offboard"); + assertTrue( + offboarded, + "CF logs should confirm repo was offboarded. Logs:\n" + + logOutput.substring(0, Math.min(logOutput.length(), 2000))); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 4 — Delete subscription when repo doesn't exist → logs indicate 404 + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(4) + void testDeleteSubscription_RepoDoesNotExist_Logs404() throws Exception { + System.out.println( + "Test (4) : Unsubscribe when repo doesn't exist — expect logs to indicate 404 from DI"); + + // Pre-condition: Ensure subscribed but repo does NOT exist + // Wait extra time for test 4's unsubscribe to fully complete + Thread.sleep(30_000); + + System.out.println(" Subscribing..."); + int subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + if (subscribeExit != 0) { + // Retry once after waiting — previous unsubscribe may still be processing + System.out.println( + " First subscribe attempt failed (exit " + subscribeExit + ") — retrying after 30s..."); + Thread.sleep(30_000); + subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + } + assertEquals(0, subscribeExit, "Subscription should succeed"); + + // Wait for subscription callback to complete + Thread.sleep(15_000); + + // Verify repo was onboarded by the subscription callback + System.out.println(" Verifying repo was onboarded after subscription..."); + ShellScriptRunner.Result repoResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals( + 0, + repoResult.getExitCode(), + "Repository should exist after subscription before manual offboard"); + + // Manually offboard the repo so it doesn't exist when we unsubscribe + System.out.println(" Manually offboarding repo to set up precondition..."); + ShellScriptRunner.Result offboardResult = repoOffboard(SUBSCRIPTION_REPO_EXTERNAL_ID); + // It's OK if offboard fails because the repo might not exist + if (offboardResult.getExitCode() == 0) { + System.out.println(" Repo offboarded successfully."); + } else { + System.out.println( + " Repo was already not present (exit code: " + offboardResult.getExitCode() + ")"); + } + + // Verify precondition — repo should NOT exist + ShellScriptRunner.Result checkResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals( + 1, checkResult.getExitCode(), "Repo should NOT exist before unsubscribe for this test"); + + // Act: Unsubscribe (the app will try to offboard a non-existent repo) + System.out.println(" Unsubscribing..."); + int unsubscribeExit = ShellScriptRunner.run(TENANT_ENV, UNSUBSCRIBE_SCRIPT); + assertEquals(0, unsubscribeExit, "Unsubscription itself should succeed"); + + // Allow time for the unsubscribe callback to process + Thread.sleep(15_000); + + // Verify: Check CF logs for 404 indication from DI/SDM + System.out.println(" Fetching CF logs to verify 404 handling..."); + ShellScriptRunner.Result logResult = + ShellScriptRunner.runAndCaptureAll(CF_LOGS_SCRIPT, "--app", MT_APP_NAME); + String logOutput = logResult.getOutput(); + + boolean has404Indication = + logResult.containsIgnoreCase("not found") + || logResult.containsIgnoreCase("Repository with ID") + || logResult.containsIgnoreCase("404") + || logResult.containsIgnoreCase("does not exist"); + assertTrue( + has404Indication, + "CF logs should indicate a 404 or 'not found' when offboarding non-existent repo. Logs:\n" + + logOutput.substring(0, Math.min(logOutput.length(), 2000))); + } + + // ─────────────────────────────────────────────────────────────────────────── + // Test 5 — Create subscription without existing repo → repo gets onboarded + // ─────────────────────────────────────────────────────────────────────────── + @Test + @Order(5) + void testCreateSubscription_NoExistingRepo_RepoOnboarded() throws Exception { + System.out.println("Test (5) : Subscribe without existing repo — expect repo to be onboarded"); + + // Wait for test 4's unsubscribe to fully complete + Thread.sleep(30_000); + + // Pre-condition: ensure the repo does NOT exist (offboard if present) + System.out.println(" Ensuring repo '" + SUBSCRIPTION_REPO_EXTERNAL_ID + "' does not exist..."); + ShellScriptRunner.Result checkResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + if (checkResult.getExitCode() == 0) { + // Repo exists — offboard it first + System.out.println(" Repo exists — offboarding to set up precondition..."); + ShellScriptRunner.Result offResult = repoOffboard(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals(0, offResult.getExitCode(), "Pre-condition offboard should succeed"); + } + + // Also ensure NOT subscribed + System.out.println(" Ensuring consumer is unsubscribed..."); + ShellScriptRunner.run(TENANT_ENV, UNSUBSCRIBE_SCRIPT); + + // Act: Subscribe + System.out.println(" Subscribing..."); + int subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + if (subscribeExit != 0) { + System.out.println( + " First subscribe attempt failed (exit " + subscribeExit + ") — retrying after 30s..."); + Thread.sleep(30_000); + subscribeExit = ShellScriptRunner.run(TENANT_ENV, SUBSCRIBE_SCRIPT); + } + assertEquals(0, subscribeExit, "Subscription should succeed"); + + // Allow time for async repo onboarding + Thread.sleep(15_000); + + // Verify: repo should now exist + System.out.println(" Verifying repo was onboarded..."); + ShellScriptRunner.Result verifyResult = repoCheck(SUBSCRIPTION_REPO_EXTERNAL_ID); + assertEquals( + 0, + verifyResult.getExitCode(), + "Repository '" + SUBSCRIPTION_REPO_EXTERNAL_ID + "' should exist after subscription"); + assertTrue( + verifyResult.containsIgnoreCase("FOUND"), "Check output should confirm repo was found"); + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CfEnvHelper.java b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CfEnvHelper.java new file mode 100644 index 000000000..f8e293e45 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CfEnvHelper.java @@ -0,0 +1,34 @@ +package integration.com.sap.cds.sdm.utils; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Helper for Cloud Foundry environment variable operations. Delegates to cf-update-env.sh via + * ShellScriptRunner, following the same pattern as CmisDocumentHelper. + */ +public class CfEnvHelper { + + private static final String UPDATE_ENV_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh"; + + public static void updateEnv(String key, String value) { + updateEnv(null, key, value); + } + + public static void updateEnv(String app, String key, String value) { + try { + int exitCode; + if (app != null) { + exitCode = + ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--app", app, "--key", key, "--value", value); + } else { + exitCode = ShellScriptRunner.run(UPDATE_ENV_SCRIPT, "--key", key, "--value", value); + } + if (exitCode != 0) { + fail("cf-update-env.sh exited with non-zero code: " + exitCode); + } + } catch (Exception e) { + fail("Failed to update CF environment variable '" + key + "': " + e.getMessage()); + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CmisDocumentHelper.java b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CmisDocumentHelper.java new file mode 100644 index 000000000..02f85eeee --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/CmisDocumentHelper.java @@ -0,0 +1,205 @@ +package integration.com.sap.cds.sdm.utils; + +import static org.junit.jupiter.api.Assertions.fail; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import integration.com.sap.cds.sdm.Credentials; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +public class CmisDocumentHelper { + + private static final String CREATE_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/create.sh"; + private static final String GET_OBJECT_ID_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/get-object-id.sh"; + private static final String DELETE_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/delete.sh"; + private static final String READ_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/read.sh"; + private static final String GET_METADATA_SCRIPT = + "src/test/java/integration/com/sap/cds/sdm/utils/get-metadata.sh"; + + private static Map getCmisEnv() { + String tenancyModel = System.getProperty("tenancyModel"); + if ("multi".equals(tenancyModel)) { + Properties props = Credentials.getCredentials(); + String repoId = props.getProperty("defaultRepositoryIDMT"); + String tenant = System.getProperty("tenant"); + String suffix = "TENANT1".equals(tenant) ? "1" : "2"; + String authUrl = props.getProperty("authUrlMT" + suffix); + Map env = new HashMap<>(); + if (repoId != null && !repoId.isEmpty()) { + env.put("SDM_REPOSITORY_ID", repoId); + } + if (authUrl != null && !authUrl.isEmpty()) { + env.put("SDM_AUTH_URL", authUrl); + } + return env.isEmpty() ? null : env; + } + return null; + } + + /** + * Resolves the CMIS parent folder ID from {@code entityId + "__attachments"}, then uploads a + * local file to that folder via create.sh. + * + * @param cmisName the name the document will have in the CMIS repository + * @param filePath path to the local file to upload + * @param entityId the entity ID whose attachments folder is the upload target + */ + public static void createDocumentInCmis(String cmisName, String filePath, String entityId) { + try { + Map env = getCmisEnv(); + String folderLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, entityId + "__attachments"); + String parentFolderObjectId = + folderLine != null && folderLine.contains(": ") + ? folderLine.substring(folderLine.lastIndexOf(": ") + 2).trim() + : folderLine; + + int exitCode = + ShellScriptRunner.run(env, CREATE_SCRIPT, cmisName, filePath, parentFolderObjectId); + if (exitCode != 0) { + fail("create.sh exited with non-zero code: " + exitCode); + } + } catch (Exception e) { + fail("Failed to create document in CMIS: " + e.getMessage()); + } + } + + /** + * Resolves the CMIS object ID of a document by name inside the folder named {@code entityId + + * "__attachments"}, then deletes it via the delete.sh script. + * + * @param entityId the entity ID whose attachments folder is the parent + * @param fileName the cmis:name of the document to delete + */ + public static void deleteDocumentFromCmis(String entityId, String fileName) { + try { + Map env = getCmisEnv(); + String folderLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, entityId + "__attachments"); + String parentFolderObjectId = + folderLine != null && folderLine.contains(": ") + ? folderLine.substring(folderLine.lastIndexOf(": ") + 2).trim() + : folderLine; + + String docLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, fileName, parentFolderObjectId, "cmis:document"); + String documentObjectId = + docLine != null && docLine.contains(": ") + ? docLine.substring(docLine.lastIndexOf(": ") + 2).trim() + : docLine; + + int deleteExitCode = + ShellScriptRunner.run(env, DELETE_SCRIPT, documentObjectId, parentFolderObjectId); + if (deleteExitCode != 0) { + fail("delete.sh failed with exit code: " + deleteExitCode); + } + } catch (Exception e) { + fail("Failed to delete document from CMIS: " + e.getMessage()); + } + } + + /** + * Reads (downloads) a CMIS document by resolving its object ID from the entity's attachments + * folder, then downloads it to the specified output path via read.sh. + * + * @param entityId the entity ID whose attachments folder contains the document + * @param fileName the cmis:name of the document to read + * @param outputPath local path to save the downloaded content + */ + public static void readDocumentFromCmis(String entityId, String fileName, String outputPath) { + try { + Map env = getCmisEnv(); + String folderLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, entityId + "__attachments"); + String parentFolderObjectId = + folderLine != null && folderLine.contains(": ") + ? folderLine.substring(folderLine.lastIndexOf(": ") + 2).trim() + : folderLine; + + String docLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, fileName, parentFolderObjectId, "cmis:document"); + String documentObjectId = + docLine != null && docLine.contains(": ") + ? docLine.substring(docLine.lastIndexOf(": ") + 2).trim() + : docLine; + + int exitCode = ShellScriptRunner.run(env, READ_SCRIPT, documentObjectId, outputPath); + if (exitCode != 0) { + fail("read.sh exited with non-zero code: " + exitCode); + } + } catch (Exception e) { + fail("Failed to read document from CMIS: " + e.getMessage()); + } + } + + /** + * Reads CMIS metadata (properties) for a document by resolving its object ID from the entity's + * attachments folder, then fetching its properties via get-metadata.sh. + * + * @param entityId the entity ID whose attachments folder contains the document + * @param fileName the cmis:name of the document to get metadata for + * @return the JSON metadata string returned by the CMIS API + */ + public static String readDocumentMetadataFromCmis(String entityId, String fileName) { + try { + Map env = getCmisEnv(); + String folderName = entityId + "__attachments"; + String folderLine = + ShellScriptRunner.runAndCaptureOutput(env, GET_OBJECT_ID_SCRIPT, folderName); + String parentFolderObjectId = + folderLine != null && folderLine.contains(": ") + ? folderLine.substring(folderLine.lastIndexOf(": ") + 2).trim() + : folderLine; + + String docLine = + ShellScriptRunner.runAndCaptureOutput( + env, GET_OBJECT_ID_SCRIPT, fileName, parentFolderObjectId, "cmis:document"); + String documentObjectId = + docLine != null && docLine.contains(": ") + ? docLine.substring(docLine.lastIndexOf(": ") + 2).trim() + : docLine; + + String metadata = + ShellScriptRunner.runAndCaptureOutput(env, GET_METADATA_SCRIPT, documentObjectId); + return metadata; + } catch (Exception e) { + fail("Failed to read document metadata from CMIS: " + e.getMessage()); + return null; + } + } + + /** + * Retrieves the value of a specific CMIS property for a document. + * + * @param entityId the entity ID whose attachments folder contains the document + * @param fileName the cmis:name of the document + * @param propertyName the CMIS property name (e.g. "cmis:createdBy") + * @return the property value as a String, or null if the property is not found + */ + public static String getCmisProperty(String entityId, String fileName, String propertyName) { + try { + String metadata = readDocumentMetadataFromCmis(entityId, fileName); + JsonNode root = new ObjectMapper().readTree(metadata); + JsonNode valueNode = root.path("properties").path(propertyName).path("value"); + if (valueNode.isMissingNode()) { + fail("CMIS property '" + propertyName + "' not found in metadata"); + return null; + } + return valueNode.asText(); + } catch (Exception e) { + fail("Failed to get CMIS property '" + propertyName + "': " + e.getMessage()); + return null; + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/README.md b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/README.md new file mode 100644 index 000000000..f97f397ff --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/README.md @@ -0,0 +1,290 @@ +# Helper Scripts & Utilities + +This folder contains shell scripts and Java helper classes for managing SAP Document Management Service (SDM/CMIS) objects and Cloud Foundry / BTP subscription lifecycle tasks. + +All scripts read their configuration from [`cf-config.env`](cf-config.env) located in the **same directory** as the scripts. Copy [`cf-config.env.example`](cf-config.env.example) to `cf-config.env` and fill in your values before running any script. + +--- + +## Configuration file + +### `cf-config.env` + +Central configuration file sourced by every script. See [`cf-config.env.example`](cf-config.env.example) for a full annotated template. + +| Section | Variables | +|---|---| +| Cloud Foundry (provider) | `CF_API_ENDPOINT`, `CF_ORG`, `CF_SPACE`, `CF_USERNAME`, `CF_PASSWORD`, `APP_NAME` | +| CF env-var update | `VAR_NAME`, `VAR_VALUE` | +| Consumer account | `CONSUMER_CF_API_ENDPOINT`, `CONSUMER_CF_ORG`, `CONSUMER_CF_SPACE`, `CONSUMER_CF_USERNAME`, `CONSUMER_CF_PASSWORD` | +| BTP subscription | `CONSUMER_SUBACCOUNT_ID`, `SAAS_APP_NAME`, `SAAS_APP_PLAN`, `ROLE_ASSIGNMENT_EMAILS`, `ROLE_COLLECTION_NAME`, `APP_ROLE_FILTER` | +| BTP CLI | `BTP_CLI_URL`, `BTP_GLOBAL_ACCOUNT_SUBDOMAIN` | +| CMIS / SDM | `CMIS_URL`, `CMIS_REPOSITORY_ID`, `CMIS_TOKEN_URL`, `CMIS_CLIENT_ID`, `CMIS_CLIENT_SECRET`, `CMIS_USERNAME`, `CMIS_PASSWORD`, `CMIS_FOLDER_ID` | + +--- + +## Scripts + +### `create.sh` — Upload a document to SDM + +**Function** +Uploads a local file to the SAP Document Management Service repository via the CMIS Browser Binding API. An OAuth2 access token is obtained automatically using the password grant before the upload. + +**Required config (`cf-config.env`)** +`CMIS_URL`, `CMIS_REPOSITORY_ID`, `CMIS_TOKEN_URL`, `CMIS_CLIENT_ID`, `CMIS_CLIENT_SECRET`, `CMIS_USERNAME`, `CMIS_PASSWORD` + +**Optional config** +`CMIS_FOLDER_ID` — fallback target folder object ID; overridden by the `parentFolderID` argument if supplied. If neither is provided the file is uploaded to the repository root. + +**Parameters** + +| # | Name | Default | Description | +|---|---|---|---| +| 1 | `cmisName` | — | Name the document will have inside the CMIS repository | +| 2 | `file` | — | Path to the local file to upload | +| 3 | `parentFolderID` | _(CMIS_FOLDER_ID or root)_ | CMIS object ID of the parent folder to upload into. Takes precedence over `CMIS_FOLDER_ID` from `cf-config.env`. | + +**Shell usage** +```bash +cd helper-scripts + +# Upload to the repository root (or CMIS_FOLDER_ID from cf-config.env) +./create.sh "my-document.pdf" "/path/to/my-document.pdf" + +# Upload into a specific parent folder +./create.sh "my-document.pdf" "/path/to/my-document.pdf" "" +``` + +**Usage in integration tests** +Called via `CmisDocumentHelper.createDocumentInCmis(cmisName, filePath, entityId)` inside `testUploadSingleAttachmentPDF` (Order 3). The helper automatically resolves the parent folder object ID from `entityId + "__attachments"` before calling this script: +```java +// Upload README.md into the attachments folder of the entity +CmisDocumentHelper.createDocumentInCmis("README.md", "../README.md", entityID); +``` + +--- + +### `get-object-id.sh` — Resolve a CMIS object ID by name + +**Function** +Queries the SDM repository using a CMIS SQL statement to find the `cmis:objectId` of an object (folder or document) by its `cmis:name`. The resolved ID is printed to stdout on the last line, making it easy to capture programmatically. + +**Required config (`cf-config.env`)** +`CMIS_URL`, `CMIS_REPOSITORY_ID`, `CMIS_TOKEN_URL`, `CMIS_CLIENT_ID`, `CMIS_CLIENT_SECRET`, `CMIS_USERNAME`, `CMIS_PASSWORD` + +**Parameters** + +| # | Name | Default | Description | +|---|---|---|---| +| 1 | `cmisName` | — | `cmis:name` of the object to look up | +| 2 | `folderID` | _(repository root)_ | CMIS object ID of the parent folder to search within | +| 3 | `cmisType` | `cmis:folder` | CMIS type to query — use `cmis:document` to find uploaded files | + +**Shell usage** +```bash +# Find a folder by name anywhere in the repository +./get-object-id.sh "entityId__attachments" + +# Find a document inside a specific folder +./get-object-id.sh "sample.pdf" "" "cmis:document" +``` + +**Usage in integration tests** +Called internally by `CmisDocumentHelper` (both `createDocumentInCmis` and `deleteDocumentFromCmis`) to resolve folder and document object IDs before upload or deletion. Not called directly from the test class. + +--- + +### `delete.sh` — Delete a document from SDM + +**Function** +Sends a CMIS `delete` action to remove a document from the repository by its object ID. An OAuth2 access token is obtained automatically before the request. + +**Required config (`cf-config.env`)** +`CMIS_URL`, `CMIS_REPOSITORY_ID`, `CMIS_TOKEN_URL`, `CMIS_CLIENT_ID`, `CMIS_CLIENT_SECRET`, `CMIS_USERNAME`, `CMIS_PASSWORD` + +**Parameters** + +| # | Name | Default | Description | +|---|---|---|---| +| 1 | `objectID` | — | CMIS object ID of the document to delete | +| 2 | `parentFolderID` | _(optional)_ | CMIS object ID of the parent folder (used for logging; does not change the delete target) | + +**Shell usage** +```bash +./delete.sh "" +./delete.sh "" "" +``` + +**Usage in integration tests** +Called via `CmisDocumentHelper.deleteDocumentFromCmis(entityId, fileName)` inside `testUploadSingleAttachmentPDF` (Order 3) after the PDF upload has been verified. The helper resolves folder and document object IDs automatically: +```java +// Delete sample.pdf from the attachments folder of the entity +CmisDocumentHelper.deleteDocumentFromCmis(entityID, file.getName()); +``` + +--- + +### `cf-subscribe.sh` — Subscribe a BTP consumer subaccount to a SaaS app + +**Function** +Uses the BTP CLI to subscribe a consumer subaccount to a SaaS application and then assigns all app role collections to the configured email addresses. + +**Required config (`cf-config.env`)** +`CONSUMER_CF_USERNAME` (or `CF_USERNAME`), `CONSUMER_SUBACCOUNT_ID`, `SAAS_APP_NAME` + +**Optional config** +`SAAS_APP_PLAN`, `ROLE_ASSIGNMENT_EMAILS`, `ROLE_COLLECTION_NAME`, `APP_ROLE_FILTER`, `BTP_CLI_URL`, `BTP_GLOBAL_ACCOUNT_SUBDOMAIN` + +**Shell usage** +```bash +cd helper-scripts +./cf-subscribe.sh +``` + +**No direct usage in integration tests.** Run manually before a test suite to set up a consumer subscription. + +--- + +### `cf-unsubscribe.sh` — Unsubscribe a BTP consumer subaccount + +**Function** +Uses the BTP CLI to remove a SaaS subscription from a consumer subaccount. + +**Required config (`cf-config.env`)** +`CONSUMER_CF_USERNAME` (or `CF_USERNAME`), `CONSUMER_SUBACCOUNT_ID`, `SAAS_APP_NAME` + +**Shell usage** +```bash +cd helper-scripts +./cf-unsubscribe.sh +``` + +**No direct usage in integration tests.** Run manually to tear down a consumer subscription after testing. + +--- + +### `cf-update-env.sh` — Update a Cloud Foundry app environment variable + +**Function** +Logs in to Cloud Foundry and sets a user-provided environment variable on a CF application, then restages the app so the change takes effect. + +**Required config (`cf-config.env`)** +`CF_API_ENDPOINT`, `CF_ORG`, `CF_SPACE`, `CF_USERNAME`, `APP_NAME`, `VAR_NAME`, `VAR_VALUE` + +**Optional config** +`CF_PASSWORD` — if left empty you will be prompted at runtime. + +**Shell usage** +```bash +cd helper-scripts +./cf-update-env.sh +``` + +**Usage in integration tests** +Called via `CfEnvHelper.updateEnv(key, value)`. Not used by any currently active test but available for tests that need to toggle app configuration (e.g. switching a repository ID) between test runs: +```java +CfEnvHelper.updateEnv("REPOSITORY_ID", ""); +``` + +--- + +## Java Helper Classes + +The scripts are not called directly from test methods. Instead, three Java utility classes provide a clean interface: + +### `ShellScriptRunner` + +Low-level runner that executes a shell script in a subprocess and streams its output. + +| Method | Returns | Description | +|---|---|---| +| `ShellScriptRunner.run(scriptPath, args...)` | `int` exit code | Runs a script; streams stdout with `[script]` prefix and stderr with `[script-err]` prefix | +| `ShellScriptRunner.runAndCaptureOutput(scriptPath, args...)` | `String` last stdout line | Runs a script and returns the last non-empty stdout line; useful for scripts that print a single result value | + +Script paths are relative to the Maven working directory (project root), e.g.: +``` +src/test/java/integration/com/sap/cds/sdm/utils/create.sh +``` + +--- + +### `CmisDocumentHelper` + +High-level helper for CMIS document operations. Wraps `ShellScriptRunner` and resolves object IDs automatically. + +| Method | Description | +|---|---| +| `createDocumentInCmis(cmisName, filePath, entityId)` | Resolves the `entityId__attachments` folder ID, then uploads the file via `create.sh` | +| `deleteDocumentFromCmis(entityId, fileName)` | Resolves the folder ID and the document object ID, then deletes the document via `delete.sh` | + +**Usage in integration tests** + +```java +// Order 3 — after verifying a successful PDF upload and save: +CmisDocumentHelper.createDocumentInCmis("README.md", "../README.md", entityID); +CmisDocumentHelper.deleteDocumentFromCmis(entityID, file.getName()); +``` + +--- + +### `CfEnvHelper` + +Helper for updating CF app environment variables. Wraps `cf-update-env.sh` via `ShellScriptRunner`. + +| Method | Description | +|---|---| +| `updateEnv(key, value)` | Sets `key=value` on the CF app and restages it | + +```java +CfEnvHelper.updateEnv("REPOSITORY_ID", ""); +``` + +--- + +## Active test cases & script/helper usage + +| Order | Test method | Script / helper invoked | +|---|---|---| +| 1 | `testCreateEntityAndCheck` | — | +| 2 | `testUpdateEmptyEntity` | — | +| 3 | `testUploadSingleAttachmentPDF` | `CmisDocumentHelper.createDocumentInCmis` → `create.sh` (via `get-object-id.sh`) then `CmisDocumentHelper.deleteDocumentFromCmis` → `delete.sh` (via `get-object-id.sh`) | +| 4 | `testUploadVirusFileInScannedRepo` | — | + +### Test 3 — `testUploadSingleAttachmentPDF` + +Uploads `sample.pdf`, verifies it in draft mode, saves the entity, then verifies the active attachment. On success it also uploads `README.md` to the CMIS repository (as a secondary CMIS-direct test) and immediately deletes `sample.pdf` from CMIS to clean up: + +```java +if (response.equals("OK")) { + testStatus = true; + CmisDocumentHelper.createDocumentInCmis("README.md", "../README.md", entityID); + CmisDocumentHelper.deleteDocumentFromCmis(entityID, file.getName()); +} +``` + +### Test 4 — `testUploadVirusFileInScannedRepo` + +Uploads the EICAR test file (path supplied via the `eicar.file.path` system property, defaulting to `eicar.com.txt`) and expects it to be **uploaded successfully** — this validates a repository where virus scanning is disabled or configured to allow the file through. The test follows the same verification pattern as Test 3: + +1. Edit entity draft +2. Create attachment (EICAR file, `text/plain`) +3. Read attachment in draft mode (`readAttachmentDraft`) — must return `"OK"` +4. Save entity draft +5. Read attachment as active entity (`readAttachment`) — must return `"OK"` + +The attachment ID is stored in `attachmentID2` for potential use by subsequent tests. + +--- + +## Typical test workflow + +``` +1. Fill in cf-config.env (copy from cf-config.env.example) +2. (Multi-tenant only) Run cf-subscribe.sh to set up the consumer subscription +3. Place the EICAR test file at the path configured via -Deicar.file.path (or eicar.com.txt) +4. Run the integration tests — scripts are invoked automatically: + Order 3 → CmisDocumentHelper.createDocumentInCmis (create.sh + get-object-id.sh) + → CmisDocumentHelper.deleteDocumentFromCmis (delete.sh + get-object-id.sh) +5. (Multi-tenant only) Run cf-unsubscribe.sh to tear down after testing +``` + diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/ShellScriptRunner.java b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/ShellScriptRunner.java new file mode 100644 index 000000000..178bfa508 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/ShellScriptRunner.java @@ -0,0 +1,251 @@ +package integration.com.sap.cds.sdm.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + +public class ShellScriptRunner { + + /** + * Runs a shell script and returns its exit code. stdout and stderr are printed to System.out / + * System.err. + * + * @param scriptPath absolute or relative path to the .sh file + * @param args additional arguments forwarded to the script + * @return exit code of the process (0 = success) + */ + public static int run(String scriptPath, String... args) + throws IOException, InterruptedException { + return run(null, scriptPath, args); + } + + public static int run(Map env, String scriptPath, String... args) + throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add("bash"); + command.add(scriptPath); + Collections.addAll(command, args); + + ProcessBuilder pb = new ProcessBuilder(command); + if (env != null) { + pb.environment().putAll(env); + } + pb.redirectErrorStream(false); + Process process = pb.start(); + + // Drain stdout (suppress console output) + Thread stdoutThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getInputStream()))) { + while (reader.readLine() != null) { + // discard + } + } catch (IOException e) { + // ignore + } + }); + + // Drain stderr (suppress console output) + Thread stderrThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + while (reader.readLine() != null) { + // discard + } + } catch (IOException e) { + // ignore + } + }); + + stdoutThread.start(); + stderrThread.start(); + int exitCode = process.waitFor(); + stdoutThread.join(); + stderrThread.join(); + return exitCode; + } + + /** + * Runs a shell script, streams stderr to System.err, and returns the last non-empty line of + * stdout. Useful for scripts that print a single result value as their final output line. + * + * @param scriptPath absolute or relative path to the .sh file + * @param args additional arguments forwarded to the script + * @return the last non-empty stdout line, or null if stdout was empty + */ + public static String runAndCaptureOutput(String scriptPath, String... args) + throws IOException, InterruptedException { + return runAndCaptureOutput(null, scriptPath, args); + } + + public static String runAndCaptureOutput( + Map env, String scriptPath, String... args) + throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add("bash"); + command.add(scriptPath); + Collections.addAll(command, args); + + ProcessBuilder pb = new ProcessBuilder(command); + if (env != null) { + pb.environment().putAll(env); + } + pb.redirectErrorStream(false); + Process process = pb.start(); + + final List stdoutLines = new CopyOnWriteArrayList<>(); + final List stderrLines = new CopyOnWriteArrayList<>(); + + Thread stdoutThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + if (!line.trim().isEmpty()) stdoutLines.add(line.trim()); + } + } catch (IOException e) { + // ignore + } + }); + + Thread stderrThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + String line; + while ((line = reader.readLine()) != null) { + if (!line.trim().isEmpty()) stderrLines.add(line.trim()); + } + } catch (IOException e) { + // ignore + } + }); + + stdoutThread.start(); + stderrThread.start(); + int exitCode = process.waitFor(); + stdoutThread.join(); + stderrThread.join(); + + if (exitCode != 0) { + String output = String.join("\n", stdoutLines); + String errors = String.join("\n", stderrLines); + throw new RuntimeException( + scriptPath + + " exited with code " + + exitCode + + "\nOutput: " + + output + + "\nStderr: " + + errors); + } + return stdoutLines.isEmpty() ? null : stdoutLines.get(stdoutLines.size() - 1); + } + + /** + * Runs a shell script and returns all stdout lines as a list. Does NOT throw on non-zero exit + * code — the caller is responsible for checking the exit code via the returned result. + * + * @param scriptPath absolute or relative path to the .sh file + * @param args additional arguments forwarded to the script + * @return a Result containing the exit code and all stdout lines + */ + public static Result runAndCaptureAll(String scriptPath, String... args) + throws IOException, InterruptedException { + return runAndCaptureAll(null, scriptPath, args); + } + + public static Result runAndCaptureAll(Map env, String scriptPath, String... args) + throws IOException, InterruptedException { + List command = new ArrayList<>(); + command.add("bash"); + command.add(scriptPath); + Collections.addAll(command, args); + + ProcessBuilder pb = new ProcessBuilder(command); + if (env != null) { + pb.environment().putAll(env); + } + pb.redirectErrorStream(false); + Process process = pb.start(); + + final List stdoutLines = new CopyOnWriteArrayList<>(); + + Thread stdoutThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + stdoutLines.add(line); + } + } catch (IOException e) { + // ignore + } + }); + + Thread stderrThread = + new Thread( + () -> { + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getErrorStream()))) { + while (reader.readLine() != null) { + // discard + } + } catch (IOException e) { + // ignore + } + }); + + stdoutThread.start(); + stderrThread.start(); + int exitCode = process.waitFor(); + stdoutThread.join(); + stderrThread.join(); + + return new Result(exitCode, stdoutLines); + } + + /** Holds the exit code and captured stdout lines from a script execution. */ + public static class Result { + private final int exitCode; + private final List lines; + + public Result(int exitCode, List lines) { + this.exitCode = exitCode; + this.lines = lines; + } + + public int getExitCode() { + return exitCode; + } + + public List getLines() { + return lines; + } + + /** Returns all stdout lines joined with newline. */ + public String getOutput() { + return String.join("\n", lines); + } + + /** Check if any line contains the given substring (case-insensitive). */ + public boolean containsIgnoreCase(String substring) { + String lower = substring.toLowerCase(); + return lines.stream().anyMatch(l -> l.toLowerCase().contains(lower)); + } + } +} diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-logs.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-logs.sh new file mode 100755 index 000000000..27f2ebb40 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-logs.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# cf-logs.sh — Fetch recent CF app logs and print them to stdout. +# +# Usage: ./cf-logs.sh [--app ] +# +# If --app is not provided, defaults to demoappjava-srv. +# Prints the recent logs to stdout for parsing by the calling test. +# --------------------------------------------------------------------------- + +# Default +APP_NAME="demoappjava-srv" + +# Parse optional --app argument +while [[ $# -gt 0 ]]; do + case "$1" in + --app) APP_NAME="$2"; shift 2 ;; + *) echo "Unknown argument: $1"; exit 1 ;; + esac +done + +# Validate +if [[ -z "${APP_NAME:-}" ]]; then + echo "ERROR: APP_NAME is not set" + exit 1 +fi + +# Assumes CF CLI is already logged in before running tests. +# To login manually: cf login -a -u -p -o -s + +# Fetch recent logs +cf logs "$APP_NAME" --recent diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-subscribe.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-subscribe.sh new file mode 100755 index 000000000..7454d1a79 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-subscribe.sh @@ -0,0 +1,225 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +# --- Load config --- +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found" + exit 1 +fi + +load_props "$CONFIG_FILE" + +# --- Resolve tenant-specific subaccount via ACTIVE_TENANT env var (1 or 2) --- +TENANT_SUFFIX="${ACTIVE_TENANT:-1}" +SUBACCOUNT_VAR="consumerSubaccountIdMT${TENANT_SUFFIX}" +consumerSubaccountIdMT="${!SUBACCOUNT_VAR}" + +# --- Resolve consumer credentials --- +CONSUMER_USER="${username}" +CONSUMER_PASS="${password}" +BTP_URL="${BTP_CLI_URL:-https://cli.btp.cloud.sap}" + +# --- Validate required variables --- +for var in CONSUMER_USER consumerSubaccountIdMT SAAS_APP_NAME; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: Required variable $var is not set in config" + exit 1 + fi +done + +echo "=== BTP Subaccount SaaS Subscription ===" +echo "==========================================" + +# --- BTP Login --- +echo "" +echo "Logging in to SAP BTP..." +LOGIN_ARGS=(--url "$BTP_URL" --user "$CONSUMER_USER") +if [[ -n "${CONSUMER_PASS:-}" ]]; then + LOGIN_ARGS+=(--password "$CONSUMER_PASS") +fi +if [[ -n "${BTP_GLOBAL_ACCOUNT_SUBDOMAIN:-}" ]]; then + LOGIN_ARGS+=(--subdomain "$BTP_GLOBAL_ACCOUNT_SUBDOMAIN") +fi +btp logout > /dev/null 2>&1 || true +btp login "${LOGIN_ARGS[@]}" > /dev/null 2>&1 + +# --- Check current subscription status --- +GET_ARGS=(--subaccount "$consumerSubaccountIdMT" --of-app "$SAAS_APP_NAME") +if [[ -n "${SAAS_APP_PLAN:-}" ]]; then + GET_ARGS+=(--plan "$SAAS_APP_PLAN") +fi + +# Use list to find the exact app row and check its state +# Use -w (whole word) so "NOT_SUBSCRIBED" does NOT match "SUBSCRIBED" +CURRENT_STATE=$(btp list accounts/subscription --subaccount "$consumerSubaccountIdMT" 2>/dev/null \ + | grep -F "$SAAS_APP_NAME" | grep -ow "SUBSCRIBED" | head -1 || true) + +if [[ "$CURRENT_STATE" == "SUBSCRIBED" ]]; then + echo "" + echo "Already subscribed to '$SAAS_APP_NAME' — skipping subscription step." +else + # --- Wait for any transitional state to settle before subscribing --- + echo "" + echo "Checking subscription state before subscribing..." + SKIP_SUBSCRIBE=false + for ((wait_attempt=1; wait_attempt<=30; wait_attempt++)); do + RAW_STATE=$(btp get accounts/subscription "${GET_ARGS[@]}" 2>/dev/null | grep -i "status:" | awk '{print $2}' || true) + if [[ -z "$RAW_STATE" ]] || echo "$RAW_STATE" | grep -qi "NOT_SUBSCRIBED"; then + echo "Subscription is in stable state — proceeding." + break + elif echo "$RAW_STATE" | grep -qi "SUBSCRIBED" && ! echo "$RAW_STATE" | grep -qi "NOT_SUBSCRIBED"; then + echo "Already subscribed (detected via get) — skipping subscription step." + SKIP_SUBSCRIBE=true + break + elif echo "$RAW_STATE" | grep -qi "FAILED"; then + echo "Previous operation failed (${RAW_STATE}) — proceeding with subscribe." + break + else + echo " State: ${RAW_STATE} — waiting 10s for stable state (attempt $wait_attempt/30)..." + sleep 10 + fi + done + + if [[ "$SKIP_SUBSCRIBE" == "true" ]]; then + echo "" + echo "Done." + exit 0 + fi + + # --- Subscribe to SaaS application at subaccount level --- + echo "" + echo "Subscribing to SaaS application..." + SUBSCRIBE_ARGS=(--subaccount "$consumerSubaccountIdMT" --to-app "$SAAS_APP_NAME") + if [[ -n "${SAAS_APP_PLAN:-}" ]]; then + SUBSCRIBE_ARGS+=(--plan "$SAAS_APP_PLAN") + fi + btp subscribe accounts/subaccount "${SUBSCRIBE_ARGS[@]}" > /dev/null 2>&1 + + # --- Wait for subscription to complete --- + echo "" + echo "Waiting for subscription to be ready..." + while true; do + STATE=$(btp get accounts/subscription "${GET_ARGS[@]}" 2>/dev/null | grep -i "status:" | awk '{print $2}' || true) + if echo "$STATE" | grep -qi "SUBSCRIBED"; then + echo "Subscription is active." + break + elif echo "$STATE" | grep -qi "SUBSCRIBE_FAILED"; then + echo "ERROR: Subscription failed." + exit 1 + else + echo " State: ${STATE:-pending} — waiting 10s..." + sleep 10 + fi + done +fi + +echo "" +echo "Done." + +# --- Add roles to role collection after subscription --- + +IFS=',' read -ra _colls_raw <<< "${ROLE_COLLECTION_NAME:-}" + +COLLECTIONS_ARRAY=() +for _c in ${_colls_raw[@]+"${_colls_raw[@]}"}; do + _c="${_c#"${_c%%[![:space:]]*}"}"; _c="${_c%"${_c##*[![:space:]]}"}" + [[ -n "$_c" ]] && COLLECTIONS_ARRAY+=("$_c") +done + +if [[ ${#COLLECTIONS_ARRAY[@]} -eq 0 ]]; then + echo "" + echo "No ROLE_COLLECTION_NAME configured — skipping role setup." + exit 0 +fi + +ROLE_FILTER="${APP_ROLE_FILTER:-$SAAS_APP_NAME}" + +echo "" +echo "=== Role Collection Setup ===" +echo "Fetching roles for app filter: '$ROLE_FILTER'..." + +# After a fresh subscription, role templates can take time to be provisioned. +MATCHED_ROLES="" +ROLES_RAW="" +MAX_RETRIES=6 +RETRY_INTERVAL=30 +for ((attempt=1; attempt<=MAX_RETRIES; attempt++)); do + ROLES_RAW=$(btp list security/role --subaccount "$consumerSubaccountIdMT" 2>&1) || true + + if echo "$ROLES_RAW" | grep -qi "^error\|FAILED"; then + echo "ERROR: Could not fetch roles from subaccount." + exit 1 + fi + + MATCHED_ROLES=$(echo "$ROLES_RAW" \ + | grep -i "$ROLE_FILTER" \ + | awk '{print $1 "|" $3 "|" $2}' \ + || true) + + if [[ -n "$MATCHED_ROLES" ]]; then + break + fi + + if [[ $attempt -lt $MAX_RETRIES ]]; then + echo " Roles for '$ROLE_FILTER' not yet provisioned (attempt $attempt/$MAX_RETRIES) — waiting ${RETRY_INTERVAL}s..." + sleep "$RETRY_INTERVAL" + fi +done + +if [[ -z "$MATCHED_ROLES" ]]; then + echo "WARNING: No matching roles found after $MAX_RETRIES attempts." + exit 0 +fi + +ROLE_COUNT=$(echo "$MATCHED_ROLES" | wc -l | tr -d ' ') +echo "Found $ROLE_COUNT role(s) to add." + +for COLLECTION_NAME in "${COLLECTIONS_ARRAY[@]}"; do + echo "" + echo "--- Adding roles to collection: '$COLLECTION_NAME' ---" + + # Create the role collection if it doesn't already exist + COLLECTION_EXISTS=$(btp list security/role-collection --subaccount "$consumerSubaccountIdMT" 2>/dev/null \ + | awk -v name="$COLLECTION_NAME" '$1 == name {found=1} END {print found+0}' || echo 0) + if [[ "$COLLECTION_EXISTS" != "1" ]]; then + echo "Creating role collection '$COLLECTION_NAME'..." + btp create security/role-collection "$COLLECTION_NAME" \ + --subaccount "$consumerSubaccountIdMT" \ + --description "Auto-created role collection for $SAAS_APP_NAME" \ + > /dev/null 2>&1 \ + && echo "Role collection created." \ + || echo "WARNING: Could not create role collection — continuing." + fi + + # Add each role to the collection + while IFS='|' read -r RNAME RTEMPLATE RAPPID; do + [[ -z "$RNAME" ]] && continue + btp add security/role "$RNAME" \ + --to-role-collection "$COLLECTION_NAME" \ + --subaccount "$consumerSubaccountIdMT" \ + --of-app "$RAPPID" \ + --of-role-template "$RTEMPLATE" \ + > /dev/null 2>&1 \ + && echo " Role '$RNAME' added." \ + || echo " WARNING: Could not add role '$RNAME' (may already exist) — continuing." + done <<< "$MATCHED_ROLES" +done + +echo "" +echo "Role setup complete." diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-unsubscribe.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-unsubscribe.sh new file mode 100755 index 000000000..bb17edc4a --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-unsubscribe.sh @@ -0,0 +1,93 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +# --- Load config --- +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found" + exit 1 +fi + +load_props "$CONFIG_FILE" + +# --- Resolve tenant-specific subaccount via ACTIVE_TENANT env var (1 or 2) --- +TENANT_SUFFIX="${ACTIVE_TENANT:-1}" +SUBACCOUNT_VAR="consumerSubaccountIdMT${TENANT_SUFFIX}" +consumerSubaccountIdMT="${!SUBACCOUNT_VAR}" + +# --- Resolve consumer credentials --- +CONSUMER_USER="${username}" +CONSUMER_PASS="${password}" +BTP_URL="${BTP_CLI_URL:-https://cli.btp.cloud.sap}" + +# --- Validate required variables --- +for var in CONSUMER_USER consumerSubaccountIdMT SAAS_APP_NAME; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: Required variable $var is not set in config" + exit 1 + fi +done + +echo "=== BTP Subaccount SaaS Unsubscription ===" +echo "============================================" + +# --- BTP Login --- +echo "" +echo "Logging in to SAP BTP..." +LOGIN_ARGS=(--url "$BTP_URL" --user "$CONSUMER_USER") +if [[ -n "${CONSUMER_PASS:-}" ]]; then + LOGIN_ARGS+=(--password "$CONSUMER_PASS") +fi +if [[ -n "${BTP_GLOBAL_ACCOUNT_SUBDOMAIN:-}" ]]; then + LOGIN_ARGS+=(--subdomain "$BTP_GLOBAL_ACCOUNT_SUBDOMAIN") +fi +btp logout > /dev/null 2>&1 || true +btp login "${LOGIN_ARGS[@]}" > /dev/null 2>&1 + +# --- Unsubscribe from SaaS application at subaccount level --- +echo "" +echo "Unsubscribing from SaaS application..." +UNSUBSCRIBE_ARGS=(--subaccount "$consumerSubaccountIdMT" --from-app "$SAAS_APP_NAME") +if [[ -n "${SAAS_APP_PLAN:-}" ]]; then + UNSUBSCRIBE_ARGS+=(--plan "$SAAS_APP_PLAN") +fi +btp unsubscribe accounts/subaccount "${UNSUBSCRIBE_ARGS[@]}" --confirm > /dev/null 2>&1 + +# --- Wait for unsubscription to complete --- +echo "" +echo "Waiting for unsubscription to complete..." +while true; do + GET_ARGS=(--subaccount "$consumerSubaccountIdMT" --of-app "$SAAS_APP_NAME") + if [[ -n "${SAAS_APP_PLAN:-}" ]]; then + GET_ARGS+=(--plan "$SAAS_APP_PLAN") + fi + STATE=$(btp get accounts/subscription "${GET_ARGS[@]}" 2>/dev/null | grep -i "status:" | awk '{print $2}' || true) + if [[ -z "$STATE" ]] || echo "$STATE" | grep -qi "NOT_SUBSCRIBED"; then + echo "Successfully unsubscribed." + break + elif echo "$STATE" | grep -qi "UNSUBSCRIBE_FAILED"; then + echo "ERROR: Unsubscription failed." + exit 1 + else + echo " State: ${STATE:-pending} — waiting 10s..." + sleep 10 + fi +done + +echo "" +echo "Done." diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh new file mode 100755 index 000000000..f4f7dce43 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/cf-update-env.sh @@ -0,0 +1,47 @@ +#!/bin/bash +set -euo pipefail + +# Defaults +APP_NAME="demoappjava-srv" +VAR_NAME="REPOSITORY_ID" +CLI_VALUE="" + +# Parse CLI arguments +while [[ $# -gt 0 ]]; do + case "$1" in + --app) APP_NAME="$2"; shift 2 ;; + --key) VAR_NAME="$2"; shift 2 ;; + --value) CLI_VALUE="$2"; shift 2 ;; + *) echo "Unknown argument: $1"; exit 1 ;; + esac +done + +VAR_VALUE="$CLI_VALUE" + +# --- Validate required variables --- +for var in APP_NAME VAR_NAME VAR_VALUE; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set (checked CLI args)" + exit 1 + fi +done + +echo "=== Cloud Foundry Environment Variable Updater ===" +echo "==================================================" + +# Assumes CF CLI is already logged in before running tests. +# To login manually: cf login -a -u -p -o -s + +# --- Update environment variable --- +echo "" +echo "Setting $VAR_NAME=$VAR_VALUE on app $APP_NAME..." +cf set-env "$APP_NAME" "$VAR_NAME" "$VAR_VALUE" > /dev/null 2>&1 + +# --- Restage the app to pick up the change --- +echo "" +echo "Restaging app..." +cf restage "$APP_NAME" > /dev/null 2>&1 +echo "Restage complete." + +echo "" +echo "Done." diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/create.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/create.sh new file mode 100755 index 000000000..345dc495d --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/create.sh @@ -0,0 +1,125 @@ +#!/bin/bash +set -euo pipefail + + +# --------------------------------------------------------------------------- +# create.sh — Upload a file to SAP Document Management Service via CMIS API +## Usage: ./create.sh [parentFolderID] +# +# cmisName The name the document will have inside the CMIS repository +# file Path to the local file to upload +# parentFolderID (Optional) CMIS object ID of the parent folder to upload into. +# If not provided, the file is uploaded to the repository root. +# +# Required config in credentials.properties: +# CMIS_URL, defaultRepositoryID, authUrl, cmisClientID, cmisClientSecret +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 1 +fi +load_props "$CONFIG_FILE" +defaultRepositoryID="${SDM_REPOSITORY_ID:-$defaultRepositoryID}" +authUrl="${SDM_AUTH_URL:-$authUrl}" +CMIS_URL="${CMIS_URL%/}/" + +# --- Validate positional parameters --- +if [[ $# -lt 2 || $# -gt 3 ]]; then + echo "Usage: $0 [parentFolderID]" + exit 1 +fi + +CMIS_NAME="$1" +FILE_PATH="$2" +ARG_FOLDER_ID="${3:-}" +EFFECTIVE_FOLDER_ID="${ARG_FOLDER_ID:-}" + +if [[ ! -f "$FILE_PATH" ]]; then + echo "ERROR: File not found: $FILE_PATH" + exit 1 +fi + +# --- Validate required config variables --- +for var in CMIS_URL defaultRepositoryID authUrl cmisClientID cmisClientSecret username password; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 1 + fi +done + +# --- Obtain OAuth2 access token (password grant) --- +TOKEN_RESPONSE=$(curl -s -X POST "${authUrl}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + +ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + +if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." + echo "Token endpoint response: $TOKEN_RESPONSE" + exit 1 +fi + +# --- Detect MIME type of the local file --- +MIME_TYPE=$(file --mime-type -b "$FILE_PATH") + +# --- Build the CMIS browser endpoint URL --- +if [[ -n "${EFFECTIVE_FOLDER_ID}" ]]; then + CMIS_ENDPOINT="${CMIS_URL}browser/${defaultRepositoryID}/root?objectId=${EFFECTIVE_FOLDER_ID}" +else + CMIS_ENDPOINT="${CMIS_URL}browser/${defaultRepositoryID}/root" +fi + +# --- Assemble curl arguments --- +CURL_ARGS=( + -s -w "\n%{http_code}" + -X POST "$CMIS_ENDPOINT" + -H "Authorization: Bearer $ACCESS_TOKEN" + -F "cmisaction=createDocument" + -F "propertyId[0]=cmis:name" + -F "propertyValue[0]=${CMIS_NAME}" + -F "propertyId[1]=cmis:objectTypeId" + -F "propertyValue[1]=cmis:document" + -F "succinct=true" + -F "filename=@${FILE_PATH};type=${MIME_TYPE}" +) + +RESPONSE=$(curl "${CURL_ARGS[@]}") + +HTTP_CODE=$(echo "$RESPONSE" | tail -n1) +BODY=$(echo "$RESPONSE" | sed '$d') + +if [[ "$HTTP_CODE" == "201" || "$HTTP_CODE" == "200" ]]; then + OBJECT_ID=$(echo "$BODY" \ + | grep -o '"cmis:objectId":"[^"]*"' \ + | head -1 \ + | sed 's/"cmis:objectId":"//;s/"$//') + echo "SUCCESS: Document '${CMIS_NAME}' created." + echo "Object ID: ${OBJECT_ID}" +else + echo "ERROR: Failed to create document (HTTP ${HTTP_CODE})." + echo "$BODY" + exit 1 +fi diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/delete.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/delete.sh new file mode 100755 index 000000000..605ea79bb --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/delete.sh @@ -0,0 +1,107 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# delete.sh — Delete a document from SAP Document Management Service via CMIS API +# +# Usage: ./delete.sh [parentFolderID] +# +# objectID The CMIS object ID of the document to delete +# parentFolderID (Optional) The CMIS object ID of the parent folder. +# If provided, the endpoint is scoped to that folder. +# If omitted, defaults to the repository root. +# +# Required config in cf-config.env: +# CMIS_URL, defaultRepositoryID, authUrl, cmisClientID, cmisClientSecret, +# username, password +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 1 +fi +load_props "$CONFIG_FILE" +defaultRepositoryID="${SDM_REPOSITORY_ID:-$defaultRepositoryID}" +authUrl="${SDM_AUTH_URL:-$authUrl}" +CMIS_URL="${CMIS_URL%/}/" + +# --- Validate positional parameters --- +if [[ $# -lt 1 || $# -gt 2 ]]; then + echo "Usage: $0 [parentFolderID]" + exit 1 +fi + +OBJECT_ID="$1" +PARENT_FOLDER_ID="${2:-}" + +# --- Validate required config variables --- +for var in CMIS_URL defaultRepositoryID authUrl cmisClientID cmisClientSecret username password; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 1 + fi +done + +# --- Obtain OAuth2 access token (password grant) --- +TOKEN_RESPONSE=$(curl -s -X POST "${authUrl}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + +ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + +if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." + echo "Token endpoint response: $TOKEN_RESPONSE" + exit 1 +fi + +# --- Build the CMIS browser endpoint URL --- +# For delete, the target object is always identified by the objectId form field. +# The parentFolderID is logged for context only; it does NOT go in the URL, +# as having ?objectId= in the URL conflicts with the objectId form field. +CMIS_ENDPOINT="${CMIS_URL}browser/${defaultRepositoryID}/root" + +if [[ -n "${PARENT_FOLDER_ID}" ]]; then + echo "Deleting object '${OBJECT_ID}' (parent folder: '${PARENT_FOLDER_ID}')..." +else + echo "Deleting object '${OBJECT_ID}'..." +fi + +RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X POST "$CMIS_ENDPOINT" \ + -H "Authorization: Bearer $ACCESS_TOKEN" \ + -F "cmisaction=delete" \ + -F "objectId=${OBJECT_ID}" \ + -F "allVersions=true") + +HTTP_CODE=$(echo "$RESPONSE" | tail -n1) +BODY=$(echo "$RESPONSE" | sed '$d') + +if [[ "$HTTP_CODE" == "200" || "$HTTP_CODE" == "204" ]]; then + echo "SUCCESS: Object '${OBJECT_ID}' deleted." +else + echo "ERROR: Failed to delete object (HTTP ${HTTP_CODE})." + echo "$BODY" + exit 1 +fi diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-metadata.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-metadata.sh new file mode 100755 index 000000000..ed36fee14 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-metadata.sh @@ -0,0 +1,97 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# get-metadata.sh — Retrieve CMIS metadata (properties) for a document +# +# Usage: ./get-metadata.sh +# +# objectID The CMIS object ID of the document to retrieve metadata for +# +# On success, prints the JSON properties of the object to stdout and exits +# with code 0. On failure, exits with a non-zero code. +# +# Required config in credentials.properties: +# CMIS_URL, defaultRepositoryID, authUrl, +# cmisClientID, cmisClientSecret, username, password +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 1 +fi +load_props "$CONFIG_FILE" +defaultRepositoryID="${SDM_REPOSITORY_ID:-$defaultRepositoryID}" +authUrl="${SDM_AUTH_URL:-$authUrl}" +CMIS_URL="${CMIS_URL%/}/" + +# --- Validate positional parameters --- +if [[ $# -ne 1 ]]; then + echo "Usage: $0 " + exit 1 +fi + +OBJECT_ID="$1" + +# --- Validate required config variables --- +for var in CMIS_URL defaultRepositoryID authUrl cmisClientID cmisClientSecret username password; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 1 + fi +done + +# --- Obtain OAuth2 access token (password grant) --- +TOKEN_RESPONSE=$(curl -s -X POST "${authUrl}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + +ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + +if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." >&2 + echo "Token endpoint response: $TOKEN_RESPONSE" >&2 + exit 1 +fi + +# --- Fetch object properties via CMIS browser binding --- +CMIS_ENDPOINT="${CMIS_URL}browser/${defaultRepositoryID}/root?objectId=${OBJECT_ID}&cmisselector=object" + + +RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X GET "$CMIS_ENDPOINT" \ + -H "Authorization: Bearer $ACCESS_TOKEN") + +HTTP_CODE=$(echo "$RESPONSE" | tail -n1) +BODY=$(echo "$RESPONSE" | sed '$d') + +if [[ "$HTTP_CODE" == "200" ]]; then + echo "SUCCESS: Metadata retrieved for object '${OBJECT_ID}'." >&2 + echo "$BODY" + exit 0 +else + echo "ERROR: Failed to retrieve metadata. HTTP status: $HTTP_CODE" >&2 + echo "$BODY" >&2 + exit 1 +fi diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-object-id.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-object-id.sh new file mode 100755 index 000000000..bc84835f3 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/get-object-id.sh @@ -0,0 +1,121 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# get-object-id.sh — Find the CMIS object ID for an object by name in the SDM repository. +# +# Usage: ./get-object-id.sh [folderID] [cmisType] +# +# cmisName The cmis:name of the object to look up +# folderID (Optional) CMIS object ID of the parent folder to search in. +# If omitted, searches the entire repository. +# cmisType (Optional) CMIS type to query. Defaults to 'cmis:folder'. +# Use 'cmis:document' to find uploaded files. +# +# On success, the resolved CMIS object ID is printed to stdout and the script +# exits with code 0. On failure the script exits with a non-zero code. +# +# Required config in cf-config.env: +# CMIS_URL, defaultRepositoryID, authUrl, +# cmisClientID, cmisClientSecret, username, password +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 1 +fi +load_props "$CONFIG_FILE" +defaultRepositoryID="${SDM_REPOSITORY_ID:-$defaultRepositoryID}" +authUrl="${SDM_AUTH_URL:-$authUrl}" +CMIS_URL="${CMIS_URL%/}/" + +# --- Validate positional parameters --- +if [[ $# -lt 1 || $# -gt 3 ]]; then + echo "Usage: $0 [folderID] [cmisType]" + exit 1 +fi + +CMIS_NAME="$1" +PARENT_FOLDER_ID="${2:-}" +CMIS_TYPE="${3:-cmis:folder}" + +# --- Validate required config variables --- +for var in CMIS_URL defaultRepositoryID authUrl cmisClientID cmisClientSecret username password; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 1 + fi +done + +# --- Obtain OAuth2 access token (password grant) --- +TOKEN_RESPONSE=$(curl -s -X POST "${authUrl}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + +ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + +if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." + echo "Token endpoint response: $TOKEN_RESPONSE" + exit 1 +fi + +# --- Execute CMIS query to find the folder by name --- +QUERY_URL="${CMIS_URL}browser/${defaultRepositoryID}" + +if [[ -n "${PARENT_FOLDER_ID}" ]]; then + CMIS_QUERY="SELECT cmis:objectId FROM ${CMIS_TYPE} WHERE cmis:name = '${CMIS_NAME}' AND IN_FOLDER('${PARENT_FOLDER_ID}')" +else + CMIS_QUERY="SELECT cmis:objectId FROM ${CMIS_TYPE} WHERE cmis:name = '${CMIS_NAME}'" +fi +RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X GET "${QUERY_URL}" \ + -H "Authorization: Bearer ${ACCESS_TOKEN}" \ + -G \ + --data-urlencode "cmisselector=query" \ + --data-urlencode "q=${CMIS_QUERY}") + +HTTP_CODE=$(echo "$RESPONSE" | tail -n1) +BODY=$(echo "$RESPONSE" | sed '$d') + +if [[ "$HTTP_CODE" != "200" ]]; then + echo "ERROR: CMIS query failed (HTTP ${HTTP_CODE})." + echo "$BODY" + exit 1 +fi + +# --- Parse the objectId from the JSON response --- +OBJECT_ID=$(echo "$BODY" \ + | grep -o '"cmis:objectId"[^}]*"value":"[^"]*"' \ + | head -1 \ + | grep -o '"value":"[^"]*"' \ + | sed 's/"value":"//;s/"$//' || true) + +if [[ -z "$OBJECT_ID" ]]; then + echo "ERROR: No ${CMIS_TYPE} found with name '${CMIS_NAME}'." + echo "Query response: $BODY" + exit 1 +fi + +echo "Found object ID for '${CMIS_NAME}': ${OBJECT_ID}" diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/read.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/read.sh new file mode 100755 index 000000000..aa7b7490e --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/read.sh @@ -0,0 +1,117 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# read.sh — Read (download) a document from SAP Document Management Service via CMIS API +# +# Usage: ./read.sh [outputPath] +# +# objectID The CMIS object ID of the document to read/download +# outputPath (Optional) Local path to save the downloaded content. +# If omitted, content is written to stdout. +# +# Required config in credentials.properties: +# CMIS_URL, defaultRepositoryID, authUrl, +# cmisClientID, cmisClientSecret, username, password +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file without shell expansion of values +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 1 +fi +load_props "$CONFIG_FILE" +defaultRepositoryID="${SDM_REPOSITORY_ID:-$defaultRepositoryID}" +authUrl="${SDM_AUTH_URL:-$authUrl}" +CMIS_URL="${CMIS_URL%/}/" + +# --- Validate positional parameters --- +if [[ $# -lt 1 || $# -gt 2 ]]; then + echo "Usage: $0 [outputPath]" + exit 1 +fi + +OBJECT_ID="$1" +OUTPUT_PATH="${2:-}" + +# --- Validate required config variables --- +for var in CMIS_URL defaultRepositoryID authUrl cmisClientID cmisClientSecret username password; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 1 + fi +done + +# --- Obtain OAuth2 access token (password grant) --- +TOKEN_RESPONSE=$(curl -s -X POST "${authUrl}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + +ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + +if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." + echo "Token endpoint response: $TOKEN_RESPONSE" + exit 1 +fi + +# --- Build the CMIS browser endpoint URL for content stream --- +CMIS_ENDPOINT="${CMIS_URL}browser/${defaultRepositoryID}/root?objectId=${OBJECT_ID}&cmisselector=content" + + +if [[ -n "${OUTPUT_PATH}" ]]; then + # Download to file + HTTP_CODE=$(curl -s -w "%{http_code}" \ + -X GET "$CMIS_ENDPOINT" \ + -H "Authorization: Bearer $ACCESS_TOKEN" \ + -o "$OUTPUT_PATH") + + if [[ "$HTTP_CODE" == "200" ]]; then + echo "SUCCESS: Document '${OBJECT_ID}' saved to '${OUTPUT_PATH}'." + exit 0 + else + echo "ERROR: Failed to read document. HTTP status: $HTTP_CODE" + # Print the output file content for debugging (it may contain the error body) + if [[ -f "$OUTPUT_PATH" ]]; then + cat "$OUTPUT_PATH" + fi + exit 1 + fi +else + # Stream to stdout + RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X GET "$CMIS_ENDPOINT" \ + -H "Authorization: Bearer $ACCESS_TOKEN") + + HTTP_CODE=$(echo "$RESPONSE" | tail -n1) + BODY=$(echo "$RESPONSE" | sed '$d') + + if [[ "$HTTP_CODE" == "200" ]]; then + echo "$BODY" + exit 0 + else + echo "ERROR: Failed to read document. HTTP status: $HTTP_CODE" + echo "$BODY" + exit 1 + fi +fi diff --git a/sdm/src/test/java/integration/com/sap/cds/sdm/utils/sdm-repo-manage.sh b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/sdm-repo-manage.sh new file mode 100755 index 000000000..9730a06c5 --- /dev/null +++ b/sdm/src/test/java/integration/com/sap/cds/sdm/utils/sdm-repo-manage.sh @@ -0,0 +1,317 @@ +#!/bin/bash +set -euo pipefail + +# --------------------------------------------------------------------------- +# sdm-repo-manage.sh — Manage SDM repositories (check, onboard, offboard). +# +# Usage: +# ./sdm-repo-manage.sh check --externalId +# ./sdm-repo-manage.sh onboard --externalId [--displayName ] [--description ] +# ./sdm-repo-manage.sh offboard --externalId +# ./sdm-repo-manage.sh list +# +# Exit codes: +# check: 0 = repo exists, 1 = repo NOT found, 2 = error +# onboard: 0 = success, non-zero = failure +# offboard: 0 = success, non-zero = failure +# list: 0 = success, prints repo list +# +# Required config in credentials.properties: +# CMIS_URL, authUrl, cmisClientID, cmisClientSecret, +# username, password +# --------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_FILE="${SCRIPT_DIR}/../../../../../../../resources/credentials.properties" + +# Load key=value pairs from .properties file +load_props() { + local key val + while IFS= read -r line || [[ -n "$line" ]]; do + [[ "$line" =~ ^[[:space:]]*$ || "$line" =~ ^[[:space:]]*# ]] && continue + key="${line%%=*}" + val="${line#*=}" + key="${key//[[:space:]]/}" + [[ -z "$key" ]] && continue + printf -v "$key" '%s' "$val" + done < "$1" +} + +# --- Load config --- +if [[ ! -f "$CONFIG_FILE" ]]; then + echo "ERROR: Config file not found at $CONFIG_FILE" + exit 2 +fi +load_props "$CONFIG_FILE" +CMIS_URL="${CMIS_URL%/}/" + +# --- Parse command --- +if [[ $# -lt 1 ]]; then + echo "Usage: $0 {check|onboard|offboard|list} [options]" + exit 2 +fi + +ACTION="$1" +shift + +# --- Parse optional arguments --- +EXTERNAL_ID="" +DISPLAY_NAME="" +DESCRIPTION="" +SUBDOMAIN="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --externalId) EXTERNAL_ID="$2"; shift 2 ;; + --displayName) DISPLAY_NAME="$2"; shift 2 ;; + --description) DESCRIPTION="$2"; shift 2 ;; + --subdomain) SUBDOMAIN="$2"; shift 2 ;; + *) echo "Unknown argument: $1"; exit 2 ;; + esac +done + +# --- Validate required config --- +for var in CMIS_URL authUrl cmisClientID cmisClientSecret; do + if [[ -z "${!var:-}" ]]; then + echo "ERROR: $var is not set in $CONFIG_FILE" + exit 2 + fi +done + +# --- Resolve token URL (replace provider subdomain with consumer if --subdomain given) --- +RESOLVED_TOKEN_URL="$authUrl" +if [[ -n "$SUBDOMAIN" ]]; then + # Extract provider subdomain from token URL (between :// and first .) + PROVIDER_SUBDOMAIN=$(echo "$authUrl" | sed -n 's|.*://\([^.]*\)\..*|\1|p') + RESOLVED_TOKEN_URL="${authUrl/$PROVIDER_SUBDOMAIN/$SUBDOMAIN}" + echo "Using consumer subdomain: $SUBDOMAIN (token URL: $RESOLVED_TOKEN_URL)" +fi + +# --- Obtain OAuth2 access token --- +get_token() { + local TOKEN_RESPONSE + if [[ -n "$SUBDOMAIN" ]]; then + # Use client_credentials grant for consumer-scoped access + TOKEN_RESPONSE=$(curl -s -X POST "${RESOLVED_TOKEN_URL}/oauth/token" \ + --data-urlencode "grant_type=client_credentials" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}") + else + # Use password grant for provider-scoped access + TOKEN_RESPONSE=$(curl -s -X POST "${RESOLVED_TOKEN_URL}/oauth/token" \ + --data-urlencode "grant_type=password" \ + --data-urlencode "client_id=${cmisClientID}" \ + --data-urlencode "client_secret=${cmisClientSecret}" \ + --data-urlencode "username=${username}" \ + --data-urlencode "password=${password}") + fi + + ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" \ + | grep -o '"access_token":"[^"]*"' \ + | sed 's/"access_token":"//;s/"$//' || true) + + if [[ -z "$ACCESS_TOKEN" ]]; then + echo "ERROR: Failed to obtain access token." + echo "Token response: $TOKEN_RESPONSE" + exit 2 + fi +} + +# =========================================================================== +# ACTION: list — List all onboarded repositories +# =========================================================================== +action_list() { + get_token + echo "Listing onboarded repositories..." + + RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X GET "${CMIS_URL}rest/v2/repositories" \ + -H "Authorization: Bearer ${ACCESS_TOKEN}" \ + -H "Content-Type: application/json") + + HTTP_CODE=$(echo "$RESPONSE" | tail -n1) + BODY=$(echo "$RESPONSE" | sed '$d') + + if [[ "$HTTP_CODE" != "200" ]]; then + echo "ERROR: Failed to list repositories (HTTP ${HTTP_CODE})." + echo "$BODY" + exit 2 + fi + + echo "$BODY" +} + +# =========================================================================== +# ACTION: check — Check if a repository with given externalId exists +# =========================================================================== +action_check() { + if [[ -z "$EXTERNAL_ID" ]]; then + echo "ERROR: --externalId is required for check" + exit 2 + fi + + get_token + echo "Checking if repository with externalId '${EXTERNAL_ID}' exists..." + + RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X GET "${CMIS_URL}rest/v2/repositories" \ + -H "Authorization: Bearer ${ACCESS_TOKEN}" \ + -H "Content-Type: application/json") + + HTTP_CODE=$(echo "$RESPONSE" | tail -n1) + BODY=$(echo "$RESPONSE" | sed '$d') + + if [[ "$HTTP_CODE" != "200" ]]; then + echo "ERROR: Failed to list repositories (HTTP ${HTTP_CODE})." + echo "$BODY" + exit 2 + fi + + # Check if any repository has the matching externalId + if echo "$BODY" | grep -q "\"externalId\":\"${EXTERNAL_ID}\""; then + echo "FOUND: Repository with externalId '${EXTERNAL_ID}' exists." + exit 0 + else + echo "NOT_FOUND: No repository with externalId '${EXTERNAL_ID}'." + exit 1 + fi +} + +# =========================================================================== +# ACTION: onboard — Create/onboard a new repository +# =========================================================================== +action_onboard() { + if [[ -z "$EXTERNAL_ID" ]]; then + echo "ERROR: --externalId is required for onboard" + exit 2 + fi + + # Default display name and description + [[ -z "$DISPLAY_NAME" ]] && DISPLAY_NAME="$EXTERNAL_ID" + [[ -z "$DESCRIPTION" ]] && DESCRIPTION="Repository $EXTERNAL_ID" + + get_token + echo "Onboarding repository with externalId '${EXTERNAL_ID}'..." + + PAYLOAD=$(cat </dev/null || true) + + if [[ -z "$REPO_ID" ]]; then + echo "NOT_FOUND: No repository with externalId '${EXTERNAL_ID}' to offboard." + exit 1 + fi + + echo "Found repository ID: ${REPO_ID} for externalId '${EXTERNAL_ID}'" + + # Delete the repository + DEL_RESPONSE=$(curl -s -w "\n%{http_code}" \ + -X DELETE "${CMIS_URL}rest/v2/repositories/${REPO_ID}" \ + -H "Authorization: Bearer ${ACCESS_TOKEN}" \ + -H "Content-Type: application/json") + + DEL_HTTP_CODE=$(echo "$DEL_RESPONSE" | tail -n1) + DEL_BODY=$(echo "$DEL_RESPONSE" | sed '$d') + + if [[ "$DEL_HTTP_CODE" == "200" || "$DEL_HTTP_CODE" == "204" ]]; then + echo "SUCCESS: Repository '${EXTERNAL_ID}' (ID: ${REPO_ID}) offboarded." + exit 0 + else + echo "ERROR: Failed to offboard repository (HTTP ${DEL_HTTP_CODE})." + echo "$DEL_BODY" + exit 1 + fi +} + +# =========================================================================== +# Dispatch action +# =========================================================================== +case "$ACTION" in + check) action_check ;; + onboard) action_onboard ;; + offboard) action_offboard ;; + list) action_list ;; + *) + echo "Unknown action: $ACTION" + echo "Usage: $0 {check|onboard|offboard|list} [options]" + exit 2 + ;; +esac diff --git a/sdm/src/test/resources/credentials.properties b/sdm/src/test/resources/credentials.properties index f6002f84c..6fd70c72a 100644 --- a/sdm/src/test/resources/credentials.properties +++ b/sdm/src/test/resources/credentials.properties @@ -10,4 +10,134 @@ appUrlMT= authUrlMTSDC= authUrlMTGWC= clientIDMT= -clientSecretMT= \ No newline at end of file +clientSecretMT= + +# ============================================================================== +# Cloud Foundry — Provider Account +# Used by: cf-update-env.sh (via CfEnvHelper.updateEnv) +# ============================================================================== + +# CF API endpoint for the landscape where the provider app is deployed +# Example: https://api.cf.eu12.hana.ondemand.com +CF_API_ENDPOINT=https://api.cf..hana.ondemand.com + +# CF organization that contains the provider space +CF_ORG= + +# CF space where the provider application is deployed +CF_SPACE= + +# SAP email address used to log in to CF (must have SpaceDeveloper role) +CF_USERNAME= + +# CF password — leave blank to be prompted at runtime (recommended for local runs) +CF_PASSWORD= + +# ============================================================================== +# Cloud Foundry — Application Environment Variable Update +# Used by: cf-update-env.sh (via CfEnvHelper.updateEnv) +# ============================================================================== + +# Technical CF app name (use cf apps to look it up; typically ends in -srv) +APP_NAME=-srv + +# Name of the user-provided environment variable to set on the app +VAR_NAME=REPOSITORY_ID + +# The new value to assign to VAR_NAME +VAR_VALUE= + +# ============================================================================== +# Cloud Foundry — Consumer Account +# Used by: cf-subscribe.sh, cf-unsubscribe.sh +# Leave CONSUMER_CF_USERNAME / CONSUMER_CF_PASSWORD blank to reuse CF_USERNAME / +# CF_PASSWORD from the provider section above. +# ============================================================================== + +# CF API endpoint for the consumer landscape (may differ from the provider) +CONSUMER_CF_API_ENDPOINT=https://api.cf..hana.ondemand.com + +# CF organization of the consumer account +CONSUMER_CF_ORG= + +# CF space of the consumer account +CONSUMER_CF_SPACE= + +# Consumer credentials — leave blank to reuse CF_USERNAME / CF_PASSWORD +CONSUMER_CF_USERNAME= +CONSUMER_CF_PASSWORD= + +# ============================================================================== +# BTP Subaccount Subscription +# Used by: cf-subscribe.sh, cf-unsubscribe.sh +# ============================================================================== + +# GUID of the BTP consumer subaccount to subscribe +# Find it in the BTP Cockpit under Account Details +CONSUMER_SUBACCOUNT_ID= + +# Technical name of the SaaS application to subscribe to +# Example: bookshop-mt-sdmgoogleworkspacedev +SAAS_APP_NAME= + +# Service plan name — leave blank if the app exposes only one (default) plan +SAAS_APP_PLAN= + +# Space-separated list of BTP user emails that will receive all app role collections +# Example: user1@sap.com user2@sap.com +ROLE_ASSIGNMENT_EMAILS= + +# Name to give the role collection created during subscription +# Defaults to "-Users" if left blank +ROLE_COLLECTION_NAME= + +# Substring used to filter roles by appId when assigning role collections +# Defaults to SAAS_APP_NAME if left blank +APP_ROLE_FILTER= + +# ============================================================================== +# BTP CLI +# Used by: cf-subscribe.sh, cf-unsubscribe.sh +# ============================================================================== + +# BTP CLI server URL — use the default unless you are on a canary landscape +BTP_CLI_URL=https://cli.btp.cloud.sap + +# Subdomain or GUID of the global account +# Find it in the BTP Cockpit under Account Details of the global account +BTP_GLOBAL_ACCOUNT_SUBDOMAIN= + +# ============================================================================== +# CMIS / SAP Document Management Service +# Used by: create.sh, get-object-id.sh, delete.sh +# +# All values are available in the SDM service instance service key. +# In the BTP Cockpit: go to your space → Service Instances → SDM instance → +# Service Keys → View → copy the JSON. +# ============================================================================== + +# ECM service URL — credentials.endpoints.ecmservice.url (must end with /) +CMIS_URL=https://api-sdm-di.cfapps..hana.ondemand.com/ + +# Repository ID created in the SDM Admin UI (Content Management → Repositories) +CMIS_REPOSITORY_ID= + +# UAA token URL — credentials.uaa.url (do NOT append /oauth/token; the script adds it) +CMIS_TOKEN_URL=https://.authentication..hana.ondemand.com + +# OAuth2 client ID — credentials.uaa.clientid +CMIS_CLIENT_ID= + +# OAuth2 client secret — credentials.uaa.clientsecret +CMIS_CLIENT_SECRET= + +# User for the OAuth2 password grant (typically the same as CF_USERNAME) +CMIS_USERNAME= + +# Password for CMIS_USERNAME +CMIS_PASSWORD= + +# (Optional) Default CMIS parent folder object ID used by create.sh when +# no parentFolderID argument is passed from the test. +# Leave blank to upload to the repository root. +CMIS_FOLDER_ID= \ No newline at end of file diff --git a/sdm/src/test/resources/credentials.properties.example b/sdm/src/test/resources/credentials.properties.example new file mode 100644 index 000000000..7f887456e --- /dev/null +++ b/sdm/src/test/resources/credentials.properties.example @@ -0,0 +1,53 @@ +# ============================================ +# Application Configuration +# ============================================ +# Login to CF before running tests: cf login -a https://api.cf..hana.ondemand.com -u -p -o -s + + +appUrl= +authUrl= +clientID= +clientSecret= +username= +password= +noSDMRoleUsername= +noSDMRoleUserPassword= +versionedRepositoryID= +virusScanRepositoryID= +defaultRepositoryID= +defaultRepositoryIDMT= + +# ============================================ +# Multi-Tenant Credentials +# ============================================ +appUrlMT= +authUrlMT1= +authUrlMT2= +clientIDMT= +clientSecretMT= + +# ============================================ +# Consumer Account Configuration +# ============================================ +consumerSubaccountIdMT1= +consumerSubdomainMT1= +consumerSubaccountIdMT2= +consumerSubdomainMT2= + +# BTP Subaccount Subscription +SAAS_APP_NAME= +ROLE_COLLECTION_NAME= +APP_ROLE_FILTER= + +# BTP CLI Configuration +BTP_CLI_URL=https://cli.btp.cloud.sap +BTP_GLOBAL_ACCOUNT_SUBDOMAIN= + +# ============================================ +# CMIS / SAP Document Management Service +# ============================================ +CMIS_URL=https://api-sdm-di.cfapps..hana.ondemand.com/ +cmisClientID= +cmisClientSecret= +cmisClientIDMT= +cmisClientSecretMT=