diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 4e0b5a43b..a8bab8c16 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -14,6 +14,7 @@ # specific language governing permissions and limitations # under the License. +#test name: Build Financial Services Repository on: @@ -24,57 +25,32 @@ on: jobs: - Build-repo-check: - + Run-Test-Suite: runs-on: ubuntu-latest + env: # Or as an environment variable + WSO2_PASSWORD: ${{secrets.SOLUTIONS_BOT_PASSWORD}} + STMP_ROOT_PASSWORD: ${{secrets.SOLUTIONS_BOT_PASSWORD}} + + steps: - - uses: actions/checkout@v2 - - name: Set up Adopt JDK 11 - uses: actions/setup-java@v2 - with: - java-version: 11.0.16+8 - distribution: 'temurin' - uses: actions/checkout@v3 - - name: Set up Node 16 - uses: actions/setup-node@v3 - with: - node-version: 16 - - name: Cache local Maven repository - uses: actions/cache@v4 - with: - path: ~/.m2/repository - key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} - restore-keys: | - ${{ runner.os }}-maven- - - - name: Setup Maven settings.xml - uses: whelk-io/maven-settings-xml-action@v11 - with: - mirrors: > - [ - { - "id": "wso2-nexus", - "mirrorOf": "wso2-nexus", - "url": "http://maven.wso2.org/nexus/content/groups/wso2-public/" - }, - { - "id": "wso2.releases", - "mirrorOf": "wso2.releases", - "url": "http://maven.wso2.org/nexus/content/repositories/releases/" - }, - { - "id": "wso2.snapshots", - "mirrorOf": "wso2.snapshots", - "url": "http://maven.wso2.org/nexus/content/repositories/snapshots/" - }, - { - "id": "knopflerfish", - "mirrorOf": "knopflerfish", - "url": "http://resources.knopflerfish.org/repo/maven2/release" - } - ] - - name: Build with Maven + - name: Run Tests run: | - export MAVEN_OPTS="-Xmx4g -XX:MaxPermSize=512m" - mvn -B install --file pom.xml + + if [ -z "$WSO2_PASSWORD" ]; then + echo "❌ WSO2_PASSWORD is not set!" +# exit 1 + else + echo "✅ WSO2_PASSWORD is set." + fi + + RUNNER_HOME=`pwd` + bash $RUNNER_HOME/test-automation/test.sh -u solutions-bot@wso2.com -p ${{ secrets.SOLUTIONS_BOT_PASSWORD }} -o "$HOME" -h "$HOME" + + + + + + + diff --git a/.gitignore b/.gitignore index 77401fa65..634be682a 100644 --- a/.gitignore +++ b/.gitignore @@ -67,4 +67,7 @@ node_modules/ **/dist/ **/package-lock.json -fs-integration-test-suite/accelerator-test-framework/src/main/resources/TestConfiguration.xml + +/.smarttomcat/ + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/.choreo/component.yaml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/.choreo/component.yaml new file mode 100644 index 000000000..249dcf980 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/.choreo/component.yaml @@ -0,0 +1,45 @@ +# Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com/) All Rights Reserved. +# +# WSO2 LLC. licenses this file to you under the Apache License, +# Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# +required The configuration file schema version +schemaVersion: 1.1 + +# +optional Incoming connection details for the component +endpoints: + # +required Unique name for the endpoint. + # This name will be used when generating the managed API + - name: consent-mgt + # +optional Display name for the endpoint. + displayName: Consent Mgt + # +required Service section has the user service endpoint details + service: + # +optional Base path of the API that gets exposed via the endpoint. + # This is mandatory if the endpoint type is set to REST or GraphQL. + basePath: / + # +required Numeric port value that gets exposed via the endpoint + port: 8080 + # +required Type of traffic that the endpoint is accepting. + # Allowed values: REST, GraphQL, GRPC, TCP, UDP. + type: REST + # +optional Network level visibilities of the endpoint. + # Accepted values: Project|Organization|Public(Default). + networkVisibilities: + - Public + # +optional The path to the schema definition file. + # Defaults to wildcard route if not specified. + # This is only applicable to REST endpoint types. + # The path should be relative to the docker context. + schemaFilePath: financial-services-accelerator/internal-webapps/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/openapi.yaml diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/README.md b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/README.md new file mode 100644 index 000000000..d9058b64f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/README.md @@ -0,0 +1,74 @@ +# Consent Management API + +A lightweight RESTful API for managing user consent records, built using JAX-RS with Apache CXF. + +## 🧰 Features + +- Create, retrieve, update, and revoke and track consent records +- Clean and minimal implementation for quick integration or extension +- Dockerized for easy deployment + +## 🛠️ Technologies + +- Java +- Apache CXF (JAX-RS) +- Maven +- Tomcat +- Docker + +--- + +## 🚀 Getting Started + +Follow these steps to build and run the project using Docker. + +### 1. Clone the Repository + +```bash + +git clone https://github.com/ParameswaranSajeenthiran/consent-mgt-api.git + +cd consent-mgt-api +``` + +### 2. Configure Database + +Copy the context.xml to same folder and configure the database credentials + +| Placeholder | Description | Example | +|-------------------|--------------------------------------|-------------------------| +| `` | Your MySQL database username | `wso2_user` | +| `` | Your MySQL database password | `your_secure_password` | +| `` | Hostname or IP address of the DB | `localhost` or `db` | +| `` | Name of your MySQL database | `wso2_consent_db` | + + + +```bash + +cp deployment/context.xml.example deployment/context.xml +``` + + +### 3. Build the Docker Image + +```bash + +docker build -t consent-rest-api -f deployment/Dockerfile . + +``` + +### 4. Run the Docker Container + +```bash + +docker run -p 8080:8080 consent-rest-api + +``` + +Explore the APIs available in the Swagger UI at http://localhost:8080/swagger-ui/index.html?url=http://localhost:8080/api/openapi.json + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/pom.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/pom.xml new file mode 100644 index 000000000..37ed8ae83 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/pom.xml @@ -0,0 +1,259 @@ + + + + 4.0.0 + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.api + 4.0.0-SNAPSHOT + ../../pom.xml + + + org.wso2.financial.services.accelerator.consent.mgt.dao + WSO2 Financial Services - Consent DAO + WSO2 Financial Services - Consent DAO Module + http://maven.apache.org + jar + + + + commons-logging + commons-logging + + + org.apache.commons + commons-lang3 + + + net.minidev + json-smart + ${json-smart.version} + + + com.fasterxml.jackson.core + jackson-databind + + + org.apache.commons + commons-collections4 + + + org.wso2.eclipse.osgi + org.eclipse.osgi.services + + + org.eclipse.osgi + org.eclipse.osgi + + + + + + + + com.github.spotbugs + spotbugs-annotations + + + + commons-dbcp + commons-dbcp + + + org.testng + testng + test + + + com.h2database.wso2 + h2-database-engine + test + + + org.jacoco + org.jacoco.agent + runtime + test + + + org.mockito + mockito-core + test + + + jakarta.ws.rs + jakarta.ws.rs-api + 2.1.6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + src/test/resources/testng.xml + + + target/jacoco.exec + + true + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + **/*ServiceComponent.class + **/*Constants.class + **/*Exception.class + + **/ConsentStoreInitializer.class + **/ConsentRetentionDataStoreInitializer.class + **/MssqlConsentCoreDAOImpl.class + **/ConsentMgtMssqlDBQueries.class + **/OracleConsentCoreDAOImpl.class + **/ConsentMgtOracleDBQueries.class + **/ConsentMgtPostgresDBQueries.class + + + + + default-prepare-agent + + prepare-agent + + + + default-prepare-agent-integration + + prepare-agent-integration + + + + default-report + + report + + + + default-report-integration + + report-integration + + + + default-check + + check + + + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.7 + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + UTF-8 + + + + org.apache.felix + maven-bundle-plugin + true + + + + ${project.artifactId} + + + org.wso2.financial.services,accelerator.consent.mgt.dao.internal + + + org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", + org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", + org.wso2.financial.services.accelerator.common.*;version="${project.version}", + org.apache.commons.lang3;version="${commons-lang3.version}", + org.apache.commons.collections4;version="${commons-collections.version}", + org.apache.commons.logging;version="${commons.logging.version}", + net.minidev.json; version="${json-smart.version}" + + + !org.wso2.financial.services,accelerator.consent.mgt.dao.internal, + org.wso2.financial.services.accelerator.consent.mgt.dao.*;version="${project.version}", + + <_dsannotations>* + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/ConsentCoreDAO.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/ConsentCoreDAO.java new file mode 100644 index 000000000..ef7b85924 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/ConsentCoreDAO.java @@ -0,0 +1,499 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao; + +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * This interface access the data storage layer to retrieve, store, delete and update consent management related + * resources. + */ +public interface ConsentCoreDAO { + + /** + * This method is used to store the consent resource in the database. The request consent resource object must + * contain all data in it without the consent ID. A consent ID will be generated and set to the response object + * if the insertion is successful. + * + * @param connection connection object + * @param consentResource ConsentResource object with all required data + * @return returns the consent resource with the consent ID and created time if insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + ConsentResource storeConsentResource(Connection connection, ConsentResource consentResource) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve a consent resource for the provided consent ID (without associated consent + * attributes). + * + * @param connection connection object + * @param consentID consent ID + * @return returns the consent resource related to the provided consent ID without consent attributes. + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ConsentResource getConsentResource(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve a consent resource for the provided consent ID with associated attributes. + * + * @param connection connection object + * @param consentID consent ID + * @return returns the consent resource related to the provided consent ID with additional consent attributes + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ConsentResource getConsentResourceWithAttributes(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve a detailed consent resource for the provided consent ID (includes + * authorization resources, account mapping resources and consent attributes). + * + * @param connection connection object + * @param consentID consent ID + * @return returns a detailed consent resource related to the provided consent ID + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + DetailedConsentResource getDetailedConsentResource(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve a detailed consent resource for the provided consent ID (includes + * authorization resources, account mapping resources and consent attributes). + * + * @param connection connection object + * @param consentID consent ID + * @return returns a detailed consent resource related to the provided consent ID + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + DetailedConsentResource getConsentResourceWithAuthorizationResources(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to update the status of a consent resource. The request consent resource object must be + * set with a consent ID and the new consent status. + * + * @param connection connection object + * @param consentID consent ID of the consent needed to be updated + * @param consentStatus the new status that should be updated with + * @throws ConsentDataUpdationException thrown if a database error occur or an update failure + */ + void updateConsentStatus(Connection connection, String consentID, String consentStatus) + throws + ConsentDataUpdationException; + + /** + * This method is used to update consent receipt. + * + * @param connection connection object + * @param consentID ID of the consent to be amended + * @param consentReceipt new consent receipt + * @throws ConsentDataUpdationException thrown if an error occur in the process + */ + void updateConsentReceipt(Connection connection, String consentID, String consentReceipt) + throws + ConsentDataUpdationException; + + /** + * This method is used to update consent validity time. + * + * @param connection connection object + * @param consentID consent ID + * @param validityTime new validity time + * @throws ConsentDataUpdationException thrown if any error occurs in the process + */ + void updateConsentValidityTime(Connection connection, String consentID, long validityTime) + throws + ConsentDataUpdationException; + + /** + * This method is used to store the authorization resource in the database. The request authorization resource + * object must contain data all in it without the authorization ID and the updated time. Both of them will be + * generated and set to the response object if the insertion is successful. + * + * @param connection connection object + * @param authorizationResource authorization resource with all required data + * @return returns the authorization resource with the updated time if insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + AuthorizationResource storeAuthorizationResource(Connection connection, AuthorizationResource authorizationResource) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve an authorization resource for the provided authorization ID. + * + * @param connection connection object + * @param authorizationID authorization ID + * @return the relevant authorization resource + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + AuthorizationResource getAuthorizationResource(Connection connection, String authorizationID, String orgID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to update a given authorization object. The status of the authorization resource provided + * will be updated with the new status. + * + * @param connection connection object + * @param authorizationID authorization ID of the resource needed to be updated + * @param newAuthorizationStatus the new authorization status that should be updated with + * @throws ConsentDataUpdationException thrown if a database error occur or an update failure + */ + void updateAuthorizationStatus(Connection connection, String authorizationID, String newAuthorizationStatus) + throws + ConsentDataUpdationException; + + /** + * This method is used for updating the user of a given authorization resource. The user ID of the authorization + * resource provided will be updated with the new user ID. + * + * @param connection connection object + * @param authorizationID authorization ID of the resource needed to be updated + * @param userID the new user ID that should be updated with + * @throws ConsentDataUpdationException thrown if a database error occur or an update failure + */ + void updateAuthorizationUser(Connection connection, String authorizationID, String userID) + throws + ConsentDataUpdationException; + + /** + * This method is used to store the consent mapping resource in the database. The request consent mapping object + * must contain all the data in it without the consent mapping ID. It will be generated and set to the response + * object if the insertion is successful. + * + * @param connection connection object + * @param consentMappingResource consent mapping resource with all required data + * @return returns the consent mapping resource if the insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + ConsentMappingResource storeConsentMappingResource(Connection connection, + ConsentMappingResource consentMappingResource) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve consent mapping resources for a given authorization ID. + * + * @param connection connection object + * @param authorizationID authorization ID + * @return a list of all consent mapping resources for the given authorization ID + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ArrayList getConsentMappingResources(Connection connection, String authorizationID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to update given consent mapping resources. All the mapping resources of provided mapping + * IDs will be updated with the new mapping status provided. + * + * @param connection connection object + * @param mappingIDs a list of mapping IDs that needed to be updated + * @param mappingStatus the new mapping status that should be updated with + * @throws ConsentDataUpdationException thrown if a database error occur or an update failure + */ + void updateConsentMappingStatus(Connection connection, ArrayList mappingIDs, + String mappingStatus) + throws + ConsentDataUpdationException; + + /** + * This method is used to store the consent attributes in the database. The request consent attributes object + * must be set with a consent ID and consent attribute map. + * must be set with a consent ID and consent attribute map. + * + * @param connection connection object + * @param consentAttributes consent attributes object with consent ID and attributes map + * @return returns true if insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + boolean storeConsentAttributes(Connection connection, ConsentAttributes consentAttributes) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve all the consent attributes from the database for the given consent ID. + * + * @param connection connection object + * @param consentID consent ID + * @return returns the consent attributes that matches the provided consentID and consent attribute keys + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ConsentAttributes getConsentAttributes(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve the consent attributes from the database for given attribute keys. + * + * @param connection connection object + * @param consentID consent ID + * @param consentAttributeKeys the keys of the consent attributes that need to be retrieved + * @return returns the consent attributes that matches the provided consentID and consent attribute keys + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ConsentAttributes getConsentAttributes(Connection connection, String consentID, + ArrayList consentAttributeKeys) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve consent attribute using the attribute name. + * + * @param connection connection object + * @param attributeName attribute name + * @return a map with the consent ID and the related attribute value + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + Map getConsentAttributesByName(Connection connection, String attributeName) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve consent id using the attribute name and value. + * + * @param connection connection object + * @param attributeName attribute name + * @param attributeValue attribute value + * @return Consent ID related to the given attribute key and value + * @throws ConsentDataRetrievalException `thrown if a database error occurs + */ + ArrayList getConsentIdByConsentAttributeNameAndValue(Connection connection, String attributeName, + String attributeValue) + throws + ConsentDataRetrievalException; + + /** + * This method is used to update a given list of consent attributes. + * + * @param connection connection object + * @param consentID consent ID + * @param consentAttributes a map of attributes that should be updated + * @throws ConsentDataUpdationException thrown if a database error occurs + */ + void updateConsentAttributes(Connection connection, String consentID, Map consentAttributes) + throws + ConsentDataUpdationException; + + /** + * This method is used to delete a given list of consent attributes. + * + * @param connection connection object + * @param consentID consent ID + * @param consentAttributeKeys a list of attribute keys that should be deleted + * @return true if the deletion is successful + * @throws ConsentDataDeletionException thrown if a database error occurs + */ + boolean deleteConsentAttributes(Connection connection, String consentID, ArrayList consentAttributeKeys) + throws + ConsentDataDeletionException; + + /** + * This method is used to store the consent file in the database. The request consent file object must be set + * with a consent ID and the file that needed to be stored. + * + * @param connection connection object + * @param consentFileResource consent file resource with consent ID and the file content + * @return returns true if insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + boolean storeConsentFile(Connection connection, ConsentFile consentFileResource) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve the consent file from the database. + * + * @param connection connection object + * @param consentID consent ID of the file needed to be retrieved + * @return returns the requested consent file resource + * @throws ConsentDataRetrievalException thrown if a database error occur or an retrieval failure + */ + ConsentFile getConsentFile(Connection connection, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to search detailed consents for the given lists of parameters. The search will be + * performed according to the provided input. Any list can contain any number of elements. The conjunctive result + * will be returned. If all lists are passed as null, all the consents related to other search parameters will be + * returned. "fromTime" and "toTime" are also optional. "limit" and "offset" are optional combined. If all + * parameters are null, all the consents will be returned. + * + * @param connection connection object + * @param consentIDs consent IDs optional list + * @param clientIDs client IDs optional list + * @param consentTypes consent types optional list + * @param consentStatuses consent statuses optional list + * @param userIDs user IDs optional list + * @param fromTime from time + * @param toTime to time + * @param limit limit + * @param offset offset + * @return a list of detailed consent resources according to the provided parameters or the list of all consents + * if all parameters are null + * @throws ConsentDataRetrievalException thrown if any error occur + */ + ArrayList searchConsents(Connection connection, String orgID, ArrayList consentIDs, + ArrayList clientIDs, ArrayList consentTypes, + ArrayList consentStatuses, ArrayList userIDs, + Long fromTime, Long toTime, Integer limit, Integer offset) + throws + ConsentDataRetrievalException; + + + /** + * This method is used to search authorization resources using following optional parameters. If all the input + * parameters are null, all the relevant authorization resources will be returned. + * 1. Consent ID + * 2. User ID + * + * @param connection connection object + * @param consentID consent ID (optional) + * @param userID user ID (optional) + * @return a list of authorization resources + * @throws ConsentDataRetrievalException thrown if an error occurs in the process + */ + ArrayList searchConsentAuthorizations(Connection connection, String consentID, String userID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to store the consent status audit record in the database. The request consent status audit + * record object must contain all the data in it without the status audit ID and actionTime. They will be generated + * and set to the response object if the insertion is successful. + * + * @param connection connection object + * @param consentStatusAuditRecord consent status audit record with all required data + * @return returns the consent status audit record if the insertion is successful + * @throws ConsentDataInsertionException thrown if a database error occur or an insertion failure + */ + ConsentStatusAuditRecord storeConsentStatusAuditRecord(Connection connection, + ConsentStatusAuditRecord consentStatusAuditRecord) + throws + ConsentDataInsertionException; + + + /** + * This method is used to retrieve consent status audit records. It queries the consent audit records by the + * parameter that is provided. All parameters are optional. If no parameters are provided, all the records will + * be queried. + * + * @param connection connection object + * @param consentID consent ID + * @param currentStatus current status of the consent + * @param actionBy the user who performed the status update + * @param fromTime lower bound of the time of the needed records + * @param toTime upper bound of the time of the needed records + * @param statusAuditID status audit ID + * @return a list of retrieved audit records that matches the provided parameters + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ArrayList getConsentStatusAuditRecords(Connection connection, String consentID, + String currentStatus, String actionBy, + Long fromTime, Long toTime, + String statusAuditID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to retrieve a list of consent status audit records by consent_ids. + * + * @param connection connection object + * @param consentIDs consentIDs + * @return returns a list of consent status audit records. + * @throws ConsentDataRetrievalException thrown if a database error occurs + */ + ArrayList getConsentStatusAuditRecordsByConsentId(Connection connection, + ArrayList consentIDs, + Integer limit, Integer offset) + throws + ConsentDataRetrievalException; + + /** + * This method is used to store the changed attribute values of the consent into consent history when an + * amendment happens to the consent. + * + * @param connection connection object + * @param historyID An identifier for consent history uniquely assigned per consent amendment + * @param timestamp The timestamp at which the consent amendment happened + * @param recordID Identifier for each history record (can be ConsentID or MappingID) + * @param consentDataType The consent data type stored in each history record (can be ConsentData, + * ConsentAttributesData or ConsentMappingData) + * @param changedAttributesJsonString The key-value pair json string that represents the changes + * relevant to each history record + * @param amendmentReason A string that indicates the reason that caused the amendment of the consent + * @return true if insertion successful + * @throws ConsentDataInsertionException thrown if any error occurs in the process + */ + boolean storeConsentAmendmentHistory(Connection connection, String historyID, long timestamp, String recordID, + String consentDataType, String changedAttributesJsonString, + String amendmentReason) + throws + ConsentDataInsertionException; + + /** + * This method is used to retrieve consent amendment history for a given consentID provided with its mappingIDs, + * AuthorizationIDs. + * + * @param connection connection object + * @param recordIDsList the list of recordIDs relevant to the consent (includes consentID, MappingIDs, AuthIDs) + * @return a comprehensive map of consent history data + * @throws ConsentDataRetrievalException thrown if any error occurs in the process + */ + Map retrieveConsentAmendmentHistory(Connection connection, + List recordIDsList, String consentID) + throws + ConsentDataRetrievalException; + + /** + * This method is used to fetch consents which has a expiring time as a consent attribute + * (eligible for expiration). + * @throws ConsentDataRetrievalException thrown if any error occurs in the process + */ + ArrayList getExpiringConsents(Connection connection, String orgID, + String statusesEligibleForExpiration) + throws + ConsentDataRetrievalException; + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java new file mode 100644 index 000000000..d8204fde9 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/constants/ConsentMgtDAOConstants.java @@ -0,0 +1,165 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.constants; + +import java.util.HashMap; +import java.util.Map; + + + +/** + * Constants related to the DAO layer. + */ +public class ConsentMgtDAOConstants { + + public static final String CONSENT_ID = "CONSENT_ID"; + public static final String ORG_ID = "ORG_ID"; + public static final String DEFAULT_ORG = "DEFAULT_ORG"; + public static final String RECEIPT = "RECEIPT"; + public static final String CREATED_TIME = "CREATED_TIME"; + public static final String UPDATED_TIME = "UPDATED_TIME"; + public static final String CLIENT_ID = "CLIENT_ID"; + public static final String CONSENT_TYPE = "CONSENT_TYPE"; + public static final String CURRENT_STATUS = "CURRENT_STATUS"; + public static final String CONSENT_FREQUENCY = "CONSENT_FREQUENCY"; + public static final String VALIDITY_TIME = "VALIDITY_TIME"; + public static final String RECURRING_INDICATOR = "RECURRING_INDICATOR"; + public static final String CONSENT_CREATED_TIME = "CONSENT_CREATED_TIME"; + public static final String CONSENT_UPDATED_TIME = "CONSENT_UPDATED_TIME"; + public static final String AUTH_ID = "AUTH_ID"; + public static final String AUTH_TYPE = "AUTH_TYPE"; + public static final String USER_ID = "USER_ID"; + public static final String AUTH_STATUS = "AUTH_STATUS"; + public static final String AUTH_UPDATED_TIME = "AUTH_UPDATED_TIME"; + public static final String MAPPING_ID = "MAPPING_ID"; + public static final String ACCOUNT_ID = "ACCOUNT_ID"; + public static final String PERMISSION = "PERMISSION"; + public static final String MAPPING_STATUS = "MAPPING_STATUS"; + public static final String RESOURCE = "resource"; + public static final String ATT_KEY = "ATT_KEY"; + public static final String ATT_VALUE = "ATT_VALUE"; + public static final String SESSION_DATA_KEY = "sessionDataKey"; + public static final String CONSENT_FILE = "CONSENT_FILE"; + public static final String AUTH_MAPPING_ID = "AUTH_MAPPING_ID"; + public static final String ACTION_BY = "ACTION_BY"; + public static final String ACTION_TIME = "ACTION_TIME"; + public static final String STATUS_AUDIT_ID = "STATUS_AUDIT_ID"; + public static final String PREVIOUS_STATUS = "PREVIOUS_STATUS"; + public static final String REASON = "REASON"; + public static final String RECORD_ID = "RECORD_ID"; + public static final String EFFECTIVE_TIMESTAMP = "EFFECTIVE_TIMESTAMP"; + public static final String TABLE_ID = "TABLE_ID"; + public static final String HISTORY_ID = "HISTORY_ID"; + public static final String CHANGED_VALUES = "CHANGED_VALUES"; + public static final String CONSENT_EXPIRY_TIME_ATTRIBUTE = "ExpirationDateTime"; + + public static final String TYPE_CONSENT_BASIC_DATA = "ConsentData"; + public static final String TYPE_CONSENT_AUTH_RESOURCE_DATA = "ConsentAuthResourceData"; + public static final String TYPE_CONSENT_ATTRIBUTES_DATA = "ConsentAttributesData"; + public static final String TYPE_CONSENT_MAPPING_DATA = "ConsentMappingData"; + public static final String CONSENT_IDS = "consentIDs"; + public static final String CLIENT_IDS = "clientIDs"; + public static final String CONSENT_TYPES = "consentTypes"; + public static final String CONSENT_STATUSES = "consentStatuses"; + public static final String USER_IDS = "userIDs"; + public static final String IN = "inOperator"; + public static final String AND = "andOperator"; + public static final String OR = "orOperator"; + public static final String WHERE = "where"; + public static final String PLACEHOLDER = "placeholder"; + public static final String PLAIN_PLACEHOLDER = "plainPlaceholder"; + public static final String EQUALS = "equals"; + // Consent Database Table Identifiers + public static final String TABLE_FS_CONSENT = "FS_CONSENT"; + public static final String TABLE_FS_CONSENT_AUTH_RESOURCE = "FS_CONSENT_AUTH_RESOURCE"; + public static final String TABLE_FS_CONSENT_MAPPING = "FS_CONSENT_MAPPING"; + public static final String TABLE_FS_CONSENT_ATTRIBUTE = "FS_CONSENT_ATTRIBUTE"; + public static final String TABLE_FS_CONSENT_FILE = "FS_CONSENT_FILE"; + + //Numbers are assigned to each consent DB table & used as the reference for each table when storing CA history +public static final Map TABLES_MAP = new HashMap<>(); +static { + TABLES_MAP.put(TABLE_FS_CONSENT, "01"); + TABLES_MAP.put(TABLE_FS_CONSENT_AUTH_RESOURCE, "02"); + TABLES_MAP.put(TABLE_FS_CONSENT_MAPPING, "03"); + TABLES_MAP.put(TABLE_FS_CONSENT_ATTRIBUTE, "04"); + TABLES_MAP.put(TABLE_FS_CONSENT_FILE, "05"); +} + +public static final Map COLUMNS_MAP = new HashMap<>(); +static { + COLUMNS_MAP.put(CONSENT_IDS, "CONSENT_ID"); + COLUMNS_MAP.put(CLIENT_IDS, "CLIENT_ID"); + COLUMNS_MAP.put(CONSENT_TYPES, "CONSENT_TYPE"); + COLUMNS_MAP.put(ORG_ID, "ORG_ID"); + COLUMNS_MAP.put(CONSENT_STATUSES, "CURRENT_STATUS"); + COLUMNS_MAP.put(USER_IDS, "OCAR.USER_ID"); +} + //Error Messages + public static final String CONSENT_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing consent resource in " + + "the database"; + public static final String FAILED_TO_STORE_ERROR_MSG = "Failed to store the consent resource in the database."; + public static final String NO_RECORDS_FOUND_ERROR_MSG = "No records are found for the given inputs"; + public static final String CONSENT_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + + "resource from the database"; + public static final String CONSENT_WITH_ATTRIBUTES_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + + "resource with consent attributes from the database for the given consent ID"; + public static final String DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + + "detailed consent resource from the database"; + public static final String CONSENT_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating consent status in the" + + " database"; + public static final String AUTHORIZATION_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing authorization " + + "resource in the database"; + public static final String CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + + "consent authorization resource from the database"; + public static final String CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating " + + "authorization status in the database"; + public static final String CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG = "Error occurred while updating " + + "authorization user in the database"; + public static final String CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG = "Error occurred while storing consent " + + "mapping resource in the database"; + public static final String CONSENT_MAPPING_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent mapping " + + "resources from the database"; + public static final String CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG = "Error occurred while updating consent " + + "mapping status in the database"; + public static final String CONSENT_ATTRIBUTES_STORE_ERROR_MSG = "Error occurred while storing consent attributes " + + "in the database"; + public static final String CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + + "attributes from the database for the given consent ID"; + public static final String CONSENT_ATTRIBUTES_KEYS_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent " + + "attributes from the database for the given consent ID and attribute keys"; + public static final String CONSENT_ID_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent id from the " + + "database for the given attribute key and attribute value"; + public static final String CONSENT_ATTRIBUTES_UPDATE_ERROR_MSG = "Error occurred while updating consent " + + "attributes in the database"; + public static final String CONSENT_ATTRIBUTES_DELETE_ERROR_MSG = "Error occurred while deleting consent " + + "attributes in the database"; + public static final String CONSENT_FILE_STORE_ERROR_MSG = "Error occurred while storing consent file resource in " + + "the database"; + public static final String CONSENT_FILE_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent file " + + "resource from the database"; + public static final String CONSENT_SEARCH_ERROR_MSG = "Error occurred while searching consents"; + public static final String AUDIT_RECORD_STORE_ERROR_MSG = "Error occurred while storing consent status audit " + + "record in the database"; + public static final String AUDIT_RECORDS_RETRIEVE_ERROR_MSG = "Error occurred while retrieving consent status " + + "audit records"; + public static final String CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG = "Error occurred while retrieving " + + "consent amendment history records from the database for the given consent ID"; + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataDeletionException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataDeletionException.java new file mode 100644 index 000000000..cda863c45 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataDeletionException.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions; + +/** + * ConsentDataDeletionException. + */ +public class ConsentDataDeletionException extends Exception { + + public ConsentDataDeletionException(String message) { + super(message); + } + + public ConsentDataDeletionException(String message, Throwable e) { + super(message, e); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataInsertionException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataInsertionException.java new file mode 100644 index 000000000..542d2a18f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataInsertionException.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions; + +/** + * ConsentDataInsertionException. + */ +public class ConsentDataInsertionException extends Exception { + + public ConsentDataInsertionException(String message) { + super(message); + } + + public ConsentDataInsertionException(String message, Throwable e) { + super(message, e); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataRetrievalException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataRetrievalException.java new file mode 100644 index 000000000..67246c4db --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataRetrievalException.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions; + +/** + * ConsentDataRetrievalException. + */ +public class ConsentDataRetrievalException extends Exception { + + public ConsentDataRetrievalException(String message) { + super(message); + } + + public ConsentDataRetrievalException(String message, Throwable e) { + super(message, e); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataUpdationException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataUpdationException.java new file mode 100644 index 000000000..146745be0 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentDataUpdationException.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions; + +/** + * ConsentDataUpdationException. + */ +public class ConsentDataUpdationException extends Exception { + + public ConsentDataUpdationException(String message) { + super(message); + } + + public ConsentDataUpdationException(String message, Throwable e) { + super(message, e); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentMgtException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentMgtException.java new file mode 100644 index 000000000..3ea1fde4a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/exceptions/ConsentMgtException.java @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions; + +import javax.ws.rs.core.Response; + +/** + * Used for creating runtime exceptions for financial services modules. + */ +public class ConsentMgtException extends Exception { + + private static final long serialVersionUID = -5686395831712095972L; + private Response.Status errorCode; + + public ConsentMgtException(Response.Status errorCode, Throwable cause) { + + super(cause); + this.errorCode = errorCode; + } + + + public ConsentMgtException(Response.Status errorCode, String message) { + + super(message); + this.errorCode = errorCode; + } + + public ConsentMgtException(String message) { + + super(message); + } + + + public ConsentMgtException(Response.Status status, String message, Throwable cause) { + super(message, cause); + this.errorCode = status; + + } + + public ConsentMgtException(String message, Throwable cause) { + super(message, cause); + } + + public Response.Status getErrorCode() { + + return errorCode; + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java new file mode 100644 index 000000000..5b171f392 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOImpl.java @@ -0,0 +1,1735 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.impl; + +import com.fasterxml.jackson.core.JsonProcessingException; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.ConsentManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * This class only implements the data access methods for the consent management accelerator. It implements all the + * methods defined in the ConsentCoreDAO interface and is only responsible for reading and writing data from/to the + * database. The incoming data are pre-validated in the upper service layer. Therefore, no validations are done in + * this layer. + */ +public class ConsentCoreDAOImpl implements ConsentCoreDAO { + + private static final Log log = LogFactory.getLog(ConsentCoreDAOImpl.class); + private static final String GROUP_BY_SEPARATOR = "\\|\\|"; + ConsentMgtCommonDBQueries sqlStatements; + + public ConsentCoreDAOImpl(ConsentMgtCommonDBQueries sqlStatements) { + + this.sqlStatements = sqlStatements; + } + + @Override + public ConsentResource storeConsentResource(Connection connection, ConsentResource consentResource) + throws + ConsentDataInsertionException { + + String consentID = StringUtils.isBlank(consentResource.getConsentID()) ? UUID.randomUUID().toString() : + consentResource.getConsentID(); + // Unix time in seconds + long currentTimestamp = System.currentTimeMillis() / 1000; + long createdTime = consentResource.getCreatedTime() == 0 ? currentTimestamp : consentResource.getCreatedTime(); + long updatedTime = consentResource.getUpdatedTime() == 0 ? currentTimestamp : consentResource.getUpdatedTime(); + + String storeConsentPrepStatement = sqlStatements.getStoreConsentPreparedStatement(); + + try (PreparedStatement storeConsentPreparedStmt = connection.prepareStatement(storeConsentPrepStatement)) { + + log.debug("Setting parameters to prepared statement to store consent resource"); + storeConsentPreparedStmt.setString(1, consentResource.getOrgID()); + + storeConsentPreparedStmt.setString(2, consentID); + storeConsentPreparedStmt.setString(3, consentResource.getReceipt()); + storeConsentPreparedStmt.setLong(4, createdTime); + storeConsentPreparedStmt.setLong(5, updatedTime); + storeConsentPreparedStmt.setString(6, consentResource.getClientID()); + storeConsentPreparedStmt.setString(7, consentResource.getConsentType()); + storeConsentPreparedStmt.setString(8, consentResource.getCurrentStatus()); + storeConsentPreparedStmt.setLong(9, consentResource.getConsentFrequency()); + storeConsentPreparedStmt.setLong(10, consentResource.getValidityPeriod()); + storeConsentPreparedStmt.setBoolean(11, consentResource.isRecurringIndicator()); + + // with result, we can determine whether the insertion was successful or not + int result = storeConsentPreparedStmt.executeUpdate(); + + // Confirm that the data are inserted successfully + if (result > 0) { + log.debug("Stored the consent resource successfully"); + consentResource.setConsentID(consentID); + consentResource.setCreatedTime(createdTime); + consentResource.setUpdatedTime(createdTime); + return consentResource; + } else { + log.error(ConsentMgtDAOConstants.FAILED_TO_STORE_ERROR_MSG); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.FAILED_TO_STORE_ERROR_MSG); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_RESOURCE_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_RESOURCE_STORE_ERROR_MSG, e); + } + } + + @Override + public ConsentResource getConsentResource(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + String getConsentResourcePrepStatement = sqlStatements.getGetConsentPreparedStatement(); + + try (PreparedStatement getConsentResourcePreparedStmt = + connection.prepareStatement(getConsentResourcePrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent resource"); + + getConsentResourcePreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { + if (resultSet.next()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the consent resource from FS_CONSENT table for consent ID" + + " : %s", consentID.replaceAll("[\r\n]", ""))); + } + return ConsentManagementDAOUtil.setDataToConsentResource(resultSet); + } else { + log.error(String.format("No records are found for consent ID : %S", + consentID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent resource for " + + "consent ID : %s", consentID.replaceAll("[\r\n]", "")); + log.error(errorMessage, e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + } + + @Override + public ConsentResource getConsentResourceWithAttributes(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + String getConsentResourcePrepStatement = sqlStatements.getGetConsentWithConsentAttributesPreparedStatement(); + + try (PreparedStatement getConsentResourcePreparedStmt = + connection.prepareStatement(getConsentResourcePrepStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { + + log.debug("Setting parameters to prepared statement to retrieve consent resource with consent " + + "attributes"); + + getConsentResourcePreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { + if (resultSet.next()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the consent resource with consent attributes for " + + "consent ID : %s ", consentID.replaceAll("[\r\n]", ""))); + } + return ConsentManagementDAOUtil.setDataToConsentResourceWithAttributes(resultSet); + } else { + log.error(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent " + + "resource with consent attributes for consent ID : %s", consentID.replaceAll("[\r\n]", "")); + log.error(errorMessage, e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_WITH_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_WITH_ATTRIBUTES_RETRIEVE_ERROR_MSG, + e); + } + } + + @Override + public DetailedConsentResource getDetailedConsentResource(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + String getDetailedConsentResourcePrepStatement = sqlStatements.getGetDetailedConsentPreparedStatement(); + + try (PreparedStatement getDetailedConsentResourcePreparedStmt = connection + .prepareStatement(getDetailedConsentResourcePrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve detailed consent resource"); + + getDetailedConsentResourcePreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getDetailedConsentResourcePreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the detailed consent resource for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + } + return ConsentManagementDAOUtil.setDataToDetailedConsentResource(resultSet); + } else { + log.error(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + log.error("Error occurred while reading detailed consent resource", e); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving " + + "detailed consent resource for consent ID : %s", consentID), e); + } + } catch (SQLException | JsonProcessingException e) { + log.error(ConsentMgtDAOConstants.DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants + .DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + } + + @Override + public DetailedConsentResource getConsentResourceWithAuthorizationResources(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + String getConsentResourceWithAuthorizationResourcesPreparedStatemen = sqlStatements. + getGetConsentResourceWithAuthorizationResourcesPreparedStatement(); + + try (PreparedStatement getConsentResourceWithAuthorizationResourcesPreparedStmt = connection + .prepareStatement(getConsentResourceWithAuthorizationResourcesPreparedStatemen)) { + + log.debug("Setting parameters to prepared statement to retrieve detailed consent resource"); + + getConsentResourceWithAuthorizationResourcesPreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentResourceWithAuthorizationResourcesPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the detailed consent resource for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + } + return ConsentManagementDAOUtil.setDataToConsentResourceWithAuthorizationResource(resultSet); + } else { + log.error(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + log.error("Error occurred while reading detailed consent resource", e); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving " + + "detailed consent resource for consent ID : %s", consentID), e); + } + } catch (SQLException | JsonProcessingException e) { + log.error(ConsentMgtDAOConstants.DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants + .DETAILED_CONSENT_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + } + + + + @Override + public void updateConsentStatus(Connection connection, String consentID, String newConsentStatus) + throws + ConsentDataUpdationException { + + long updatedTime = System.currentTimeMillis() / 1000; + String updateConsentStatusPrepStatement = sqlStatements.getUpdateConsentStatusPreparedStatement(); + + try (PreparedStatement updateConsentStatusPreparedStmt = + connection.prepareStatement(updateConsentStatusPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update consent status"); + + updateConsentStatusPreparedStmt.setString(1, newConsentStatus); + updateConsentStatusPreparedStmt.setLong(2, updatedTime); + updateConsentStatusPreparedStmt.setString(3, consentID); + + // with result, we can determine whether the updating was successful or not + int result = updateConsentStatusPreparedStmt.executeUpdate(); + // Confirm that the data are updated successfully + if (result > 0) { + log.debug("Updated the consent status successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent status properly."); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_STATUS_UPDATE_ERROR_MSG, e); + throw new ConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_STATUS_UPDATE_ERROR_MSG, e); + } + } + + @Override + public void updateConsentReceipt(Connection connection, String consentID, String consentReceipt) + throws + ConsentDataUpdationException { + + String updateConsentReceiptPrepStatement = sqlStatements.getUpdateConsentReceiptPreparedStatement(); + + try (PreparedStatement updateConsentReceiptPreparedStmt = + connection.prepareStatement(updateConsentReceiptPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update consent receipt"); + + updateConsentReceiptPreparedStmt.setString(1, consentReceipt); + updateConsentReceiptPreparedStmt.setString(2, consentID); + + // with result, we can determine whether the updating was successful or not + int result = updateConsentReceiptPreparedStmt.executeUpdate(); + // Confirm that the data are updated successfully + if (result > 0) { + log.debug("Updated the consent receipt successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent receipt properly."); + } + } catch (SQLException e) { + String errorMessage = String.format("Error while updating consent receipt for consent ID: %s", consentID); + log.error(errorMessage.replaceAll("[\r\n]", ""), e); + throw new ConsentDataUpdationException(errorMessage, e); + } + } + + @Override + public void updateConsentValidityTime(Connection connection, String consentID, long validityTime) + throws + ConsentDataUpdationException { + + String updateConsentReceiptPrepStatement = sqlStatements.getUpdateConsentValidityTimePreparedStatement(); + long updatedTime = System.currentTimeMillis() / 1000; + + try (PreparedStatement updateConsentValidityTimePreparedStmt = + connection.prepareStatement(updateConsentReceiptPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update consent receipt"); + + updateConsentValidityTimePreparedStmt.setLong(1, validityTime); + updateConsentValidityTimePreparedStmt.setLong(2, updatedTime); + updateConsentValidityTimePreparedStmt.setString(3, consentID); + + // with result, we can determine whether the updating was successful or not + int result = updateConsentValidityTimePreparedStmt.executeUpdate(); + // Confirm that the data are updated successfully + if (result > 0) { + log.debug("Updated the consent validity time successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent validity time properly."); + } + } catch (SQLException e) { + String errorMessage = String.format("Error while updating consent validity time for consent ID: %s", + consentID); + log.error(errorMessage.replaceAll("[\r\n]", ""), e); + throw new ConsentDataUpdationException(errorMessage, e); + } + } + + @Override + public AuthorizationResource storeAuthorizationResource(Connection connection, + AuthorizationResource authorizationResource) + throws + ConsentDataInsertionException { + + String authorizationID = StringUtils.isEmpty(authorizationResource.getAuthorizationID()) ? + UUID.randomUUID().toString() : authorizationResource.getAuthorizationID(); + // Unix time in seconds + long updatedTime = authorizationResource.getUpdatedTime() == 0 ? System.currentTimeMillis() / 1000 : + authorizationResource.getUpdatedTime(); + + String storeAuthorizationPrepStatement = sqlStatements.getStoreAuthorizationPreparedStatement(); + + try (PreparedStatement storeAuthorizationPreparedStmt = + connection.prepareStatement(storeAuthorizationPrepStatement)) { + + log.debug("Setting parameters to prepared statement to store authorization resource"); + + storeAuthorizationPreparedStmt.setString(1, authorizationID); + storeAuthorizationPreparedStmt.setString(2, authorizationResource.getConsentID()); + storeAuthorizationPreparedStmt.setString(3, authorizationResource.getAuthorizationType()); + storeAuthorizationPreparedStmt.setString(4, authorizationResource.getUserID()); + storeAuthorizationPreparedStmt.setString(5, authorizationResource.getAuthorizationStatus()); + storeAuthorizationPreparedStmt.setLong(6, updatedTime); + + // with result, we can determine whether the insertion was successful or not + int result = storeAuthorizationPreparedStmt.executeUpdate(); + + // Confirm that the data are inserted successfully + if (result > 0) { + log.debug("Stored the authorization resource successfully"); + authorizationResource.setAuthorizationID(authorizationID); + authorizationResource.setUpdatedTime(updatedTime); + return authorizationResource; + } else { + throw new ConsentDataInsertionException("Failed to store authorization resource data properly."); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.AUTHORIZATION_RESOURCE_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.AUTHORIZATION_RESOURCE_STORE_ERROR_MSG, e); + } + } + + @Override + public AuthorizationResource getAuthorizationResource(Connection connection, String authorizationID, String orgID) + throws + ConsentDataRetrievalException { + + String getAuthorizationResourcePrepStatement = sqlStatements.getGetAuthorizationResourcePreparedStatement(); + + try (PreparedStatement getConsentResourcePreparedStmt = + connection.prepareStatement(getAuthorizationResourcePrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent authorization resource"); + + getConsentResourcePreparedStmt.setString(1, authorizationID); + getConsentResourcePreparedStmt.setString(2, orgID); + + try (ResultSet resultSet = getConsentResourcePreparedStmt.executeQuery()) { + if (resultSet.next()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the consent authorization resource for authorization ID" + + " : %s", authorizationID.replaceAll("[\r\n]", ""))); + } + return ConsentManagementDAOUtil.setAuthorizationDataWithConsentMapping(resultSet, + ConsentMgtDAOConstants.UPDATED_TIME); + } else { + log.error(String.format("No records are found for authorization ID : %s", + authorizationID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(String.format("No records are found for " + + "authorization ID : %s", + authorizationID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent authorization " + + "resource for authorization ID : %s", authorizationID.replaceAll("[\r\n]", + "")); + log.error(errorMessage, e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException | JsonProcessingException e) { + log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants. + CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + } + + @Override + public void updateAuthorizationStatus(Connection connection, String authorizationID, String newAuthorizationStatus) + throws + ConsentDataUpdationException { + + // Unix time in seconds + long updatedTime = System.currentTimeMillis() / 1000; + String updateAuthorizationStatusPrepStatement = sqlStatements.getUpdateAuthorizationStatusPreparedStatement(); + + try (PreparedStatement updateAuthorizationStatusPreparedStmt = + connection.prepareStatement(updateAuthorizationStatusPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update authorization status"); + + updateAuthorizationStatusPreparedStmt.setString(1, newAuthorizationStatus); + updateAuthorizationStatusPreparedStmt.setLong(2, updatedTime); + updateAuthorizationStatusPreparedStmt.setString(3, authorizationID); + + // with result, we can determine whether the updating was successful or not + int result = updateAuthorizationStatusPreparedStmt.executeUpdate(); + + // Confirm that the data are updated successfully + if (result > 0) { + log.debug("Updated the authorization status successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent status properly."); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG, e); + throw new ConsentDataUpdationException(ConsentMgtDAOConstants + .CONSENT_AUTHORIZATION_STATUS_UPDATE_ERROR_MSG, e); + } + } + + @Override + public void updateAuthorizationUser(Connection connection, String authorizationID, String userID) + throws + ConsentDataUpdationException { + // Unix time in seconds + long updatedTime = System.currentTimeMillis() / 1000; + String updateAuthorizationUserPrepStatement = sqlStatements.getUpdateAuthorizationUserPreparedStatement(); + + try (PreparedStatement updateAuthorizationUserPreparedStmt = + connection.prepareStatement(updateAuthorizationUserPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update authorization user"); + + updateAuthorizationUserPreparedStmt.setString(1, userID); + updateAuthorizationUserPreparedStmt.setLong(2, updatedTime); + updateAuthorizationUserPreparedStmt.setString(3, authorizationID); + + // with result, we can determine whether the updating was successful or not + int result = updateAuthorizationUserPreparedStmt.executeUpdate(); + + // Confirm that the data are updated successfully + if (result > 0) { + log.debug("Updated the authorization user successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update authorization user properly."); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG, e); + throw new ConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_USER_UPDATE_ERROR_MSG, + e); + } + } + + @Override + public ConsentMappingResource storeConsentMappingResource(Connection connection, + ConsentMappingResource consentMappingResource) + throws + ConsentDataInsertionException { + + String consentMappingID = StringUtils.isEmpty(consentMappingResource.getMappingID()) ? + UUID.randomUUID().toString() : consentMappingResource.getMappingID(); + + String storeConsentMappingPrepStatement = sqlStatements.getStoreConsentMappingPreparedStatement(); + + try (PreparedStatement storeConsentMappingPreparedStmt = + connection.prepareStatement(storeConsentMappingPrepStatement)) { + + log.debug("Setting parameters to prepared statement to store consent mapping resource"); + + storeConsentMappingPreparedStmt.setString(1, consentMappingID); + storeConsentMappingPreparedStmt.setString(2, consentMappingResource.getAuthorizationID()); + storeConsentMappingPreparedStmt.setString(3, consentMappingResource.getResource().toString()); + storeConsentMappingPreparedStmt.setString(4, consentMappingResource.getMappingStatus()); + + + // with result, we can determine whether the insertion was successful or not + int result = storeConsentMappingPreparedStmt.executeUpdate(); + + // Confirm that the data are inserted successfully + if (result > 0) { + log.debug("Stored the consent mapping resource successfully"); + consentMappingResource.setMappingID(consentMappingID); + return consentMappingResource; + } else { + throw new ConsentDataInsertionException("Failed to store consent mapping resource data properly."); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_MAPPING_RESOURCE_STORE_ERROR_MSG, + e); + } + } + + @Override + public ArrayList getConsentMappingResources(Connection connection, String authorizationID) + throws + ConsentDataRetrievalException { + + ArrayList retrievedConsentMappingResources = new ArrayList<>(); + String getMappingResourcePrepStatement = sqlStatements.getGetConsentMappingResourcesPreparedStatement(); + + try (PreparedStatement getConsentMappingResourcePreparedStmt = + connection.prepareStatement(getMappingResourcePrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent mapping resources"); + + getConsentMappingResourcePreparedStmt.setString(1, authorizationID); + + try (ResultSet resultSet = getConsentMappingResourcePreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + retrievedConsentMappingResources.add(ConsentManagementDAOUtil + .getConsentMappingResourceWithData(resultSet)); + } + } else { + log.debug(String.format("No records are found for authorization ID : %s", + authorizationID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException e) { + log.error("Error occurred while reading consent mapping resources", e); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + + "mapping resources for authorization ID : %s", authorizationID), e); + } + + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the consent mapping resources for authorization ID : %s", + authorizationID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException | JsonProcessingException e) { + log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_MAPPING_RETRIEVE_ERROR_MSG, e); + } + return retrievedConsentMappingResources; + } + + @Override + public void updateConsentMappingStatus(Connection connection, ArrayList mappingIDs, String mappingStatus) + throws + ConsentDataUpdationException { + + int[] result; + String updateConsentMappingStatusPrepStatement = sqlStatements.getUpdateConsentMappingStatusPreparedStatement(); + + try (PreparedStatement updateConsentMappingStatusPreparedStmt = + connection.prepareStatement(updateConsentMappingStatusPrepStatement)) { + + log.debug("Setting parameters to prepared statement to update consent mapping status"); + + for (String mappingID : mappingIDs) { + updateConsentMappingStatusPreparedStmt.setString(1, mappingStatus); + updateConsentMappingStatusPreparedStmt.setString(2, mappingID); + updateConsentMappingStatusPreparedStmt.addBatch(); + } + + // with result, we can determine whether the updating was successful or not + result = updateConsentMappingStatusPreparedStmt.executeBatch(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG, e); + throw new ConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_MAPPING_STATUS_UPDATE_ERROR_MSG, e); + } + + // An empty array or an array with value -3 means the batch execution is failed + if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { + log.debug("Updated the consent mapping statuses of matching records successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent mapping status properly."); + } + } + + @Override + public boolean storeConsentAttributes(Connection connection, ConsentAttributes consentAttributes) + throws + ConsentDataInsertionException { + + int[] result; + String storeConsentAttributesPrepStatement = sqlStatements.getStoreConsentAttributesPreparedStatement(); + Map consentAttributesMap = consentAttributes.getConsentAttributes(); + + try (PreparedStatement storeConsentAttributesPreparedStmt = + connection.prepareStatement(storeConsentAttributesPrepStatement)) { + + for (Map.Entry entry : consentAttributesMap.entrySet()) { + storeConsentAttributesPreparedStmt.setString(1, consentAttributes.getConsentID()); + storeConsentAttributesPreparedStmt.setString(2, entry.getKey()); + storeConsentAttributesPreparedStmt.setString(3, entry.getValue()); + storeConsentAttributesPreparedStmt.addBatch(); + } + + // with result, we can determine whether the updating was successful or not + result = storeConsentAttributesPreparedStmt.executeBatch(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_STORE_ERROR_MSG, e); + } + + /* + An empty array or an array with value -3 means the batch execution is failed. + If an array contains value -2, it means the command completed successfully but the number of rows affected + are unknown. Therefore, only checking for the existence of -3. + */ + if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { + log.debug("Stored the consent attributes successfully"); + return true; + } else { + throw new ConsentDataInsertionException("Failed to store consent attribute data properly."); + } + } + + @Override + public ConsentAttributes getConsentAttributes(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + Map retrievedConsentAttributesMap = new HashMap<>(); + String getConsentAttributesPrepStatement = sqlStatements.getGetConsentAttributesPreparedStatement(); + + try (PreparedStatement getConsentAttributesPreparedStmt = + connection.prepareStatement(getConsentAttributesPrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent attributes"); + + getConsentAttributesPreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentAttributesPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + retrievedConsentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), + resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); + } + } else { + log.debug(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException e) { + log.error("Error occurred while reading consent attributes", e); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + + "attributes for consent ID : %s", consentID), e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); + } + + ConsentAttributes retrievedConsentAttributesResource = new ConsentAttributes(); + retrievedConsentAttributesResource.setConsentID(consentID); + retrievedConsentAttributesResource.setConsentAttributes(retrievedConsentAttributesMap); + return retrievedConsentAttributesResource; + } + + @Override + public ConsentAttributes getConsentAttributes(Connection connection, String consentID, + ArrayList consentAttributeKeys) + throws + ConsentDataRetrievalException { + + Map retrievedConsentAttributesMap = new HashMap<>(); + String getConsentAttributesPrepStatement = sqlStatements.getGetConsentAttributesPreparedStatement(); + + try (PreparedStatement getConsentAttributesPreparedStmt = + connection.prepareStatement(getConsentAttributesPrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent attributes"); + + getConsentAttributesPreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentAttributesPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + String attributeKey = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY); + String attributeValue = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE); + + // Filter the needed attributes + if (consentAttributeKeys.contains(attributeKey)) { + retrievedConsentAttributesMap.put(attributeKey, attributeValue); + if (retrievedConsentAttributesMap.size() == consentAttributeKeys.size()) { + break; + } + } + } + } else { + log.error(String.format("No records are found for consent ID : %s and consent attribute keys", + consentID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent attributes for " + + "consent ID : %s and provided consent attributes", consentID.replaceAll("[\r\n]", "")); + log.error(errorMessage, e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_KEYS_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_KEYS_RETRIEVE_ERROR_MSG, + e); + } + + ConsentAttributes retrievedConsentAttributesResource = new ConsentAttributes(); + retrievedConsentAttributesResource.setConsentID(consentID); + retrievedConsentAttributesResource.setConsentAttributes(retrievedConsentAttributesMap); + return retrievedConsentAttributesResource; + } + + @Override + public Map getConsentAttributesByName(Connection connection, String attributeName) + throws + ConsentDataRetrievalException { + + Map retrievedConsentAttributesMap = new HashMap<>(); + String getConsentAttributesByNamePrepStatement = sqlStatements.getGetConsentAttributesByNamePreparedStatement(); + + try (PreparedStatement getConsentAttributesByNamePreparedStmt = + connection.prepareStatement(getConsentAttributesByNamePrepStatement)) { + + if (log.isDebugEnabled()) { + log.debug(String.format("Setting parameters to prepared statement to retrieve consent attributes" + + " for the provided key: %s", attributeName.replaceAll("[\r\n]", ""))); + } + getConsentAttributesByNamePreparedStmt.setString(1, attributeName); + + try (ResultSet resultSet = getConsentAttributesByNamePreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + retrievedConsentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), + resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); + } + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent attributes for " + + "attribute key: %s", attributeName); + log.error(errorMessage.replaceAll("[\r\n]", ""), e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_RETRIEVE_ERROR_MSG, e); + } + return retrievedConsentAttributesMap; + } + + @Override + public ArrayList getConsentIdByConsentAttributeNameAndValue(Connection connection, String attributeName, + String attributeValue) + throws + ConsentDataRetrievalException { + + ArrayList retrievedConsentIdList = new ArrayList<>(); + String getConsentIdByConsentAttributeNameAndValuePrepStatement = sqlStatements + .getConsentIdByConsentAttributeNameAndValuePreparedStatement(); + + try (PreparedStatement getConsentAttributesByNamePreparedStmt = + connection.prepareStatement(getConsentIdByConsentAttributeNameAndValuePrepStatement)) { + + if (log.isDebugEnabled()) { + log.debug(String.format("Setting parameters to prepared statement to retrieve consent id for the" + + " provided key: %s and value: %s", attributeName.replaceAll("[\r\n]", ""), + attributeValue.replaceAll("[\r\n]", ""))); + } + getConsentAttributesByNamePreparedStmt.setString(1, attributeName); + getConsentAttributesByNamePreparedStmt.setString(2, attributeValue); + + try (ResultSet resultSet = getConsentAttributesByNamePreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + retrievedConsentIdList.add(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); + } + } else { + if (log.isDebugEnabled()) { + log.debug(String.format("No records are found for the provided attribute key : %s " + + "and value: %s", attributeName.replaceAll("[\r\n]", ""), + attributeValue.replaceAll("[\r\n]", ""))); + } + } + } catch (SQLException e) { + String errorMessage = String.format("Error occurred while retrieving consent " + + "attributes for attribute key: %s and value: %s", attributeName, attributeValue); + log.error(errorMessage.replaceAll("[\r\n]", ""), e); + throw new ConsentDataRetrievalException(errorMessage, e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ID_RETRIEVE_ERROR_MSG); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_ID_RETRIEVE_ERROR_MSG, e); + } + return retrievedConsentIdList; + } + + @Override + public void updateConsentAttributes(Connection connection, String consentID, Map consentAttributes) + throws + ConsentDataUpdationException { + + int[] result; + String updateConsentAttributesPrepStatement = sqlStatements.getUpdateConsentAttributesPreparedStatement(); + + try (PreparedStatement updateConsentAttributesPreparedStmt = + connection.prepareStatement(updateConsentAttributesPrepStatement)) { + + for (Map.Entry entry : consentAttributes.entrySet()) { + updateConsentAttributesPreparedStmt.setString(1, entry.getValue()); + updateConsentAttributesPreparedStmt.setString(2, consentID); + updateConsentAttributesPreparedStmt.setString(3, entry.getKey()); + updateConsentAttributesPreparedStmt.addBatch(); + } + + // with result, we can determine whether the updating was successful or not + result = updateConsentAttributesPreparedStmt.executeBatch(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_UPDATE_ERROR_MSG, e); + throw new ConsentDataUpdationException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_UPDATE_ERROR_MSG, e); + } + + /* + An empty array or an array with value -3 means the batch execution is failed. + If an array contains value -2, it means the command completed successfully but the number of rows affected + are unknown. Therefore, only checking for the existence of -3. + */ + if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { + log.debug("Updated the consent attributes successfully"); + } else { + throw new ConsentDataUpdationException("Failed to update consent attribute data properly."); + } + } + + @Override + public boolean deleteConsentAttributes(Connection connection, String consentID, + ArrayList consentAttributeKeys) + throws + ConsentDataDeletionException { + + int[] result; + String deleteConsentAttributePrepStatement = sqlStatements.getDeleteConsentAttributePreparedStatement(); + + try (PreparedStatement deleteConsentAttributesPreparedStmt = + connection.prepareStatement(deleteConsentAttributePrepStatement)) { + + log.debug("Setting parameters to prepared statement to delete the provided consent attributes"); + + for (String key : consentAttributeKeys) { + deleteConsentAttributesPreparedStmt.setString(1, consentID); + deleteConsentAttributesPreparedStmt.setString(2, key); + deleteConsentAttributesPreparedStmt.addBatch(); + } + + result = deleteConsentAttributesPreparedStmt.executeBatch(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG, e); + throw new ConsentDataDeletionException(ConsentMgtDAOConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG, e); + } + + if (result.length != 0 && IntStream.of(result).noneMatch(value -> value == -3)) { + if (log.isDebugEnabled()) { + log.debug(String.format("Deleted the consent attribute of key %s", + consentAttributeKeys.toString().replaceAll("[\r\n]", ""))); + } + return true; + } else { + throw new ConsentDataDeletionException("Failed to delete consent attribute properly."); + } + } + + @Override + public boolean storeConsentFile(Connection connection, ConsentFile consentFileResource) + throws + ConsentDataInsertionException { + + int result; + String storeConsentMappingPrepStatement = sqlStatements.getStoreConsentFilePreparedStatement(); + + try (PreparedStatement storeConsentFilePreparedStmt = + connection.prepareStatement(storeConsentMappingPrepStatement)) { + + log.debug("Setting parameters to prepared statement to store consent file resource"); + + storeConsentFilePreparedStmt.setString(1, consentFileResource.getConsentID()); + storeConsentFilePreparedStmt.setString(2, consentFileResource.getConsentFile()); + + // with result, we can determine whether the insertion was successful or not + result = storeConsentFilePreparedStmt.executeUpdate(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_FILE_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.CONSENT_FILE_STORE_ERROR_MSG, e); + } + + // Confirm that the data are inserted successfully + if (result > 0) { + log.debug("Stored the consent file resource successfully"); + return true; + } else { + throw new ConsentDataInsertionException("Failed to store consent file resource data properly."); + } + } + + @Override + public ConsentFile getConsentFile(Connection connection, String consentID) + throws + ConsentDataRetrievalException { + + ConsentFile receivedConsentFileResource = new ConsentFile(); + String getConsentFilePrepStatement = sqlStatements.getGetConsentFileResourcePreparedStatement(); + + try (PreparedStatement getConsentFileResourcePreparedStmt = + connection.prepareStatement(getConsentFilePrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent file resource"); + + getConsentFileResourcePreparedStmt.setString(1, consentID); + + try (ResultSet resultSet = getConsentFileResourcePreparedStmt.executeQuery()) { + if (resultSet.next()) { + String storedConsentID = resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID); + String consentFile = resultSet.getString(ConsentMgtDAOConstants.CONSENT_FILE); + + receivedConsentFileResource.setConsentID(storedConsentID); + receivedConsentFileResource.setConsentFile(consentFile); + } else { + log.error(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + log.error("Error occurred while reading consent file resource"); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving consent file" + + " resource for consent ID : %s", consentID.replaceAll("[\r\n]", "")), e); + } + + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieved the consent file resource for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_FILE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_FILE_RETRIEVE_ERROR_MSG, e); + } + return receivedConsentFileResource; + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(searchConsentsPreparedStatement, + // ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + + + public ArrayList searchConsents(Connection connection, + String orgID, ArrayList consentIDs, + ArrayList clientIDs, + ArrayList consentTypes, + ArrayList consentStatuses, + ArrayList userIDs, Long fromTime, Long toTime, + Integer limit, Integer offset) + throws + ConsentDataRetrievalException { + + boolean shouldLimit = true; + boolean shouldOffset = true; + int parameterIndex = 0; + Map> applicableConditionsMap = new HashMap<>(); + + + if (orgID == null) { + orgID = ConsentMgtDAOConstants.DEFAULT_ORG; + } + ArrayList orgIDs = new ArrayList<>(); + orgIDs.add(orgID); + validateAndSetSearchConditions(orgIDs, applicableConditionsMap, consentIDs, clientIDs, consentTypes, + consentStatuses); + + // Don't limit if either of limit or offset is null + if (limit == null) { + shouldLimit = false; + } + if (offset == null) { + shouldOffset = false; + } + + // logic to set the prepared statement + log.debug("Constructing the prepared statement"); + String constructedConditions = + ConsentManagementDAOUtil.constructConsentSearchPreparedStatement(applicableConditionsMap); + + String userIDFilterCondition = ""; + Map> userIdMap = new HashMap<>(); + if (CollectionUtils.isNotEmpty(userIDs)) { + userIdMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); + userIDFilterCondition = ConsentManagementDAOUtil.constructUserIdListFilterCondition(userIdMap); + } + + String searchConsentsPreparedStatement = + sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, shouldOffset, + userIDFilterCondition); + + try (PreparedStatement searchConsentsPreparedStmt = + connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_UPDATABLE)) { + + /* Since we don't know the order of the set condition clauses, have to determine the order of them to set + the actual values to the prepared statement */ + Map> orderedParamsMap = ConsentManagementDAOUtil.determineOrderOfParamsToSet( + constructedConditions, applicableConditionsMap, ConsentMgtDAOConstants.COLUMNS_MAP); + + log.debug("Setting parameters to prepared statement to search consents"); + + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedParamsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + + //determine order of user Ids to set + if (CollectionUtils.isNotEmpty(userIDs)) { + Map> orderedUserIdsMap = ConsentManagementDAOUtil + .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, + ConsentMgtDAOConstants.COLUMNS_MAP); + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedUserIdsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + } + + if (fromTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (toTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (limit != null && offset != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, limit); + searchConsentsPreparedStmt.setInt(++parameterIndex, offset); + } else if (limit != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, limit); + } + ArrayList detailedConsentResources = new ArrayList<>(); + + try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + int resultSetSize = ConsentManagementDAOUtil.getResultSetSize(resultSet); + detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); + } + return detailedConsentResources; + } catch (SQLException e) { + log.error("Error occurred while searching detailed consent resources", e); + throw new ConsentDataRetrievalException("Error occurred while searching detailed " + + "consent resources", e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG); + } + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(searchAuthorizationResourcesPrepStatement) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public ArrayList searchConsentAuthorizations(Connection connection, String consentID, + String userID) + throws + ConsentDataRetrievalException { + + ArrayList retrievedAuthorizationResources = new ArrayList<>(); + Map conditions = new HashMap<>(); + if (StringUtils.trimToNull(consentID) != null) { + conditions.put("CONSENT_ID", consentID); + } + if (StringUtils.trimToNull(userID) != null) { + conditions.put("USER_ID", userID); + } + String whereClause = ConsentManagementDAOUtil.constructAuthSearchPreparedStatement(conditions); + String searchAuthorizationResourcesPrepStatement = + sqlStatements.getSearchAuthorizationResourcesPreparedStatement(whereClause); + + try (PreparedStatement getSearchAuthorizationResourcesPreparedStmt = + connection.prepareStatement(searchAuthorizationResourcesPrepStatement)) { + + if (log.isDebugEnabled()) { + log.debug("Setting parameters to prepared statement to search authorization resources"); + } + + Iterator> conditionIterator = conditions.entrySet().iterator(); + + for (int count = 1; count <= conditions.size(); count++) { + getSearchAuthorizationResourcesPreparedStmt.setString(count, conditionIterator.next().getValue()); + } + + try (ResultSet resultSet = getSearchAuthorizationResourcesPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResource + .setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); + authorizationResource.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); + authorizationResource + .setUserID(resultSet.getString(ConsentMgtDAOConstants.USER_ID)); + authorizationResource.setAuthorizationStatus(resultSet + .getString(ConsentMgtDAOConstants.AUTH_STATUS)); + authorizationResource + .setAuthorizationType(resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE)); + authorizationResource.setUpdatedTime(resultSet.getLong(ConsentMgtDAOConstants.UPDATED_TIME)); + retrievedAuthorizationResources.add(authorizationResource); + } + } else { + log.error("No records are found for the provided inputs"); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + log.error("Error occurred while searching authorization resources", e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants + .CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + log.debug("Retrieved the authorization resources successfully"); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants + .CONSENT_AUTHORIZATION_RESOURCE_RETRIEVE_ERROR_MSG, e); + } + return retrievedAuthorizationResources; + } + + @Override + public ConsentStatusAuditRecord storeConsentStatusAuditRecord(Connection connection, + ConsentStatusAuditRecord consentStatusAuditRecord) + throws + ConsentDataInsertionException { + + int result; + String statusAuditID = StringUtils.isEmpty(consentStatusAuditRecord.getStatusAuditID()) ? + UUID.randomUUID().toString() : consentStatusAuditRecord.getStatusAuditID(); + // Unix time in seconds + long actionTime = (consentStatusAuditRecord.getActionTime() == 0) ? System.currentTimeMillis() : + consentStatusAuditRecord.getActionTime(); + + String storeConsentStatusAuditRecordPrepStatement = + sqlStatements.getStoreConsentStatusAuditRecordPreparedStatement(); + + try (PreparedStatement storeConsentStatusAuditRecordPreparedStmt = + connection.prepareStatement(storeConsentStatusAuditRecordPrepStatement)) { + + log.debug("Setting parameters to prepared statement to store consent audit record"); + + storeConsentStatusAuditRecordPreparedStmt.setString(1, statusAuditID); + storeConsentStatusAuditRecordPreparedStmt.setString(2, consentStatusAuditRecord + .getConsentID()); + storeConsentStatusAuditRecordPreparedStmt.setString(3, consentStatusAuditRecord + .getCurrentStatus()); + storeConsentStatusAuditRecordPreparedStmt.setLong(4, actionTime); + storeConsentStatusAuditRecordPreparedStmt.setString(5, consentStatusAuditRecord.getReason()); + storeConsentStatusAuditRecordPreparedStmt.setString(6, consentStatusAuditRecord + .getActionBy()); + storeConsentStatusAuditRecordPreparedStmt.setString(7, consentStatusAuditRecord + .getPreviousStatus()); + + // with result, we can determine whether the insertion was successful or not + result = storeConsentStatusAuditRecordPreparedStmt.executeUpdate(); + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.AUDIT_RECORD_STORE_ERROR_MSG, e); + throw new ConsentDataInsertionException(ConsentMgtDAOConstants.AUDIT_RECORD_STORE_ERROR_MSG, e); + } + + // Confirm that the data are inserted successfully + if (result > 0) { + log.debug("Stored the consent status audit record successfully"); + consentStatusAuditRecord.setStatusAuditID(statusAuditID); + consentStatusAuditRecord.setActionTime(actionTime); + return consentStatusAuditRecord; + } else { + throw new ConsentDataInsertionException("Failed to store consent status audit record data properly."); + } + } + + @Override + public ArrayList getConsentStatusAuditRecords(Connection connection, String consentID, + String currentStatus, String actionBy, + Long fromTime, Long toTime, + String statusAuditID) + throws + ConsentDataRetrievalException { + + ArrayList retrievedAuditRecords = new ArrayList<>(); + String getConsentStatusAuditRecordsPrepStatement = + sqlStatements.getGetConsentStatusAuditRecordsPreparedStatement(); + + try (PreparedStatement getConsentStatusAuditRecordPreparedStmt = + connection.prepareStatement(getConsentStatusAuditRecordsPrepStatement)) { + + if (log.isDebugEnabled()) { + log.debug("Setting parameters to prepared statement to retrieve consent status audit records"); + } + + // consentID + if (StringUtils.trimToNull(consentID) != null) { + getConsentStatusAuditRecordPreparedStmt.setString(1, consentID); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(1, Types.VARCHAR); + } + + // currentStatus + if (StringUtils.trimToNull(currentStatus) != null) { + getConsentStatusAuditRecordPreparedStmt.setString(2, currentStatus); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(2, Types.VARCHAR); + } + + // actionBy + if (StringUtils.trimToNull(actionBy) != null) { + getConsentStatusAuditRecordPreparedStmt.setString(3, actionBy); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(3, Types.VARCHAR); + } + + // statusAuditID + if (StringUtils.trimToNull(statusAuditID) != null) { + getConsentStatusAuditRecordPreparedStmt.setString(4, statusAuditID); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(4, Types.VARCHAR); + } + + // fromTime + if (fromTime != null) { + getConsentStatusAuditRecordPreparedStmt.setLong(5, fromTime); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(5, Types.BIGINT); + } + + // toTime + if (toTime != null) { + getConsentStatusAuditRecordPreparedStmt.setLong(6, toTime); + } else { + getConsentStatusAuditRecordPreparedStmt.setNull(6, Types.BIGINT); + } + + try (ResultSet resultSet = getConsentStatusAuditRecordPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); + consentStatusAuditRecord + .setStatusAuditID(resultSet.getString(ConsentMgtDAOConstants.STATUS_AUDIT_ID)); + consentStatusAuditRecord.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); + consentStatusAuditRecord + .setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); + consentStatusAuditRecord.setActionBy(resultSet.getString(ConsentMgtDAOConstants.ACTION_BY)); + consentStatusAuditRecord.setActionTime(resultSet.getLong(ConsentMgtDAOConstants.ACTION_TIME)); + consentStatusAuditRecord.setReason(resultSet.getString(ConsentMgtDAOConstants.REASON)); + consentStatusAuditRecord + .setPreviousStatus(resultSet.getString(ConsentMgtDAOConstants.PREVIOUS_STATUS)); + retrievedAuditRecords.add(consentStatusAuditRecord); + } + } else { + log.error("No records are found for the provided inputs"); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + } catch (SQLException e) { + log.error("Error occurred while reading consent status audit records", e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + } + + log.debug("Retrieved the consent status audit records successfully"); + + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + } + return retrievedAuditRecords; + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(getConsentStatusAuditRecordsPrepStatement) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public ArrayList getConsentStatusAuditRecordsByConsentId(Connection connection, + ArrayList consentIDs, + Integer limit, Integer offset) + throws + ConsentDataRetrievalException { + + boolean shouldLimit = true; + boolean shouldOffset = true; + int parameterIndex = 0; + + // Don't limit if either of limit or offset is null + if (limit == null) { + shouldLimit = false; + } + if (offset == null) { + shouldOffset = false; + } + + ArrayList retrievedAuditRecords = new ArrayList<>(); + String constructedConditions = + ConsentManagementDAOUtil.constructConsentAuditRecordSearchPreparedStatement(consentIDs); + + String getConsentStatusAuditRecordsPrepStatement = + sqlStatements.getConsentStatusAuditRecordsByConsentIdsPreparedStatement(constructedConditions, + shouldLimit, shouldOffset); + + try (PreparedStatement getConsentStatusAuditRecordPreparedStmt = + connection.prepareStatement(getConsentStatusAuditRecordsPrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent status audit records"); + if (!CollectionUtils.isEmpty(consentIDs)) { + for (String consentId : consentIDs) { + parameterIndex++; + getConsentStatusAuditRecordPreparedStmt.setString(parameterIndex, consentId); + } + } + if (limit != null && offset != null) { + getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, + sqlStatements.isLimitBeforeThanOffset() ? limit : offset); + getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, + sqlStatements.isLimitBeforeThanOffset() ? offset : limit); + } else if (limit != null) { + getConsentStatusAuditRecordPreparedStmt.setInt(++parameterIndex, limit); + } + + try (ResultSet resultSet = getConsentStatusAuditRecordPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); + consentStatusAuditRecord + .setStatusAuditID(resultSet.getString(ConsentMgtDAOConstants.STATUS_AUDIT_ID)); + consentStatusAuditRecord.setConsentID(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); + consentStatusAuditRecord + .setCurrentStatus(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS)); + consentStatusAuditRecord.setActionBy(resultSet.getString(ConsentMgtDAOConstants.ACTION_BY)); + consentStatusAuditRecord.setActionTime(resultSet.getLong(ConsentMgtDAOConstants.ACTION_TIME)); + consentStatusAuditRecord.setReason(resultSet.getString(ConsentMgtDAOConstants.REASON)); + consentStatusAuditRecord + .setPreviousStatus(resultSet.getString(ConsentMgtDAOConstants.PREVIOUS_STATUS)); + retrievedAuditRecords.add(consentStatusAuditRecord); + } + } + } catch (SQLException e) { + log.error("Error occurred while reading consent status audit records", e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + } + + log.debug("Retrieved the consent status audit records successfully"); + + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.AUDIT_RECORDS_RETRIEVE_ERROR_MSG, e); + } + return retrievedAuditRecords; + } + + @Override + public boolean storeConsentAmendmentHistory(Connection connection, String historyID, long timestamp, + String recordID, String consentDataType, + String changedAttributesJsonString, String amendmentReason) + throws + ConsentDataInsertionException { + + String tableID = ConsentManagementDAOUtil.generateConsentTableId(consentDataType.replaceAll("[\r\n]", "")); + + + int result; + String insertConsentHistoryPrepStatement = sqlStatements.getInsertConsentHistoryPreparedStatement(); + + try (PreparedStatement insertConsentHistoryPreparedStmt = + connection.prepareStatement(insertConsentHistoryPrepStatement)) { + + if (log.isDebugEnabled()) { + log.debug(String.format("Setting parameters to prepared statement to store consent amendment history " + + "of %s", consentDataType.replaceAll("[\r\n]", ""))); + } + + insertConsentHistoryPreparedStmt.setString(1, tableID); + insertConsentHistoryPreparedStmt.setString(2, recordID); + insertConsentHistoryPreparedStmt.setString(3, historyID); + insertConsentHistoryPreparedStmt.setString(4, changedAttributesJsonString); + insertConsentHistoryPreparedStmt.setString(5, amendmentReason); + insertConsentHistoryPreparedStmt.setLong(6, timestamp); + + // with result, we can determine whether the updating was successful or not + result = insertConsentHistoryPreparedStmt.executeUpdate(); + } catch (SQLException e) { + log.error("Error while storing consent amendment history", e); + throw new ConsentDataInsertionException(String.format("Error while storing consent amendment history of" + + " %s for record ID: %s", consentDataType, recordID), e); + } + + // Confirm that the data are inserted successfully + if (result > 0) { + return true; + } else { + log.error("Failed to store consent amendment history data."); + throw new ConsentDataInsertionException("Failed to store consent amendment history data properly."); + } + } + + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(getConsentHistoryPrepStatement) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public Map retrieveConsentAmendmentHistory(Connection connection, + List recordIDsList, + String consentID) throws + ConsentDataRetrievalException { + + String whereClause = ConsentManagementDAOUtil.constructConsentHistoryPreparedStatement(recordIDsList.size()); + String getConsentHistoryPrepStatement = sqlStatements.getGetConsentHistoryPreparedStatement(whereClause); + + try (PreparedStatement getConsentHistoryPreparedStmt = + connection.prepareStatement(getConsentHistoryPrepStatement)) { + + log.debug("Setting parameters to prepared statement to retrieve consent history data"); + + for (int count = 1; count <= recordIDsList.size(); count++) { + getConsentHistoryPreparedStmt.setString(count, recordIDsList.get(count - 1)); + } + + + try (ResultSet resultSet = getConsentHistoryPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + return ConsentManagementDAOUtil.constructConsentHistoryRetrievalResult(consentID, resultSet); + } else { + log.error(String.format("No records are found for consent ID : %s", + consentID.replaceAll("[\r\n]", ""))); + return new HashMap<>(); + } + } catch (SQLException e) { + log.error("Error occurred while reading consent amendment history", e); + throw new ConsentDataRetrievalException(String.format("Error occurred while retrieving consent " + + "amendment history for consent ID : %s", consentID), e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG, e); + throw new ConsentDataRetrievalException( + ConsentMgtDAOConstants.CONSENT_AMENDMENT_HISTORY_RETRIEVE_ERROR_MSG, e); + } + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(expiringConsentStatement) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public ArrayList getExpiringConsents(Connection connection, String orgID, + String statusesEligibleForExpiration) + throws + ConsentDataRetrievalException { + + List statusesEligibleForExpirationList = Arrays.stream(statusesEligibleForExpiration + .split(",")).filter(status -> !status.isEmpty()) + .collect(Collectors.toList()); + + String statusesEligibleForExpirationCondition = ConsentManagementDAOUtil + .constructStatusesEligibleForExpirationCondition(statusesEligibleForExpirationList); + String expiringConsentStatement = sqlStatements.getSearchExpiringConsentPreparedStatement( + statusesEligibleForExpirationCondition); + + try (PreparedStatement preparedStatement = + connection.prepareStatement(expiringConsentStatement)) { + + log.debug("Setting parameters to prepared statement to fetch consents eligible for expiration"); + + ArrayList consentIdList = new ArrayList<>(); + + // populate prepared statement + int parameterIndex = 0; + preparedStatement.setString(++parameterIndex, ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE); + for (String status : statusesEligibleForExpirationList) { + preparedStatement.setString(++parameterIndex, status); + } + + try (ResultSet resultSet = preparedStatement.executeQuery()) { + if (resultSet.isBeforeFirst()) { + while (resultSet.next()) { + consentIdList.add(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID)); + } + } else { + log.debug("No consents found for expiration check eligibility."); + } + if (!consentIdList.isEmpty()) { + return searchConsents(connection, null, consentIdList, null, null, null, + null, null, null, null, null); + } else { + return new ArrayList<>(); + } + + } catch (SQLException e) { + log.error("Error occurred while searching consents eligible for expiration", e); + throw new ConsentDataRetrievalException("Error occurred while searching consents" + + " eligible for expiration", e); + } + } catch (SQLException e) { + log.error("Error while searching consents eligible for expiration", e); + throw new ConsentDataRetrievalException("Error while updating searching consents eligible for" + + " expiration", e); + } + } + + void validateAndSetSearchConditions(ArrayList orgIDs, + Map> applicableConditionsMap, + ArrayList consentIDs, ArrayList clientIDs, + ArrayList consentTypes, ArrayList consentStatuses) { + + log.debug("Validate applicable search conditions"); + + if (CollectionUtils.isNotEmpty(consentIDs)) { + applicableConditionsMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), + consentIDs); + } + if (CollectionUtils.isNotEmpty(clientIDs)) { + applicableConditionsMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), + clientIDs); + } + if (CollectionUtils.isNotEmpty(consentTypes)) { + applicableConditionsMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), + consentTypes); + } + if (CollectionUtils.isNotEmpty(consentStatuses)) { + applicableConditionsMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), + consentStatuses); + } + if (CollectionUtils.isNotEmpty(orgIDs)) { + applicableConditionsMap.put(ConsentMgtDAOConstants.COLUMNS_MAP.get(ConsentMgtDAOConstants.ORG_ID), + orgIDs); + } + } + + ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) + throws + SQLException { + + ArrayList detailedConsentResources = new ArrayList<>(); + + while (resultSet.next()) { + + Map consentAttributesMap = new HashMap<>(); + ArrayList consentMappingResources = new ArrayList<>(); + ArrayList authorizationResources = new ArrayList<>(); + DetailedConsentResource detailedConsentResource = ConsentManagementDAOUtil + .setConsentDataToDetailedConsentResource(resultSet); + + // Set consent attributes to map if available + if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && + StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY)) + && StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE))) { + // fetch attribute keys and values from group_concat + String[] attributeKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); + String[] attributeValues = resultSet + .getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); + // check if all attribute keys has values + if (attributeKeys.length == attributeValues.length) { + for (int index = 0; index < attributeKeys.length; index++) { + consentAttributesMap.put(attributeKeys[index], attributeValues[index]); + } + } + } + // Set authorization data + setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, + detailedConsentResource.getConsentID()); + // Set consent account mapping data if available + setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); + + detailedConsentResource.setConsentAttributes(consentAttributesMap); + detailedConsentResource.setAuthorizationResources(authorizationResources); + detailedConsentResource.setConsentMappingResources(consentMappingResources); + + detailedConsentResources.add(detailedConsentResource); + + } + return detailedConsentResources; + } + + protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList + authorizationResources, + ResultSet resultSet, String consentId) + throws + SQLException { + + //identify duplicate auth data + Set authIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; + String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; + String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? + resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; + String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { + if (!authIdSet.contains(authIds[index])) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + authIdSet.add(authIds[index]); + authorizationResource.setAuthorizationID(authIds[index]); + authorizationResource.setConsentID(consentId); + if (authTypes != null && authTypes.length > index) { + authorizationResource.setAuthorizationType(authTypes[index]); + } + if (authStatues != null && authStatues.length > index) { + authorizationResource.setAuthorizationStatus(authStatues[index]); + } + if (updatedTimes != null && updatedTimes.length > index) { + authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); + } + if (userIds != null && userIds.length > index) { + authorizationResource.setUserID(userIds[index]); + } + authorizationResources.add(authorizationResource); + } + } + + } + + protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, + ResultSet resultSet) throws + SQLException { + + //identify duplicate mappingIds + Set mappingIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + + String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] resources = resultSet.getString(ConsentMgtDAOConstants.RESOURCE) != null ? + resultSet.getString(ConsentMgtDAOConstants.RESOURCE).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { + if (!mappingIdSet.contains(mappingIds[index])) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + if (authIds != null && authIds.length > index) { + consentMappingResource.setAuthorizationID(authIds[index]); + } + consentMappingResource.setMappingID(mappingIds[index]); + + if (mappingStatues != null && mappingStatues.length > index) { + consentMappingResource.setMappingStatus(mappingStatues[index]); + } + if (resources != null && resources.length > index) { + consentMappingResource.setPermission(resources[index]); + } + consentMappingResources.add(consentMappingResource); + mappingIdSet.add(mappingIds[index]); + } + } + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java new file mode 100644 index 000000000..b286e3ac6 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/MssqlConsentCoreDAOImpl.java @@ -0,0 +1,367 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtMssqlDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.ConsentManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * DAO implementation for MSSQL specific methods. + */ +public class MssqlConsentCoreDAOImpl extends ConsentCoreDAOImpl { + + private static final Log log = LogFactory.getLog(MssqlConsentCoreDAOImpl.class); + + private static final String GROUP_BY_SEPARATOR = "\\|\\|"; + static final Map COLUMNS_MAP = new HashMap() { + { + put(ConsentMgtDAOConstants.CONSENT_IDS, "OBC.CONSENT_ID"); + put(ConsentMgtDAOConstants.CLIENT_IDS, "OBC.CLIENT_ID"); + put(ConsentMgtDAOConstants.CONSENT_TYPES, "OBC.CONSENT_TYPE"); + put(ConsentMgtDAOConstants.CONSENT_STATUSES, "OBC.CURRENT_STATUS"); + put(ConsentMgtDAOConstants.USER_IDS, "OCAR.USER_ID"); + } + }; + + public MssqlConsentCoreDAOImpl(ConsentMgtMssqlDBQueries sqlStatements) { + + super(sqlStatements); + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(searchConsentsPreparedStatement, + // ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public ArrayList searchConsents(Connection connection, + String orgID, ArrayList consentIDs, + ArrayList clientIDs, + ArrayList consentTypes, + ArrayList consentStatuses, + ArrayList userIDs, Long fromTime, + Long toTime, Integer limit, Integer offset) + throws ConsentDataRetrievalException { + + boolean shouldLimit = true; + boolean shouldOffset = true; + int parameterIndex = 0; + Map> applicableConditionsMap = new HashMap<>(); + + validateAndSetSearchConditions(applicableConditionsMap, consentIDs, clientIDs, consentTypes, consentStatuses); + + if (limit == null) { + shouldLimit = false; + } + if (offset == null) { + shouldOffset = false; + } + + // logic to set the prepared statement + String constructedConditions = ConsentManagementDAOUtil + .constructConsentSearchPreparedStatement(applicableConditionsMap); + + String userIDFilterCondition = ""; + Map> userIdMap = new HashMap<>(); + if (CollectionUtils.isNotEmpty(userIDs)) { + userIdMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); + userIDFilterCondition = ConsentManagementDAOUtil.constructUserIdListFilterCondition(userIdMap); + } + String searchConsentsPreparedStatement = + sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, + shouldOffset, userIDFilterCondition); + + try (PreparedStatement searchConsentsPreparedStmt = + connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_READ_ONLY)) { + + /* Since we don't know the order of the set condition clauses, have to determine the order of them to set + the actual values to the prepared statement */ + Map> orderedParamsMap = ConsentManagementDAOUtil + .determineOrderOfParamsToSet(constructedConditions, applicableConditionsMap, COLUMNS_MAP); + + log.debug("Setting parameters to prepared statement to search consents"); + + //determine order of user Ids to set + if (CollectionUtils.isNotEmpty(userIDs)) { + Map> orderedUserIdsMap = ConsentManagementDAOUtil + .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, COLUMNS_MAP); + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedUserIdsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + } + + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedParamsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + + if (fromTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (toTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (offset != null && limit != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, offset); + } + if (limit != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, limit); + } + + ArrayList detailedConsentResources = new ArrayList<>(); + + try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + int resultSetSize = ConsentManagementDAOUtil.getResultSetSize(resultSet); + detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); + } + return detailedConsentResources; + } catch (SQLException e) { + log.error("Error occurred while searching detailed consent resources", e); + throw new ConsentDataRetrievalException("Error occurred while searching detailed " + + "consent resources", e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); + } + } + + ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) + throws SQLException { + + ArrayList detailedConsentResources = new ArrayList<>(); + + while (resultSet.next()) { + + Map consentAttributesMap = new HashMap<>(); + ArrayList consentMappingResources = new ArrayList<>(); + ArrayList authorizationResources = new ArrayList<>(); + DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); + + setConsentDataToDetailedConsentInSearchResponse(resultSet, detailedConsentResource); + + // Set consent attributes to map if available + if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && + StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY))) { + // fetch attribute keys and values from group_concat + String[] attKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); + String[] attValues = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); + // check if all attribute keys has values + if (attKeys.length == attValues.length) { + for (int index = 0; index < attKeys.length; index++) { + if (!attKeys[index].isEmpty()) { + consentAttributesMap.put(attKeys[index], attValues[index]); + } + } + } + } + // Set authorization data + setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, + detailedConsentResource.getConsentID()); + // Set consent account mapping data if available + setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); + + detailedConsentResource.setConsentAttributes(consentAttributesMap); + detailedConsentResource.setAuthorizationResources(authorizationResources); + detailedConsentResource.setConsentMappingResources(consentMappingResources); + + detailedConsentResources.add(detailedConsentResource); + + } + return detailedConsentResources; + } + + void setConsentDataToDetailedConsentInSearchResponse(ResultSet resultSet, + DetailedConsentResource detailedConsentResource) + throws SQLException { + + Optional consentId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional clientId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional receipt = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.RECEIPT) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional createdTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_CREATED_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional consentUpdatedTime = Arrays.stream( + resultSet.getString(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional consentType = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional currentStatus = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional frequency = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_FREQUENCY) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional validityTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.VALIDITY_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional recurringIndicator = Arrays.stream( + resultSet.getString(ConsentMgtDAOConstants.RECURRING_INDICATOR) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + + if (consentId.isPresent() && clientId.isPresent()) { + detailedConsentResource.setConsentID(consentId.get()); + detailedConsentResource.setClientID(clientId.get()); + } else { + throw new SQLException("CLIENT_ID and CONSENT_ID could not be null."); + } + receipt.ifPresent(detailedConsentResource::setReceipt); + consentType.ifPresent(detailedConsentResource::setConsentType); + currentStatus.ifPresent(detailedConsentResource::setCurrentStatus); + createdTime.ifPresent(e -> detailedConsentResource.setCreatedTime(Long.parseLong(e))); + consentUpdatedTime.ifPresent(e -> detailedConsentResource.setUpdatedTime(Long.parseLong(e))); + frequency.ifPresent(e -> detailedConsentResource.setConsentFrequency(Integer.parseInt(e))); + validityTime.ifPresent(e -> detailedConsentResource.setValidityPeriod(Long.parseLong(e))); + recurringIndicator.ifPresent(e -> detailedConsentResource.setRecurringIndicator(Integer.parseInt(e) != 0)); + } + + protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList + authorizationResources, + ResultSet resultSet, String consentId) + throws SQLException { + + //identify duplicate auth data + Set authIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; + String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; + String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? + resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; + String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { + if (!authIdSet.contains(authIds[index])) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + authIdSet.add(authIds[index]); + authorizationResource.setAuthorizationID(authIds[index]); + authorizationResource.setConsentID(consentId); + if (authTypes != null && authTypes.length > index) { + authorizationResource.setAuthorizationType(authTypes[index]); + } + if (authStatues != null && authStatues.length > index) { + authorizationResource.setAuthorizationStatus(authStatues[index]); + } + if (updatedTimes != null && updatedTimes.length > index) { + authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); + } + if (userIds != null && userIds.length > index) { + authorizationResource.setUserID(userIds[index]); + } + authorizationResources.add(authorizationResource); + } + } + + } + + protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, + ResultSet resultSet) throws SQLException { + + //identify duplicate mappingIds + Set mappingIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + String[] accountIds = resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID).split(GROUP_BY_SEPARATOR) : null; + String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] permissions = resultSet.getString(ConsentMgtDAOConstants.PERMISSION) != null ? + resultSet.getString(ConsentMgtDAOConstants.PERMISSION).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { + if (!mappingIdSet.contains(mappingIds[index])) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + if (authIds != null && authIds.length > index) { + consentMappingResource.setAuthorizationID(authIds[index]); + } + consentMappingResource.setMappingID(mappingIds[index]); + if (accountIds != null && accountIds.length > index) { + consentMappingResource.setAccountID(accountIds[index]); + } + if (mappingStatues != null && mappingStatues.length > index) { + consentMappingResource.setMappingStatus(mappingStatues[index]); + } + if (permissions != null && permissions.length > index) { + consentMappingResource.setPermission(permissions[index]); + } + consentMappingResources.add(consentMappingResource); + mappingIdSet.add(mappingIds[index]); + } + } + + } + + void validateAndSetSearchConditions(Map> applicableConditionsMap, + ArrayList consentIDs, ArrayList clientIDs, + ArrayList consentTypes, ArrayList consentStatuses) { + + log.debug("Validate applicable search conditions"); + + if (CollectionUtils.isNotEmpty(consentIDs)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), consentIDs); + } + if (CollectionUtils.isNotEmpty(clientIDs)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), clientIDs); + } + if (CollectionUtils.isNotEmpty(consentTypes)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), consentTypes); + } + if (CollectionUtils.isNotEmpty(consentStatuses)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), consentStatuses); + } + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java new file mode 100644 index 000000000..fa629346b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/OracleConsentCoreDAOImpl.java @@ -0,0 +1,366 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtOracleDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.ConsentManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * DAO implementation for Oracle specific methods. + */ +public class OracleConsentCoreDAOImpl extends ConsentCoreDAOImpl { + + private static final Log log = LogFactory.getLog(OracleConsentCoreDAOImpl.class); + + private static final String GROUP_BY_SEPARATOR = "\\|\\|"; + static final Map COLUMNS_MAP = new HashMap() { + { + put(ConsentMgtDAOConstants.CONSENT_IDS, "OBC.CONSENT_ID"); + put(ConsentMgtDAOConstants.CLIENT_IDS, "OBC.CLIENT_ID"); + put(ConsentMgtDAOConstants.CONSENT_TYPES, "OBC.CONSENT_TYPE"); + put(ConsentMgtDAOConstants.CONSENT_STATUSES, "OBC.CURRENT_STATUS"); + put(ConsentMgtDAOConstants.USER_IDS, "OCAR.USER_ID"); + } + }; + + public OracleConsentCoreDAOImpl(ConsentMgtOracleDBQueries sqlStatements) { + + super(sqlStatements); + } + + @Override + @SuppressFBWarnings("SQL_INJECTION_JDBC") + // Suppressed content - connection.prepareStatement(searchConsentsPreparedStatement, + // ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE) + // Suppression reason - False Positive : Cannot bind variables separately as the query is complex + // Suppressed warning count - 1 + public ArrayList searchConsents(Connection connection, + String orgID, ArrayList consentIDs, + ArrayList clientIDs, + ArrayList consentTypes, + ArrayList consentStatuses, + ArrayList userIDs, Long fromTime, + Long toTime, Integer limit, Integer offset) + throws ConsentDataRetrievalException { + + boolean shouldLimit = true; + boolean shouldOffset = true; + int parameterIndex = 0; + Map> applicableConditionsMap = new HashMap<>(); + + validateAndSetSearchConditions(applicableConditionsMap, consentIDs, clientIDs, consentTypes, consentStatuses); + + if (limit == null) { + shouldLimit = false; + } + if (offset == null) { + shouldOffset = false; + } + + // logic to set the prepared statement + String constructedConditions = ConsentManagementDAOUtil + .constructConsentSearchPreparedStatement(applicableConditionsMap); + + String userIDFilterCondition = ""; + Map> userIdMap = new HashMap<>(); + if (CollectionUtils.isNotEmpty(userIDs)) { + userIdMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.USER_IDS), userIDs); + userIDFilterCondition = ConsentManagementDAOUtil.constructUserIdListFilterCondition(userIdMap); + } + String searchConsentsPreparedStatement = + sqlStatements.getSearchConsentsPreparedStatement(constructedConditions, shouldLimit, + shouldOffset, userIDFilterCondition); + + try (PreparedStatement searchConsentsPreparedStmt = + connection.prepareStatement(searchConsentsPreparedStatement, ResultSet.TYPE_SCROLL_INSENSITIVE, + ResultSet.CONCUR_UPDATABLE)) { + + //determine order of user Ids to set + if (CollectionUtils.isNotEmpty(userIDs)) { + Map> orderedUserIdsMap = ConsentManagementDAOUtil + .determineOrderOfParamsToSet(userIDFilterCondition, userIdMap, COLUMNS_MAP); + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedUserIdsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + } + + /* Since we don't know the order of the set condition clauses, have to determine the order of them to set + the actual values to the prepared statement */ + Map> orderedParamsMap = ConsentManagementDAOUtil + .determineOrderOfParamsToSet(constructedConditions, applicableConditionsMap, COLUMNS_MAP); + parameterIndex = ConsentManagementDAOUtil.setDynamicConsentSearchParameters(searchConsentsPreparedStmt, + orderedParamsMap, ++parameterIndex); + parameterIndex = parameterIndex - 1; + + log.debug("Setting parameters to prepared statement to search consents"); + + if (fromTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, fromTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (toTime != null) { + searchConsentsPreparedStmt.setLong(++parameterIndex, toTime); + } else { + searchConsentsPreparedStmt.setNull(++parameterIndex, Types.BIGINT); + } + + if (offset != null && limit != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, offset); + } + if (limit != null) { + searchConsentsPreparedStmt.setInt(++parameterIndex, limit); + } + + ArrayList detailedConsentResources = new ArrayList<>(); + + try (ResultSet resultSet = searchConsentsPreparedStmt.executeQuery()) { + if (resultSet.isBeforeFirst()) { + int resultSetSize = ConsentManagementDAOUtil.getResultSetSize(resultSet); + detailedConsentResources = constructDetailedConsentsSearchResult(resultSet, resultSetSize); + } + return detailedConsentResources; + } catch (SQLException e) { + log.error("Error occurred while searching detailed consent resources", e); + throw new ConsentDataRetrievalException("Error occurred while searching detailed " + + "consent resources", e); + } + } catch (SQLException e) { + log.error(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); + throw new ConsentDataRetrievalException(ConsentMgtDAOConstants.CONSENT_SEARCH_ERROR_MSG, e); + } + } + + ArrayList constructDetailedConsentsSearchResult(ResultSet resultSet, int resultSetSize) + throws SQLException { + + ArrayList detailedConsentResources = new ArrayList<>(); + + while (resultSet.next()) { + + Map consentAttributesMap = new HashMap<>(); + ArrayList consentMappingResources = new ArrayList<>(); + ArrayList authorizationResources = new ArrayList<>(); + DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); + + setConsentDataToDetailedConsentInSearchResponse(resultSet, detailedConsentResource); + + // Set consent attributes to map if available + if (resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) != null && + StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY) + .replaceAll(GROUP_BY_SEPARATOR, ""))) { + // fetch attribute keys and values from group_concat + String[] attKeys = resultSet.getString(ConsentMgtDAOConstants.ATT_KEY).split(GROUP_BY_SEPARATOR); + String[] attValues = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE).split(GROUP_BY_SEPARATOR); + // check if all attribute keys has values + if (attKeys.length == attValues.length) { + for (int index = 0; index < attKeys.length; index++) { + if (!attKeys[index].isEmpty()) { + consentAttributesMap.put(attKeys[index], attValues[index]); + } + } + } + } + // Set authorization data + setAuthorizationDataInResponseForGroupedQuery(authorizationResources, resultSet, + detailedConsentResource.getConsentID()); + // Set consent account mapping data if available + setAccountConsentMappingDataInResponse(consentMappingResources, resultSet); + + detailedConsentResource.setConsentAttributes(consentAttributesMap); + detailedConsentResource.setAuthorizationResources(authorizationResources); + detailedConsentResource.setConsentMappingResources(consentMappingResources); + + detailedConsentResources.add(detailedConsentResource); + + } + return detailedConsentResources; + } + + void setConsentDataToDetailedConsentInSearchResponse(ResultSet resultSet, + DetailedConsentResource detailedConsentResource) + throws SQLException { + + Optional consentId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional clientId = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional receipt = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.RECEIPT) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional createdTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_CREATED_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional consentUpdatedTime = Arrays.stream( + resultSet.getString(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional consentType = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional currentStatus = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional frequency = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.CONSENT_FREQUENCY) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional validityTime = Arrays.stream(resultSet.getString(ConsentMgtDAOConstants.VALIDITY_TIME) + .split(GROUP_BY_SEPARATOR)).distinct().findFirst(); + Optional recurringIndicator = + Optional.of(resultSet.getBoolean(ConsentMgtDAOConstants.RECURRING_INDICATOR)); + + if (consentId.isPresent() && clientId.isPresent()) { + detailedConsentResource.setConsentID(consentId.get()); + detailedConsentResource.setClientID(clientId.get()); + } else { + throw new SQLException("CLIENT_ID and CONSENT_ID could not be null."); + } + receipt.ifPresent(detailedConsentResource::setReceipt); + consentType.ifPresent(detailedConsentResource::setConsentType); + currentStatus.ifPresent(detailedConsentResource::setCurrentStatus); + createdTime.ifPresent(e -> detailedConsentResource.setCreatedTime(Long.parseLong(e))); + consentUpdatedTime.ifPresent(e -> detailedConsentResource.setUpdatedTime(Long.parseLong(e))); + frequency.ifPresent(e -> detailedConsentResource.setConsentFrequency(Integer.parseInt(e))); + validityTime.ifPresent(e -> detailedConsentResource.setValidityPeriod(Long.parseLong(e))); + recurringIndicator.ifPresent(detailedConsentResource::setRecurringIndicator); + } + + protected void setAuthorizationDataInResponseForGroupedQuery(ArrayList + authorizationResources, + ResultSet resultSet, String consentId) + throws SQLException { + + //identify duplicate auth data + Set authIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_ID).split(GROUP_BY_SEPARATOR) : null; + String[] authTypes = resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE).split(GROUP_BY_SEPARATOR) : null; + String[] authStatues = resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] updatedTimes = resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME) != null ? + resultSet.getString(ConsentMgtDAOConstants.UPDATED_TIME).split(GROUP_BY_SEPARATOR) : null; + String[] userIds = resultSet.getString(ConsentMgtDAOConstants.USER_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.USER_ID).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (authIds != null ? authIds.length : 0); index++) { + if (!authIdSet.contains(authIds[index])) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + authIdSet.add(authIds[index]); + authorizationResource.setAuthorizationID(authIds[index]); + authorizationResource.setConsentID(consentId); + if (authTypes != null && authTypes.length > index) { + authorizationResource.setAuthorizationType(authTypes[index]); + } + if (authStatues != null && authStatues.length > index) { + authorizationResource.setAuthorizationStatus(authStatues[index]); + } + if (updatedTimes != null && updatedTimes.length > index) { + authorizationResource.setUpdatedTime(Long.parseLong(updatedTimes[index])); + } + if (userIds != null && userIds.length > index) { + authorizationResource.setUserID(userIds[index]); + } + authorizationResources.add(authorizationResource); + } + } + + } + + protected void setAccountConsentMappingDataInResponse(ArrayList consentMappingResources, + ResultSet resultSet) throws SQLException { + + //identify duplicate mappingIds + Set mappingIdSet = new HashSet<>(); + + // fetch values from group_concat + String[] authIds = resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.AUTH_MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + String[] mappingIds = resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID).split(GROUP_BY_SEPARATOR) : null; + String[] accountIds = resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID) != null ? + resultSet.getString(ConsentMgtDAOConstants.ACCOUNT_ID).split(GROUP_BY_SEPARATOR) : null; + String[] mappingStatues = resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) != null ? + resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS).split(GROUP_BY_SEPARATOR) : null; + String[] permissions = resultSet.getString(ConsentMgtDAOConstants.PERMISSION) != null ? + resultSet.getString(ConsentMgtDAOConstants.PERMISSION).split(GROUP_BY_SEPARATOR) : null; + + for (int index = 0; index < (mappingIds != null ? mappingIds.length : 0); index++) { + if (!mappingIdSet.contains(mappingIds[index])) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + if (authIds != null && authIds.length > index) { + consentMappingResource.setAuthorizationID(authIds[index]); + } + consentMappingResource.setMappingID(mappingIds[index]); + if (accountIds != null && accountIds.length > index) { + consentMappingResource.setAccountID(accountIds[index]); + } + if (mappingStatues != null && mappingStatues.length > index) { + consentMappingResource.setMappingStatus(mappingStatues[index]); + } + if (permissions != null && permissions.length > index) { + consentMappingResource.setPermission(permissions[index]); + } + consentMappingResources.add(consentMappingResource); + mappingIdSet.add(mappingIds[index]); + } + } + + } + + void validateAndSetSearchConditions(Map> applicableConditionsMap, + ArrayList consentIDs, ArrayList clientIDs, + ArrayList consentTypes, ArrayList consentStatuses) { + + log.debug("Validate applicable search conditions"); + + if (CollectionUtils.isNotEmpty(consentIDs)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_IDS), consentIDs); + } + if (CollectionUtils.isNotEmpty(clientIDs)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CLIENT_IDS), clientIDs); + } + if (CollectionUtils.isNotEmpty(consentTypes)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_TYPES), consentTypes); + } + if (CollectionUtils.isNotEmpty(consentStatuses)) { + applicableConditionsMap.put(COLUMNS_MAP.get(ConsentMgtDAOConstants.CONSENT_STATUSES), consentStatuses); + } + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/internal/ConsentMgtDaoServiceComponent.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/internal/ConsentMgtDaoServiceComponent.java new file mode 100644 index 000000000..4a733b590 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/internal/ConsentMgtDaoServiceComponent.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; + +/** + * Consent Management Common Service Component. + */ +@Component(name = "org.wso2.financial.services.accelerator.consent.mgt.dao.internal.ConsentMgtDaoServiceComponent", + immediate = true) +public class ConsentMgtDaoServiceComponent { + + private static final Log log = LogFactory.getLog(ConsentMgtDaoServiceComponent.class); + + @Activate + protected void activate(ComponentContext context) { + + log.debug("Consent Management DAO is registered successfully."); + } + + @Deactivate + protected void deactivate(ComponentContext context) { + + log.debug("Consent Management DAO is deactivated"); + } + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/AuthorizationResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/AuthorizationResource.java new file mode 100644 index 000000000..ed023cf07 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/AuthorizationResource.java @@ -0,0 +1,118 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import java.util.ArrayList; + +/** + * Model for the Authorization resource. + */ +public class AuthorizationResource { + + private String authorizationID; + private String consentID; + private String userID; + private String authorizationStatus; + private String authorizationType; + private long updatedTime; + private ArrayList consentMappingResource; + + public AuthorizationResource() { + + } + + public AuthorizationResource(String consentID, String userID, String authorizationStatus, + String authorizationType, long updatedTime) { + this.consentID = consentID; + this.userID = userID; + this.authorizationStatus = authorizationStatus; + this.authorizationType = authorizationType; + this.updatedTime = updatedTime; + + } + public String getAuthorizationID() { + + return authorizationID; + } + + public String getAuthorizationType() { + + return authorizationType; + } + + public void setAuthorizationType(String authorizationType) { + + this.authorizationType = authorizationType; + } + + public void setAuthorizationID(String authorizationID) { + + this.authorizationID = authorizationID; + } + + public String getConsentID() { + + return consentID; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public String getUserID() { + + return userID; + } + + public void setUserID(String userID) { + + this.userID = userID; + } + + public String getAuthorizationStatus() { + + return authorizationStatus; + } + + public void setAuthorizationStatus(String authorizationStatus) { + + this.authorizationStatus = authorizationStatus; + } + + public long getUpdatedTime() { + + return updatedTime; + } + + public void setUpdatedTime(long updatedTime) { + + this.updatedTime = updatedTime; + } + + public ArrayList getConsentMappingResource() { + return consentMappingResource; + } + + public void setConsentMappingResource( + ArrayList consentMappingResource) { + this.consentMappingResource = consentMappingResource; + } + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentAttributes.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentAttributes.java new file mode 100644 index 000000000..aab5538ae --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentAttributes.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import java.util.Map; + +/** + * Model for consent attributes. + */ +public class ConsentAttributes { + + private String consentID; + private Map consentAttributes; + + public ConsentAttributes(){ + + } + + public ConsentAttributes(String consentID, Map consentAttributes) { + this.consentID = consentID; + this.consentAttributes = consentAttributes; + } + + public String getConsentID() { + + return consentID; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public Map getConsentAttributes() { + + return consentAttributes; + } + + public void setConsentAttributes(Map consentAttributes) { + + this.consentAttributes = consentAttributes; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentFile.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentFile.java new file mode 100644 index 000000000..0bc836712 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentFile.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +/** + * Model for the consent file. + */ +public class ConsentFile { + + private String consentID; + private String consentFile; + + public ConsentFile() { + + } + + public ConsentFile(String consentID, String consentFile) { + this.consentID = consentID; + this.consentFile = consentFile; + } + + public String getConsentID() { + + return consentID; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public String getConsentFile() { + + return consentFile; + } + + public void setConsentFile(String consentFile) { + + this.consentFile = consentFile; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java new file mode 100644 index 000000000..77070aa76 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentHistoryResource.java @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import java.util.HashMap; +import java.util.Map; + +/** + * Model for the consent history resource. + */ +public class ConsentHistoryResource { + + private String historyID; + private String consentID; + private long timestamp; + private String reason; + private DetailedConsentResource detailedConsentResource; + private Map changedAttributesJsonDataMap; + + public ConsentHistoryResource() { + + } + + public ConsentHistoryResource(String consentID, String historyID) { + + this.consentID = consentID; + this.historyID = historyID; + this.changedAttributesJsonDataMap = new HashMap(); + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public DetailedConsentResource getDetailedConsentResource() { + return detailedConsentResource; + } + + public void setDetailedConsentResource(DetailedConsentResource detailedConsentResource) { + this.detailedConsentResource = detailedConsentResource; + } + + public Map getChangedAttributesJsonDataMap() { + return changedAttributesJsonDataMap; + } + + public void setChangedAttributesJsonDataMap(Map changedAttributesJsonDataMap) { + this.changedAttributesJsonDataMap = changedAttributesJsonDataMap; + } + + public String getConsentID() { + return consentID; + } + + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + public String getHistoryID() { + return historyID; + } + + public void setHistoryID(String historyID) { + this.historyID = historyID; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentMappingResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentMappingResource.java new file mode 100644 index 000000000..7053b1e37 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentMappingResource.java @@ -0,0 +1,110 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import net.minidev.json.JSONObject; + +/** + * Model for consent mapping resource. + */ +public class ConsentMappingResource { + + private String mappingID; + private String authorizationID; + private String accountID; + private String permission; + private String mappingStatus; + private JSONObject resource; + + public ConsentMappingResource() { + + } + + public ConsentMappingResource(String authorizationID, JSONObject resource, String mappingStatus) { + this.authorizationID = authorizationID; + this.resource = resource; + this.mappingStatus = mappingStatus; + } + + public ConsentMappingResource(String authorizationID, String accountID, String permission, + String mappingStatus) { + this.authorizationID = authorizationID; + this.accountID = accountID; + this.permission = permission; + this.mappingStatus = mappingStatus; + } + + public String getMappingID() { + + return mappingID; + } + + public void setMappingID(String mappingID) { + + this.mappingID = mappingID; + } + + public String getAuthorizationID() { + + return authorizationID; + } + + public void setAuthorizationID(String authorizationID) { + + this.authorizationID = authorizationID; + } + + public String getAccountID() { + + return accountID; + } + + public void setAccountID(String accountID) { + + this.accountID = accountID; + } + + public String getPermission() { + + return permission; + } + + public void setPermission(String permission) { + + this.permission = permission; + } + + public String getMappingStatus() { + + return mappingStatus; + } + + public void setMappingStatus(String mappingStatus) { + + this.mappingStatus = mappingStatus; + } + + public JSONObject getResource() { + return resource; + } + + public void setResource(JSONObject resource) { + this.resource = resource; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentResource.java new file mode 100644 index 000000000..065939da0 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentResource.java @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import java.util.Map; + +/** + * Model for the consent resource. + */ +public class ConsentResource { + + private String orgID; + private String consentID; + private String clientID; + private String receipt; + private String consentType; + private int consentFrequency; + private long validityPeriod; + private boolean recurringIndicator; + private String currentStatus; + private long createdTime; + private long updatedTime; + + public ConsentResource() { + } + + public ConsentResource(String orgId, String clientID, String receipt, String consentType, String currentStatus) { + this.orgID = orgId; + this.clientID = clientID; + this.receipt = receipt; + this.consentType = consentType; + this.currentStatus = currentStatus; + } + + public ConsentResource(String orgID, String consentID, String clientID, String receipt, String consentType, + int consentFrequency, long validityPeriod, boolean recurringIndicator, + String currentStatus, long createdTime, long updatedTime) { + this.orgID = orgID; + this.consentID = consentID; + this.clientID = clientID; + this.receipt = receipt; + this.consentType = consentType; + this.consentFrequency = consentFrequency; + this.validityPeriod = validityPeriod; + this.recurringIndicator = recurringIndicator; + this.currentStatus = currentStatus; + this.createdTime = createdTime; + this.updatedTime = updatedTime; + } + + private Map consentAttributes; + + public long getUpdatedTime() { + + return updatedTime; + } + + public void setUpdatedTime(long updatedTime) { + + this.updatedTime = updatedTime; + } + + public Map getConsentAttributes() { + + return consentAttributes; + } + + public void setConsentAttributes(Map consentAttributes) { + + this.consentAttributes = consentAttributes; + } + + public String getConsentID() { + + return consentID; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public String getOrgID() { + return orgID; + } + + public void setOrgID(String orgID) { + this.orgID = orgID; + } + + public String getClientID() { + + return clientID; + } + + public void setClientID(String clientID) { + + this.clientID = clientID; + } + + public String getReceipt() { + + return receipt; + } + + public void setReceipt(String receipt) { + + this.receipt = receipt; + } + + public String getConsentType() { + + return consentType; + } + + public void setConsentType(String consentType) { + + this.consentType = consentType; + } + + public int getConsentFrequency() { + + return consentFrequency; + } + + public void setConsentFrequency(int consentFrequency) { + + this.consentFrequency = consentFrequency; + } + + public long getValidityPeriod() { + + return validityPeriod; + } + + public void setValidityPeriod(long validityPeriod) { + + this.validityPeriod = validityPeriod; + } + + public boolean isRecurringIndicator() { + + return recurringIndicator; + } + + public void setRecurringIndicator(boolean recurringIndicator) { + + this.recurringIndicator = recurringIndicator; + } + + public String getCurrentStatus() { + + return currentStatus; + } + + public void setCurrentStatus(String currentStatus) { + + this.currentStatus = currentStatus; + } + + public long getCreatedTime() { + + return createdTime; + } + + public void setCreatedTime(long createdTime) { + + this.createdTime = createdTime; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java new file mode 100644 index 000000000..35ad01e94 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/ConsentStatusAuditRecord.java @@ -0,0 +1,128 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +/** + * Model for consent status audit record resource. + */ +public class ConsentStatusAuditRecord { + + private String statusAuditID; + private String consentID; + private String currentStatus; + private long actionTime; + private String reason; + private String actionBy; + private String previousStatus; + + public ConsentStatusAuditRecord() { + + } + + public ConsentStatusAuditRecord(String statusAuditID, String consentID, String currentStatus, long actionTime, + String reason, String actionBy, String previousStatus) { + this.statusAuditID = statusAuditID; + this.consentID = consentID; + this.currentStatus = currentStatus; + this.actionTime = actionTime; + this.reason = reason; + this.actionBy = actionBy; + this.previousStatus = previousStatus; + } + + public ConsentStatusAuditRecord(String consentID, String currentStatus, long actionTime, + String reason, String actionBy, String previousStatus) { + this.consentID = consentID; + this.currentStatus = currentStatus; + this.actionTime = actionTime; + this.reason = reason; + this.actionBy = actionBy; + this.previousStatus = previousStatus; + } + + public String getStatusAuditID() { + + return statusAuditID; + } + + public void setStatusAuditID(String statusAuditID) { + + this.statusAuditID = statusAuditID; + } + + public String getConsentID() { + + return consentID; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public String getCurrentStatus() { + + return currentStatus; + } + + public void setCurrentStatus(String currentStatus) { + + this.currentStatus = currentStatus; + } + + public long getActionTime() { + + return actionTime; + } + + public void setActionTime(long actionTime) { + + this.actionTime = actionTime; + } + + public String getReason() { + + return reason; + } + + public void setReason(String reason) { + + this.reason = reason; + } + + public String getActionBy() { + + return actionBy; + } + + public void setActionBy(String actionBy) { + + this.actionBy = actionBy; + } + + public String getPreviousStatus() { + + return previousStatus; + } + + public void setPreviousStatus(String previousStatus) { + + this.previousStatus = previousStatus; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/DetailedConsentResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/DetailedConsentResource.java new file mode 100644 index 000000000..da89a095e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/models/DetailedConsentResource.java @@ -0,0 +1,247 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.models; + +import java.util.ArrayList; +import java.util.Map; + +/** + * Model for Detailed Consent Resource. + */ +public class DetailedConsentResource { + + private String orgID; + private String consentID; + private String clientID; + private String receipt; + private String consentType; + private String currentStatus; + private int consentFrequency; + private long validityPeriod; + private long createdTime; + private long updatedTime; + private boolean recurringIndicator; + private Map consentAttributes; + private ArrayList authorizationResources; + private ArrayList consentMappingResources; + + public DetailedConsentResource() { + + } + + public DetailedConsentResource(String consentID, String clientID, String receipt, + String consentType, + String currentStatus, int consentFrequency, long validityPeriod, long createdTime, + long updatedTime, boolean recurringIndicator, + Map consentAttributes, + ArrayList authorizationResources, + ArrayList consentMappingResources) { + this.consentID = consentID; + this.clientID = clientID; + this.receipt = receipt; + this.consentType = consentType; + this.currentStatus = currentStatus; + this.consentFrequency = consentFrequency; + this.validityPeriod = validityPeriod; + this.createdTime = createdTime; + this.updatedTime = updatedTime; + this.recurringIndicator = recurringIndicator; + this.consentAttributes = consentAttributes; + this.authorizationResources = authorizationResources; + this.consentMappingResources = consentMappingResources; + + } + + public DetailedConsentResource(String orgID, String consentID, String clientID, String receipt, + String consentType, + String currentStatus, int consentFrequency, long validityPeriod, long createdTime, + long updatedTime, boolean recurringIndicator, + Map consentAttributes, + ArrayList authorizationResources, + ArrayList consentMappingResources) { + this.orgID = orgID; + this.consentID = consentID; + this.clientID = clientID; + this.receipt = receipt; + this.consentType = consentType; + this.currentStatus = currentStatus; + this.consentFrequency = consentFrequency; + this.validityPeriod = validityPeriod; + this.createdTime = createdTime; + this.updatedTime = updatedTime; + this.recurringIndicator = recurringIndicator; + this.consentAttributes = consentAttributes; + this.authorizationResources = authorizationResources; + this.consentMappingResources = consentMappingResources; + + } + + public long getUpdatedTime() { + + return updatedTime; + } + + public void setUpdatedTime(long updatedTime) { + + this.updatedTime = updatedTime; + } + + public String getConsentID() { + + return consentID; + } + + public String getOrgID() { + return orgID; + } + + public void setOrgID(String orgInfo) { + this.orgID = orgInfo; + } + + public void setConsentID(String consentID) { + + this.consentID = consentID; + } + + public String getClientID() { + + return clientID; + } + + + public void setClientID(String clientID) { + + this.clientID = clientID; + } + + public String getReceipt() { + + return receipt; + } + + public void setReceipt(String receipt) { + + this.receipt = receipt; + } + + public String getConsentType() { + + return consentType; + } + + public void setConsentType(String consentType) { + + this.consentType = consentType; + } + + public int getConsentFrequency() { + + return consentFrequency; + } + + public void setConsentFrequency(int consentFrequency) { + + this.consentFrequency = consentFrequency; + } + + public long getValidityPeriod() { + + return validityPeriod; + } + + public void setValidityPeriod(long validityPeriod) { + + this.validityPeriod = validityPeriod; + } + + public boolean isRecurringIndicator() { + + return recurringIndicator; + } + + public void setRecurringIndicator(boolean recurringIndicator) { + + this.recurringIndicator = recurringIndicator; + } + + public boolean getRecurringIndicator() { + + return recurringIndicator; + } + + public String getCurrentStatus() { + + return currentStatus; + } + + public void setCurrentStatus(String currentStatus) { + + this.currentStatus = currentStatus; + } + + public long getCreatedTime() { + + return createdTime; + } + + public void setCreatedTime(long createdTime) { + + this.createdTime = createdTime; + } + + public Map getConsentAttributes() { + + return consentAttributes; + } + + public void setConsentAttributes(Map consentAttributes) { + + this.consentAttributes = consentAttributes; + } + + public ArrayList getAuthorizationResources() { + + return authorizationResources; + } + + public void setAuthorizationResources(ArrayList authorizationResources) { + + this.authorizationResources = authorizationResources; + } + + public ArrayList getConsentMappingResources() { + + return consentMappingResources; + } + + public void setConsentMappingResources(ArrayList consentMappingResources) { + + this.consentMappingResources = consentMappingResources; + } + + public DetailedConsentResource clone() { + return new DetailedConsentResource(this.orgID, this.consentID, this.clientID, this.receipt, this.consentType, + this.currentStatus, this.consentFrequency, this.validityPeriod, this.createdTime, this.updatedTime, + this.recurringIndicator, this.consentAttributes, this.authorizationResources, + this.consentMappingResources); + + + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java new file mode 100644 index 000000000..e098c4465 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/ConsentStoreInitializer.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.persistence; + +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.impl.ConsentCoreDAOImpl; +import org.wso2.financial.services.accelerator.consent.mgt.dao.impl.MssqlConsentCoreDAOImpl; +import org.wso2.financial.services.accelerator.consent.mgt.dao.impl.OracleConsentCoreDAOImpl; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtMssqlDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtOracleDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtPostgresDBQueries; + +import java.sql.Connection; +import java.sql.SQLException; + +/** + * This class handles consent DAO layer initiation with the relevant SQL statements per database types. + */ +public class ConsentStoreInitializer { + + private static final String MYSQL = "MySQL"; + private static final String H2 = "H2"; + private static final String MICROSOFT = "Microsoft"; + private static final String MS_SQL = "MSSQL"; + private static final String POSTGRE = "PostgreSQL"; + private static final String ORACLE = "Oracle"; + private static ConsentCoreDAO consentCoreDAO = null; + + /** + * Return the DAO implementation initialized for the relevant database type. + * + * @return the dao implementation + * @throws ConsentMgtException thrown if an error occurs when getting the database connection + */ + public static synchronized ConsentCoreDAO getInitializedConsentCoreDAOImpl() throws + ConsentMgtException { + + if (consentCoreDAO == null) { + consentCoreDAO = getDaoInstance(); + } + return consentCoreDAO; + } + + private static ConsentCoreDAO getDaoInstance() + throws + ConsentMgtException { + + try { + Connection connection = JDBCPersistenceManager.getInstance().getDBConnection(); + String driverName = connection.getMetaData().getDriverName(); + + ConsentCoreDAO dao; + if (driverName.contains(MYSQL)) { + dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + } else if (driverName.contains(H2)) { + dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + } else if (driverName.contains(MS_SQL) || driverName.contains(MICROSOFT)) { + dao = new MssqlConsentCoreDAOImpl(new ConsentMgtMssqlDBQueries()); + } else if (driverName.contains(POSTGRE)) { + dao = new ConsentCoreDAOImpl(new ConsentMgtPostgresDBQueries()); + } else if (driverName.contains(ORACLE)) { + dao = new OracleConsentCoreDAOImpl(new ConsentMgtOracleDBQueries()); + } else { + throw new ConsentMgtException("Unhandled DB driver: " + driverName + " detected : "); + } + return dao; + } catch (SQLException e) { + throw new ConsentMgtException("Error while getting the database connection : ", e); + } + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/JDBCPersistenceManager.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/JDBCPersistenceManager.java new file mode 100644 index 000000000..4fafa5e0a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/persistence/JDBCPersistenceManager.java @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.persistence; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.apache.commons.lang3.StringUtils; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; + +import java.sql.Connection; +import java.sql.SQLException; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; + +/** + * This class is used for handling Financial Services consent data persistence in the JDBC Store. During the server + * start-up, it checks whether the database is created, if not it creates one. It reads the data source properties + * from the financial-services.xml. This is implemented as a singleton. An instance of this class can be obtained + * through JDBCPersistenceManager.getInstance() method. + */ +public final class JDBCPersistenceManager { + + private static volatile JDBCPersistenceManager instance; + private static volatile DataSource dataSource; +// private static final Log log = LogFactory.getLog(JDBCPersistenceManager.class); + + private JDBCPersistenceManager() throws + ConsentMgtException { + + initDataSource(); + } + + /** + * Get an instance of the JDBCPersistenceManager. It implements a double checked locking initialization. + * + * @return JDBCPersistenceManager instance + */ + public static synchronized JDBCPersistenceManager getInstance() throws + ConsentMgtException { + if (instance == null) { + synchronized (JDBCPersistenceManager.class) { + if (instance == null) { + instance = new JDBCPersistenceManager(); + } + } + } + return instance; + } + + /** + * Initialize the data source. + */ + @SuppressFBWarnings("LDAP_INJECTION") + // Suppressed content - context.lookup(dataSourceName) + // Suppression reason - False Positive : Since the dataSourceName is taken from the deployment.toml, it can be + // trusted + // Suppressed warning count - 1 + private void initDataSource() throws + ConsentMgtException { + + if (dataSource != null) { + return; + } + synchronized (JDBCPersistenceManager.class) { + try { +// String dataSourceName = FinancialServicesConfigParser.getInstance().getDataSourceName(); + String dataSourceName = "jdbc/WSO2FS_DB"; + if (StringUtils.isNotBlank(dataSourceName)) { + Context context = new InitialContext(); + dataSource = (DataSource) context.lookup("java:/comp/env/" + dataSourceName); + } else { + throw new ConsentMgtException("Persistence Manager configuration for Financial " + + "Services is not available in financial-services.xml file. Terminating the JDBC " + + "persistence manager initialization."); + } + } catch (NamingException e) { + throw new ConsentMgtException("Error when looking up the Consent Management Data Source.", + e); + } + } + } + + /** + * Returns an database connection for Consent Management data source. + * + * @return Database connection. + * @throws ConsentMgtException Exception occurred when getting the data source. + */ + public Connection getDBConnection() throws + ConsentMgtException { + + try { + Connection dbConnection = dataSource.getConnection(); + dbConnection.setAutoCommit(false); +// log.debug("Returning database connection for Consent Management data source"); + return dbConnection; + } catch (SQLException e) { + throw new ConsentMgtException("Error when getting a database connection object from the " + + "consent management data source.", e); + } + } + + /** + * Returns Consent Management data source. + * + * @return Data source. + */ + public DataSource getDataSource() { + + return dataSource; + } + + /** + * Revoke the transaction when catch then sql transaction errors. + * + * @param dbConnection database connection. + */ + public void rollbackTransaction(Connection dbConnection) { + + try { + if (dbConnection != null) { + dbConnection.rollback(); + } + } catch (SQLException e) { +// log.error("An error occurred while rolling back transactions. ", e); + } + } + + /** + * Commit the transaction. + * + * @param dbConnection database connection. + */ + public void commitTransaction(Connection dbConnection) { + + try { + if (dbConnection != null) { + dbConnection.commit(); + } + } catch (SQLException e) { +// log.error("An error occurred while commit transactions. ", e); + } + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java new file mode 100644 index 000000000..dd016cbb4 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtCommonDBQueries.java @@ -0,0 +1,370 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.queries; + +import org.apache.commons.lang3.StringUtils; + +/** + * The common database queries used by the consent management DAO layer. + */ +public class ConsentMgtCommonDBQueries { + + public String getStoreConsentPreparedStatement() { + + return "INSERT INTO FS_CONSENT (ORG_ID, CONSENT_ID, RECEIPT, CREATED_TIME, UPDATED_TIME, CLIENT_ID, " + + "CONSENT_TYPE, " + + "CURRENT_STATUS, CONSENT_FREQUENCY, VALIDITY_TIME, RECURRING_INDICATOR) VALUES ( COALESCE(?, " + + "'DEFAULT_ORG')" + + ", ?, ?, ?, ?, ?, ?, " + + "?, " + + "?, ?, ?)"; + } + + public String getGetConsentPreparedStatement() { + + return "SELECT * FROM FS_CONSENT WHERE CONSENT_ID = ?"; + } + + public String getGetConsentWithConsentAttributesPreparedStatement() { + + return "SELECT FS_CONSENT.CONSENT_ID, ORG_ID, RECEIPT, CREATED_TIME, UPDATED_TIME, CLIENT_ID, CONSENT_TYPE, " + + "CURRENT_STATUS, CONSENT_FREQUENCY, VALIDITY_TIME, RECURRING_INDICATOR, " + + "FS_CONSENT_ATTRIBUTE.ATT_KEY, FS_CONSENT_ATTRIBUTE.ATT_VALUE FROM FS_CONSENT LEFT JOIN " + + "FS_CONSENT_ATTRIBUTE ON FS_CONSENT.CONSENT_ID = FS_CONSENT_ATTRIBUTE.CONSENT_ID WHERE FS_CONSENT" + + ".CONSENT_ID = ?"; + } + + public String getGetDetailedConsentPreparedStatement() { + + return "SELECT obc.CONSENT_ID," + + "ORG_ID, " + + "RECEIPT, " + + "CLIENT_ID, " + + "ORG_ID, " + + "CONSENT_TYPE, " + + "CURRENT_STATUS, " + + "CONSENT_FREQUENCY, " + + "VALIDITY_TIME, " + + "RECURRING_INDICATOR, " + + "CREATED_TIME AS CONSENT_CREATED_TIME, " + + "obc.UPDATED_TIME AS CONSENT_UPDATED_TIME, " + + "ca.ATT_KEY, " + + "ca.ATT_VALUE, " + + "ocar.AUTH_ID, " + + "ocar.AUTH_STATUS, " + + "ocar.AUTH_TYPE, " + + "ocar.UPDATED_TIME AS AUTH_UPDATED_TIME, " + + "ocar.USER_ID, " + + "cm.MAPPING_ID, " + + "cm.MAPPING_STATUS, " + + "cm.RESOURCE " + + "FROM FS_CONSENT obc " + + "LEFT JOIN FS_CONSENT_ATTRIBUTE ca ON obc.CONSENT_ID=ca.CONSENT_ID " + + "LEFT JOIN FS_CONSENT_AUTH_RESOURCE ocar ON obc.CONSENT_ID=ocar.CONSENT_ID " + + "LEFT JOIN FS_CONSENT_MAPPING cm ON ocar.AUTH_ID=cm.AUTH_ID " + + "WHERE obc.CONSENT_ID = ?"; + } + + public String getGetConsentResourceWithAuthorizationResourcesPreparedStatement() { + + return "SELECT obc.CONSENT_ID," + + "ORG_ID, " + + "RECEIPT, " + + "CLIENT_ID, " + + "ORG_ID, " + + "CONSENT_TYPE, " + + "CURRENT_STATUS, " + + "CONSENT_FREQUENCY, " + + "VALIDITY_TIME, " + + "RECURRING_INDICATOR, " + + "CREATED_TIME AS CONSENT_CREATED_TIME, " + + "obc.UPDATED_TIME AS CONSENT_UPDATED_TIME, " + + "ocar.AUTH_ID, " + + "ocar.AUTH_STATUS, " + + "ocar.AUTH_TYPE, " + + "ocar.UPDATED_TIME AS AUTH_UPDATED_TIME, " + + "ocar.USER_ID, " + + "cm.MAPPING_ID, " + + "cm.MAPPING_STATUS, " + + "cm.RESOURCE " + + "FROM FS_CONSENT obc " + + "LEFT JOIN FS_CONSENT_AUTH_RESOURCE ocar ON obc.CONSENT_ID=ocar.CONSENT_ID " + + "LEFT JOIN FS_CONSENT_MAPPING cm ON ocar.AUTH_ID=cm.AUTH_ID " + + "WHERE obc.CONSENT_ID = ?"; + } + + public String getUpdateConsentStatusPreparedStatement() { + + return "UPDATE FS_CONSENT SET CURRENT_STATUS = ?, UPDATED_TIME = ? WHERE CONSENT_ID = ?"; + } + + public String getUpdateConsentReceiptPreparedStatement() { + + return "UPDATE FS_CONSENT SET RECEIPT = ? WHERE CONSENT_ID = ?"; + } + + public String getUpdateConsentValidityTimePreparedStatement() { + + return "UPDATE FS_CONSENT SET VALIDITY_TIME = ?, UPDATED_TIME = ? WHERE CONSENT_ID = ?"; + } + + public String getStoreAuthorizationPreparedStatement() { + + return "INSERT INTO FS_CONSENT_AUTH_RESOURCE (AUTH_ID, CONSENT_ID, AUTH_TYPE, USER_ID, AUTH_STATUS, " + + "UPDATED_TIME) VALUES (?, ?, ?, ?, ?, ?)"; + } + + public String getGetAuthorizationResourcePreparedStatement() { + + return "SELECT ACR.*, OCM.*\n" + + "FROM FS_CONSENT_AUTH_RESOURCE ACR \n" + + "LEFT JOIN FS_CONSENT_MAPPING OCM ON OCM.AUTH_ID = ACR.AUTH_ID \n" + + "LEFT JOIN FS_CONSENT C ON ACR.CONSENT_ID = C.CONSENT_ID \n" + + "WHERE ACR.AUTH_ID = ? \n" + + "AND (C.ORG_ID = ?)"; + } + + public String getUpdateAuthorizationStatusPreparedStatement() { + + return "UPDATE FS_CONSENT_AUTH_RESOURCE SET AUTH_STATUS = ?, UPDATED_TIME = ? WHERE AUTH_ID = ?"; + } + + public String getUpdateAuthorizationUserPreparedStatement() { + + return "UPDATE FS_CONSENT_AUTH_RESOURCE SET USER_ID = ?, UPDATED_TIME = ? WHERE AUTH_ID = ?"; + } + + public String getStoreConsentMappingPreparedStatement() { + + return "INSERT INTO FS_CONSENT_MAPPING (MAPPING_ID, AUTH_ID, RESOURCE, MAPPING_STATUS) VALUES " + + "(?, ?, ?, ? )"; + } + + public String getGetConsentMappingResourcesPreparedStatement() { + + return "SELECT * FROM FS_CONSENT_MAPPING WHERE AUTH_ID = ?"; + } + + public String getUpdateConsentMappingStatusPreparedStatement() { + + return "UPDATE FS_CONSENT_MAPPING SET MAPPING_STATUS = ? WHERE MAPPING_ID = ?"; + } + + public String getStoreConsentAttributesPreparedStatement() { + + return "INSERT INTO FS_CONSENT_ATTRIBUTE (CONSENT_ID, ATT_KEY, ATT_VALUE) VALUES (?, ?, ?)"; + } + + public String getGetConsentAttributesPreparedStatement() { + + return "SELECT * FROM FS_CONSENT_ATTRIBUTE WHERE CONSENT_ID = ?"; + } + + public String getGetConsentAttributesByNamePreparedStatement() { + + return "SELECT CONSENT_ID, ATT_VALUE FROM FS_CONSENT_ATTRIBUTE WHERE ATT_KEY = ?"; + } + + public String getConsentIdByConsentAttributeNameAndValuePreparedStatement() { + + return "SELECT CONSENT_ID FROM FS_CONSENT_ATTRIBUTE WHERE ATT_KEY = ? AND ATT_VALUE = ?"; + } + + public String getUpdateConsentAttributesPreparedStatement() { + + return "UPDATE FS_CONSENT_ATTRIBUTE SET ATT_VALUE = ? WHERE CONSENT_ID = ? and ATT_KEY = ?"; + } + + public String getDeleteConsentAttributePreparedStatement() { + + return "DELETE FROM FS_CONSENT_ATTRIBUTE WHERE CONSENT_ID = ? AND ATT_KEY = ?"; + } + + public String getStoreConsentFilePreparedStatement() { + + return "INSERT INTO FS_CONSENT_FILE (CONSENT_ID, CONSENT_FILE) VALUES (?, ?)"; + } + + public String getGetConsentFileResourcePreparedStatement() { + return "SELECT * FROM FS_CONSENT_FILE WHERE CONSENT_ID = ?"; + } + + public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, + String userIdFilterClause) { + + String selectClause = "(SELECT * FROM FS_CONSENT " + whereClause + ")"; + String joinType = "LEFT "; + if (StringUtils.isNotEmpty(userIdFilterClause)) { + joinType = "INNER "; + userIdFilterClause = "AND " + userIdFilterClause; + } + + StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + + "ORG_ID, " + + "RECEIPT, " + + "CLIENT_ID, " + + "CONSENT_TYPE, " + + "OBC.CURRENT_STATUS AS CURRENT_STATUS," + + "CONSENT_FREQUENCY," + + "VALIDITY_TIME," + + "RECURRING_INDICATOR," + + "OBC.CREATED_TIME AS CONSENT_CREATED_TIME," + + "OBC.UPDATED_TIME AS CONSENT_UPDATED_TIME," + + "Group_concat(distinct CA.att_key order by CA.att_key SEPARATOR '||' ) AS ATT_KEY, " + + "Group_concat(distinct CA.att_value order by CA.att_key SEPARATOR '||') AS ATT_VALUE, " + + + + "( SELECT Group_concat( OCAR2.auth_id order by OCAR2.auth_id SEPARATOR '||') " + + " FROM FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE OCAR2.consent_id = OBC.consent_id " + + " GROUP BY OCAR2.consent_id ) AS AUTH_ID, " + + + "( SELECT Group_concat(OCAR2.auth_status order by OCAR2.auth_id SEPARATOR '||') " + + " FROM FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE OCAR2.consent_id = OBC.consent_id " + + " GROUP BY OCAR2.consent_id ) AS AUTH_STATUS, " + + + "( SELECT Group_concat(OCAR2.auth_type order by OCAR2.auth_id SEPARATOR '||') " + + " FROM FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE OCAR2.consent_id = OBC.consent_id " + + " GROUP BY OCAR2.consent_id ) AS AUTH_TYPE, " + + + "( SELECT Group_concat(OCAR2.updated_time order by OCAR2.auth_id SEPARATOR '||') " + + " FROM FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE OCAR2.consent_id = OBC.consent_id " + + " GROUP BY OCAR2.consent_id ) AS UPDATED_TIME, " + + + "( SELECT Group_concat(OCAR2.user_id order by OCAR2.auth_id SEPARATOR '||') " + + " FROM FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE OCAR2.consent_id = OBC.consent_id " + + " GROUP BY OCAR2.consent_id ) AS USER_ID," + + + + " ( SELECT Group_concat(OCM2.auth_id order by OCM2.mapping_id SEPARATOR '||') " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE OCAR2.consent_id = OBC.consent_id) AS AUTH_MAPPING_ID , " + + + + + "( SELECT Group_concat(OCM2.mapping_id order by OCM2.mapping_id SEPARATOR '||') " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE OCAR2.consent_id = OBC.consent_id) AS MAPPING_ID , " + + + "( SELECT Group_concat(OCM2.mapping_status order by OCM2.mapping_id SEPARATOR '||') " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE OCAR2.consent_id = OBC.consent_id) AS MAPPING_STATUS , " + + + "( SELECT Group_concat(OCM2.resource order by OCM2.mapping_id SEPARATOR '||') " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE OCAR2.consent_id = OBC.consent_id) AS RESOURCE " + + + "FROM " + + selectClause + + "AS OBC " + + "LEFT JOIN FS_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + + joinType + "JOIN FS_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " + + userIdFilterClause + + "LEFT JOIN FS_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID WHERE " + + "(OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + + "AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) " + + "group by OBC.CONSENT_ID ORDER BY OBC.UPDATED_TIME DESC "); + + if (shouldLimit && shouldOffset) { + query.append(" LIMIT ? OFFSET ? "); + } else if (shouldLimit) { + query.append(" LIMIT ? "); + } + + return query.toString(); + } + + public String getSearchAuthorizationResourcesPreparedStatement(String whereClause) { + + return "SELECT * FROM FS_CONSENT_AUTH_RESOURCE" + whereClause; + } + + public String getStoreConsentStatusAuditRecordPreparedStatement() { + + return "INSERT INTO FS_CONSENT_STATUS_AUDIT (STATUS_AUDIT_ID, CONSENT_ID, CURRENT_STATUS, ACTION_TIME, " + + "REASON, ACTION_BY, PREVIOUS_STATUS) VALUES (?, ?, ?, ?, ?, ?, ?)"; + } + + public String getGetConsentStatusAuditRecordsPreparedStatement() { + + return "SELECT * FROM FS_CONSENT_STATUS_AUDIT WHERE CONSENT_ID = COALESCE(?, CONSENT_ID) " + + "AND CURRENT_STATUS = COALESCE(?, CURRENT_STATUS) AND ACTION_BY = COALESCE(?, ACTION_BY) " + + "AND STATUS_AUDIT_ID = COALESCE (?, STATUS_AUDIT_ID) AND ACTION_TIME >= COALESCE(?, ACTION_TIME) " + + "AND ACTION_TIME <= COALESCE(?, ACTION_TIME)"; + } + + /** + * SQL query for get consent status audit records by consentIds. + * @param whereClause conditions + * @param shouldLimit whether to consider the Limit parameter + * @param shouldOffset whether to consider the Offset parameter + * @return SQL query for get consent status audit records by consentIds + */ + public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, + boolean shouldOffset) { + + StringBuilder query = + new StringBuilder("SELECT * FROM FS_CONSENT_STATUS_AUDIT " + whereClause); + + if (shouldLimit && shouldOffset) { + query.append(" LIMIT ? OFFSET ? "); + } else if (shouldLimit) { + query.append(" LIMIT ? "); + } + return query.toString(); + } + + /** + * Util method to get the limit offset order for differentiate oracle and mssql pagination. + * @return is limit is before in prepared statement than offset + */ + public boolean isLimitBeforeThanOffset() { + + return true; + } + + public String getInsertConsentHistoryPreparedStatement() { + + return "INSERT INTO FS_CONSENT_HISTORY (TABLE_ID, RECORD_ID, HISTORY_ID, CHANGED_VALUES, " + + "REASON, EFFECTIVE_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?)"; + } + + public String getGetConsentHistoryPreparedStatement(String whereClause) { + + return "SELECT * FROM FS_CONSENT_HISTORY " + whereClause + + "ORDER BY EFFECTIVE_TIMESTAMP DESC"; + } + + public String getSearchExpiringConsentPreparedStatement(String statusesEligibleForExpirationCondition) { + + return "SELECT OBC.CONSENT_ID " + + " FROM FS_CONSENT_ATTRIBUTE CA " + + " JOIN FS_CONSENT OBC " + + " ON CA.CONSENT_ID = OBC.CONSENT_ID " + + " WHERE CA.ATT_KEY = ? AND OBC.CURRENT_STATUS IN " + statusesEligibleForExpirationCondition; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java new file mode 100644 index 000000000..a80dcbdca --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtMssqlDBQueries.java @@ -0,0 +1,174 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.queries; + +import org.apache.commons.lang3.StringUtils; + +/** + * The Microsoft SQL database queries used by the consent management DAO layer. + */ +public class ConsentMgtMssqlDBQueries extends ConsentMgtCommonDBQueries { + + public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, + String userIdFilterClause) { + + String selectClause = "(SELECT * FROM FS_CONSENT)"; + String joinType = " LEFT "; + + if (StringUtils.isNotEmpty(userIdFilterClause)) { + joinType = " INNER "; + userIdFilterClause = "AND " + userIdFilterClause; + } + + if (whereClause.trim().isEmpty()) { + whereClause = " WHERE "; + } else { + whereClause = whereClause + " AND "; + } + + StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + + " (SELECT receipt FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS RECEIPT, " + + " (SELECT client_id FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CLIENT_ID, " + + " (SELECT consent_type FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_TYPE, " + + " (SELECT current_status FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CURRENT_STATUS, " + + " (SELECT consent_frequency FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_FREQUENCY, " + + " (SELECT validity_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS VALIDITY_TIME, " + + " (SELECT recurring_indicator FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS RECURRING_INDICATOR, " + + " (SELECT created_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_CREATED_TIME, " + + " (SELECT updated_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " order by consent_id offset 0 rows FETCH next 1 rows only ) AS CONSENT_UPDATED_TIME, " + + + "( SELECT String_agg(att_key , '||') within GROUP (ORDER BY att_key) " + + " FROM FS_CONSENT_ATTRIBUTE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS ATT_KEY, " + + + "( SELECT String_agg(att_value , '||') within GROUP (ORDER BY att_key) " + + " FROM FS_CONSENT_ATTRIBUTE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS ATT_VALUE, " + + + "( SELECT String_agg(auth_id , '||') within GROUP (ORDER BY auth_id) " + + " FROM FS_CONSENT_AUTH_RESOURCE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS AUTH_ID, " + + + "( SELECT String_agg(auth_status , '||') within GROUP (ORDER BY auth_id) " + + " FROM FS_CONSENT_AUTH_RESOURCE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS AUTH_STATUS, " + + + "( SELECT String_agg(auth_type , '||') within GROUP (ORDER BY auth_id) " + + " FROM FS_CONSENT_AUTH_RESOURCE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS AUTH_TYPE, " + + + "( SELECT String_agg(updated_time , '||') within GROUP (ORDER BY auth_id) " + + " FROM FS_CONSENT_AUTH_RESOURCE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS UPDATED_TIME, " + + + "( SELECT String_agg(user_id , '||') within GROUP (ORDER BY auth_id) " + + " FROM FS_CONSENT_AUTH_RESOURCE " + + " WHERE consent_id = OBC.consent_id " + + " GROUP BY consent_id ) AS USER_ID," + + + + "( SELECT String_agg(OCM2.AUTH_ID , '||') within GROUP (ORDER BY OCM2.mapping_id) " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS AUTH_MAPPING_ID , " + + + "( SELECT String_agg(OCM2.account_id , '||') within GROUP (ORDER BY OCM2.mapping_id) " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS ACCOUNT_ID , " + + + "( SELECT String_agg(OCM2.mapping_id , '||') within GROUP (ORDER BY OCM2.mapping_id) " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_ID , " + + + "( SELECT String_agg(OCM2.mapping_status , '||') within GROUP (ORDER BY OCM2.mapping_id) " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_STATUS , " + + + "( SELECT String_agg(OCM2.permission , '||') within GROUP (ORDER BY OCM2.mapping_id) " + + " FROM FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE ocar2 ON ocar2.auth_id = OCM2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS PERMISSION " + + + + "FROM " + selectClause + "AS OBC " + + "LEFT JOIN FS_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + + joinType + "JOIN FS_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " + + userIdFilterClause + + "LEFT JOIN FS_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID " + whereClause + + " (OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + + " AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) GROUP BY obc.consent_id " + + " ORDER BY UPDATED_TIME DESC "); + + if (shouldLimit && shouldOffset) { + query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); + } else if (shouldLimit) { + query.append("OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY "); + } + + return query.toString(); + } + + /** + * SQL query for get consent status audit records by consentIds. + * @param whereClause conditions + * @param shouldLimit limit + * @param shouldOffset offset + * @return SQL query + */ + public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, + boolean shouldOffset) { + + StringBuilder query = + new StringBuilder("SELECT * FROM FS_CONSENT_STATUS_AUDIT " + whereClause); + + if (shouldLimit && shouldOffset) { + query.append("ORDER BY STATUS_AUDIT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); + } else if (shouldLimit) { + query.append("ORDER BY STATUS_AUDIT_ID OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY "); + } + return query.toString(); + } + + /** + * Util method to get the limit offset order for differentiate oracle and mssql pagination. + * @return is limit is before in prepared statement than offset + */ + public boolean isLimitBeforeThanOffset() { + + return false; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java new file mode 100644 index 000000000..c4d333b89 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtOracleDBQueries.java @@ -0,0 +1,177 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.queries; + +import org.apache.commons.lang3.StringUtils; + +/** + * The Oracle database queries used by the consent management DAO layer. + */ +public class ConsentMgtOracleDBQueries extends ConsentMgtCommonDBQueries { + + public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, + String userIdFilterClause) { + + String selectClause = "FS_CONSENT "; + String joinType = "LEFT"; + + if (StringUtils.isNotEmpty(userIdFilterClause)) { + joinType = "INNER"; + userIdFilterClause = "AND " + userIdFilterClause; + } + + if (whereClause.trim().isEmpty()) { + whereClause = " WHERE "; + } else { + whereClause = whereClause + " AND "; + } + + StringBuilder query = new StringBuilder("SELECT OBC.CONSENT_ID, " + + " ( SELECT receipt FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH first 1 rows only ) AS RECEIPT, " + + " (SELECT client_id FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS CLIENT_ID, " + + " (SELECT consent_type FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS CONSENT_TYPE, " + + " (SELECT current_status FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS current_status, " + + " (SELECT consent_frequency FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS CONSENT_FREQUENCY, " + + " (SELECT validity_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS VALIDITY_TIME, " + + " (SELECT recurring_indicator FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS RECURRING_INDICATOR, " + + " (SELECT created_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS consent_created_time, " + + " (SELECT updated_time FROM FS_CONSENT WHERE consent_id = obc.consent_id " + + " FETCH FIRST 1 rows only ) AS consent_updated_time, " + + + " ( SELECT listagg(att_key || '||') within GROUP (ORDER BY att_key) " + + " FROM fs_consent_attribute " + + " WHERE consent_id = obc.consent_id " + + " GROUP BY consent_id ) AS ATT_KEY, " + + + " ( SELECT listagg(att_value || '||') within GROUP (ORDER BY att_key)" + + " FROM fs_consent_attribute" + + " WHERE consent_id = obc.consent_id" + + " GROUP BY consent_id ) AS ATT_VALUE, " + + + " ( SELECT listagg(auth_id || '||') within GROUP (ORDER BY auth_id)" + + " FROM fs_consent_auth_resource" + + " WHERE consent_id = obc.consent_id" + + " GROUP BY consent_id ) AS AUTH_ID, " + + + " ( SELECT listagg(auth_status || '||') within GROUP (ORDER BY auth_id)" + + " FROM fs_consent_auth_resource" + + " WHERE consent_id = obc.consent_id" + + " GROUP BY consent_id ) AS AUTH_STATUS, " + + + " ( SELECT listagg(auth_type || '||') within GROUP (ORDER BY auth_id) " + + " FROM fs_consent_auth_resource " + + " WHERE consent_id = obc.consent_id " + + " GROUP BY consent_id ) AS AUTH_TYPE, " + + + " ( SELECT listagg(updated_time || '||') within GROUP (ORDER BY auth_id) " + + " FROM fs_consent_auth_resource " + + " WHERE consent_id = obc.consent_id " + + " GROUP BY consent_id ) AS UPDATED_TIME, " + + + " ( SELECT listagg(user_id || '||') within GROUP (ORDER BY auth_id) " + + " FROM fs_consent_auth_resource " + + " WHERE consent_id = obc.consent_id " + + " GROUP BY consent_id ) AS USER_ID, " + + + + " ( SELECT listagg(ocm2.auth_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + + " FROM fs_consent_mapping ocm2 " + + " JOIN fs_consent_auth_resource ocar2 " + + " ON ocar2.auth_id = ocm2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS AUTH_MAPPING_ID , " + + + " ( SELECT listagg(ocm2.account_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + + " FROM fs_consent_mapping ocm2 " + + " JOIN fs_consent_auth_resource ocar2 " + + " ON ocar2.auth_id = ocm2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS ACCOUNT_ID , " + + + " ( SELECT listagg(ocm2.mapping_id || '||') within GROUP (ORDER BY ocm2.mapping_id) " + + " FROM fs_consent_mapping ocm2 " + + " JOIN fs_consent_auth_resource ocar2 " + + " ON ocar2.auth_id = ocm2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_ID , " + + + " ( SELECT listagg(ocm2.mapping_status || '||') within GROUP (ORDER BY ocm2.mapping_id) " + + " FROM fs_consent_mapping ocm2 " + + " JOIN fs_consent_auth_resource ocar2 " + + " ON ocar2.auth_id = ocm2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS MAPPING_STATUS , " + + + " ( SELECT listagg(ocm2.permission || '||') within GROUP (ORDER BY ocm2.mapping_id) " + + " FROM fs_consent_mapping ocm2 " + + " JOIN fs_consent_auth_resource ocar2 " + + " ON ocar2.auth_id = ocm2.auth_id " + + " WHERE ocar2.consent_id = obc.consent_id) AS PERMISSION " + + + "FROM " + selectClause + " OBC " + + "LEFT JOIN FS_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + + joinType + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " + + userIdFilterClause + + "LEFT JOIN FS_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID " + whereClause + + " (OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + + " AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) GROUP BY obc.consent_id " + + "ORDER BY UPDATED_TIME DESC "); + + if (shouldLimit && shouldOffset) { + query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); + } else if (shouldLimit) { + query.append("FETCH NEXT ? ROWS ONLY"); + } + return query.toString(); + } + + /** + * SQL query for get consent status audit records by consentIds. + * @param whereClause conditions + * @param shouldLimit whether limit should be applied + * @param shouldOffset whether offset should be applied + * @return SQL query to retrieve consent status audit records by consentIds + */ + public String getConsentStatusAuditRecordsByConsentIdsPreparedStatement(String whereClause, boolean shouldLimit, + boolean shouldOffset) { + + StringBuilder query = + new StringBuilder("SELECT * FROM FS_CONSENT_STATUS_AUDIT " + whereClause); + + if (shouldLimit && shouldOffset) { + query.append("OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "); + } else if (shouldLimit) { + query.append("FETCH NEXT ? ROWS ONLY"); + } + return query.toString(); + } + + /** + * Util method to get the limit offset order for differentiate oracle and mssql pagination. + * @return is limit is before in prepared statement than offset + */ + public boolean isLimitBeforeThanOffset() { + + return false; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java new file mode 100644 index 000000000..171ff897a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/queries/ConsentMgtPostgresDBQueries.java @@ -0,0 +1,212 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.queries; + +import org.apache.commons.lang3.StringUtils; + +/** + * The PostgreSQL database queries used by the consent management DAO layer. + */ +public class ConsentMgtPostgresDBQueries extends ConsentMgtCommonDBQueries { + + /** + * This method returns the detailed consent search query. It constructs the query according to the provided + * parameters dynamically. This queries all consent attributes, authorization resources, mapping resources, consent + * data of the provided consent according to the parameters provided. To avoid fetching same rows multiple times, + * the string_agg function is used to concatenate values using a delimiter. The delimited results are later + * processed and set to the result. + * + * @param whereClause the pre-constructed where dynamic where clause + * @param shouldLimit flag that indicates the limit + * @param shouldOffset flag that indicates the offset + * @param userIdFilterClause the pre-constructed user id filter condition + * @return the constructed prepared statement for consent search function + */ + public String getSearchConsentsPreparedStatement(String whereClause, boolean shouldLimit, boolean shouldOffset, + String userIdFilterClause) { + + String selectClause = "(SELECT * FROM FS_CONSENT " + whereClause + ")"; + String joinType = "LEFT "; + if (StringUtils.isNotEmpty(userIdFilterClause)) { + joinType = "INNER "; + userIdFilterClause = "AND " + userIdFilterClause; + } + + StringBuilder query = new StringBuilder("SELECT " + + " OBC.CONSENT_ID, " + + " RECEIPT, " + + " CLIENT_ID, " + + " CONSENT_TYPE, " + + " OBC.CURRENT_STATUS AS CURRENT_STATUS, " + + " CONSENT_FREQUENCY, " + + " VALIDITY_TIME, " + + " RECURRING_INDICATOR, " + + " OBC.CREATED_TIME AS CONSENT_CREATED_TIME, " + + " OBC.UPDATED_TIME AS CONSENT_UPDATED_TIME, " + + " String_agg(" + + " CA.att_key :: varchar, '||' order by CA.att_key :: varchar" + + " ) AS ATT_KEY," + + " String_agg(" + + " CA.att_value :: varchar, '||' order by CA.att_key :: varchar" + + " ) AS ATT_VALUE," + + " (" + + " SELECT " + + " String_agg(" + + " OCAR2.auth_id:: varchar, '||' order by OCAR2.auth_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id " + + " GROUP BY " + + " OCAR2.consent_id" + + " ) AS AUTH_ID, " + + " (" + + " SELECT " + + " String_agg(" + + " OCAR2.auth_status :: varchar, '||' order by OCAR2.auth_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id " + + " GROUP BY " + + " OCAR2.consent_id" + + " ) AS AUTH_STATUS, " + + " (" + + " select" + + " String_agg(" + + " OCAR2.auth_type :: varchar, '||' order by OCAR2.auth_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id " + + " GROUP BY " + + " OCAR2.consent_id" + + " ) AS AUTH_TYPE, " + + " (" + + " SELECT " + + " String_agg(" + + " OCAR2.updated_time :: varchar, '||' order by OCAR2.auth_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id " + + " GROUP BY " + + " OCAR2.consent_id" + + " ) AS UPDATED_TIME, " + + " (" + + " SELECT " + + " String_agg(" + + " OCAR2.user_id :: varchar, '||' order by OCAR2.auth_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_AUTH_RESOURCE OCAR2 " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id " + + " GROUP BY " + + " OCAR2.consent_id" + + " ) AS USER_ID, " + + " (" + + " SELECT " + + " String_agg(" + + " OCAR2.auth_id:: varchar, '||' order by OCM2.mapping_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id" + + " ) AS AUTH_MAPPING_ID, " + + " (" + + " SELECT " + + " String_agg(" + + " OCM2.account_id :: varchar, '||' order by OCM2.mapping_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id" + + " ) AS ACCOUNT_ID, " + + " (" + + " SELECT " + + " String_agg(" + + " OCM2.mapping_id :: varchar, '||' order by OCM2.mapping_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id" + + " ) AS MAPPING_ID, " + + " (" + + " SELECT " + + " String_agg(" + + " OCM2.mapping_status :: varchar, '||' order by OCM2.mapping_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id" + + " ) AS MAPPING_STATUS, " + + " (" + + " SELECT " + + " String_agg(" + + " OCM2.permission :: varchar, '||' order by OCM2.mapping_id :: varchar" + + " )" + + " FROM " + + " FS_CONSENT_MAPPING OCM2 " + + " JOIN FS_CONSENT_AUTH_RESOURCE OCAR2 ON OCAR2.auth_id = OCM2.auth_id " + + " WHERE " + + " OCAR2.consent_id = OBC.consent_id" + + " ) AS PERMISSION" + + " FROM " + + selectClause + + "AS OBC " + + "LEFT JOIN FS_CONSENT_ATTRIBUTE CA ON OBC.CONSENT_ID=CA.CONSENT_ID " + + joinType + "JOIN FS_CONSENT_AUTH_RESOURCE OCAR ON OBC.CONSENT_ID=OCAR.CONSENT_ID " + + userIdFilterClause + + "LEFT JOIN FS_CONSENT_MAPPING OCM ON OCAR.AUTH_ID=OCM.AUTH_ID WHERE " + + "(OBC.UPDATED_TIME >= COALESCE(?, OBC.UPDATED_TIME) " + + "AND OBC.UPDATED_TIME <= COALESCE(?, OBC.UPDATED_TIME)) " + + "group by OBC.CONSENT_ID," + + "OBC.RECEIPT," + + "OBC.CLIENT_ID," + + "OBC.CONSENT_TYPE," + + "CONSENT_FREQUENCY," + + "VALIDITY_TIME," + + "RECURRING_INDICATOR," + + "OBC.CURRENT_STATUS," + + "OBC.CREATED_TIME," + + "OBC.UPDATED_TIME " + + "ORDER BY OBC.UPDATED_TIME DESC"); + + if (shouldLimit && shouldOffset) { + query.append(" LIMIT ? OFFSET ? "); + } else if (shouldLimit) { + query.append(" LIMIT ? "); + } + + return query.toString(); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOUtil.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOUtil.java new file mode 100644 index 000000000..d6a3fea65 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOUtil.java @@ -0,0 +1,857 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.minidev.json.JSONObject; +import net.minidev.json.JSONValue; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Utility class for consent management DAO. + */ +public class ConsentManagementDAOUtil { + + private static final Log log = LogFactory.getLog(ConsentManagementDAOUtil.class); + + private static final String SPACE = " "; + private static final String COMMA = ","; + private static final String PLACEHOLDER = "?"; + private static final String LEFT_PARENTHESIS = "("; + private static final String RIGHT_PARENTHESIS = ")"; + + private static final Map DB_OPERATORS_MAP = new HashMap<>(); + + static { + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.IN, + "IN"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.AND, + "AND"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.OR, + "OR"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.WHERE, + "WHERE"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.PLACEHOLDER, + "?,"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER, + "?"); + DB_OPERATORS_MAP.put(ConsentMgtDAOConstants.EQUALS, + "="); + } + + /** + * Set data from the result set to ConsentResource object. + * + * @param resultSet result set + * @return ConsentResource constructed using the result set + */ + public static ConsentResource setDataToConsentResource(ResultSet resultSet) throws + SQLException { + + return new ConsentResource( + resultSet.getString(ConsentMgtDAOConstants.ORG_ID), + resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), + resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID), + resultSet.getString(ConsentMgtDAOConstants.RECEIPT), + resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE), + resultSet.getInt(ConsentMgtDAOConstants.CONSENT_FREQUENCY), + resultSet.getLong(ConsentMgtDAOConstants.VALIDITY_TIME), + resultSet.getBoolean(ConsentMgtDAOConstants.RECURRING_INDICATOR), + resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS), + resultSet.getLong(ConsentMgtDAOConstants.CREATED_TIME), + resultSet.getLong(ConsentMgtDAOConstants.UPDATED_TIME) + ); + } + + /** + * Set data from the result set to ConsentResource object with consent attributes. + * + * @param resultSet result set + * @return ConsentResource with attributes constructed using the result set + */ + public static ConsentResource setDataToConsentResourceWithAttributes(ResultSet resultSet) + throws + SQLException { + ConsentResource consentResource = setDataToConsentResource(resultSet); + Map retrievedConsentAttributeMap = new HashMap<>(); + // Point the cursor to the beginning of the result set to read attributes + resultSet.beforeFirst(); + while (resultSet.next()) { + retrievedConsentAttributeMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), + resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE)); + } + consentResource.setConsentAttributes(retrievedConsentAttributeMap); + + return consentResource; + } + + /** + * Set data from the result set to DetailedConsentResource object. + * + * @param resultSet result set + * @return detailedConsentResource consent resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static DetailedConsentResource setDataToDetailedConsentResource(ResultSet resultSet) throws + SQLException, + JsonProcessingException { + + Map consentAttributesMap = new HashMap<>(); + ArrayList authorizationResources = new ArrayList<>(); + ArrayList consentMappingResources = new ArrayList<>(); + ArrayList authIds = new ArrayList<>(); + ArrayList consentMappingIds = new ArrayList<>(); + DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); + + while (resultSet.next()) { + detailedConsentResource = setConsentDataToDetailedConsentResource(resultSet); + // Set data related to consent attributes + if (StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY))) { + String attributeValue = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE); + + // skip adding all temporary session data to consent attributes + if (!(JSONValue.isValidJson(attributeValue) && + attributeValue.contains(ConsentMgtDAOConstants.SESSION_DATA_KEY))) { + consentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), + attributeValue); + } + } + + // Set data related to authorization resources + if (authIds.isEmpty()) { + if (resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null) { + AuthorizationResource authorizationResource = setAuthorizationData(resultSet, + ConsentMgtDAOConstants.AUTH_UPDATED_TIME); + + authorizationResources.add(authorizationResource); + authIds.add(authorizationResource.getAuthorizationID()); + } + + } else { + if (!authIds.contains(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID))) { + if (resultSet.getString(ConsentMgtDAOConstants.AUTH_ID) != null) { + + AuthorizationResource authorizationResource = setAuthorizationData(resultSet, + ConsentMgtDAOConstants.AUTH_UPDATED_TIME); + + authorizationResources.add(authorizationResource); + authIds.add(authorizationResource.getAuthorizationID()); + } + } + } + + // Set data related to consent account mappings + // Check whether consentMappingIds is empty and result set consists a mapping id since at this moment + // there can be a situation where an auth resource is created and mapping resource is not created + if (consentMappingIds.isEmpty() && resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { + ConsentMappingResource consentMappingResource = getConsentMappingResourceWithData(resultSet); + + consentMappingResources.add(consentMappingResource); + consentMappingIds.add(consentMappingResource.getMappingID()); + } else { + // Check whether result set consists a mapping id since at this moment, there can be a situation + // where an auth resource is created and mapping resource is not created + if (!consentMappingIds.contains(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)) && + resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { + ConsentMappingResource consentMappingResource = getConsentMappingResourceWithData(resultSet); + + consentMappingResources.add(consentMappingResource); + consentMappingIds.add(consentMappingResource.getMappingID()); + } + } + } + + // Set consent attributes, auth resources and account mappings to detailed consent resource + detailedConsentResource.setConsentAttributes(consentAttributesMap); + detailedConsentResource.setAuthorizationResources(authorizationResources); + detailedConsentResource.setConsentMappingResources(consentMappingResources); + return detailedConsentResource; + } + + + /** + * Set data from the result set to DetailedConsentResource object. + * + * @param resultSet result set + * @return detailedConsentResource consent resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static DetailedConsentResource setDataToConsentResourceWithAuthorizationResource(ResultSet resultSet) throws + SQLException, + JsonProcessingException { + + Map consentAttributesMap = new HashMap<>(); + ArrayList authorizationResources = new ArrayList<>(); + ArrayList consentMappingResources = new ArrayList<>(); + ArrayList authIds = new ArrayList<>(); + ArrayList consentMappingIds = new ArrayList<>(); + DetailedConsentResource detailedConsentResource = new DetailedConsentResource(); + + while (resultSet.next()) { + detailedConsentResource = setConsentDataToDetailedConsentResource(resultSet); + // Set data related to consent attributes +// if (StringUtils.isNotBlank(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY))) { +// String attributeValue = resultSet.getString(ConsentMgtDAOConstants.ATT_VALUE); +// +// // skip adding all temporary session data to consent attributes +// if (!(JSONValue.isValidJson(attributeValue) && +// attributeValue.contains(ConsentMgtDAOConstants.SESSION_DATA_KEY))) { +// consentAttributesMap.put(resultSet.getString(ConsentMgtDAOConstants.ATT_KEY), +// attributeValue); +// } +// } + + // Set data related to authorization resources + if (authIds.isEmpty()) { + AuthorizationResource authorizationResource = setAuthorizationData(resultSet, + ConsentMgtDAOConstants.AUTH_UPDATED_TIME); + + authorizationResources.add(authorizationResource); + authIds.add(authorizationResource.getAuthorizationID()); + } else { + if (!authIds.contains(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID))) { + AuthorizationResource authorizationResource = setAuthorizationData(resultSet, + ConsentMgtDAOConstants.AUTH_UPDATED_TIME); + + authorizationResources.add(authorizationResource); + authIds.add(authorizationResource.getAuthorizationID()); + } + } + + // Set data related to consent account mappings + // Check whether consentMappingIds is empty and result set consists a mapping id since at this moment + // there can be a situation where an auth resource is created and mapping resource is not created + if (consentMappingIds.isEmpty() && resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { + ConsentMappingResource consentMappingResource = getConsentMappingResourceWithData(resultSet); + + consentMappingResources.add(consentMappingResource); + consentMappingIds.add(consentMappingResource.getMappingID()); + } else { + // Check whether result set consists a mapping id since at this moment, there can be a situation + // where an auth resource is created and mapping resource is not created + if (!consentMappingIds.contains(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)) && + resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID) != null) { + ConsentMappingResource consentMappingResource = getConsentMappingResourceWithData(resultSet); + + consentMappingResources.add(consentMappingResource); + consentMappingIds.add(consentMappingResource.getMappingID()); + } + } + } + + // Set consent attributes, auth resources and account mappings to detailed consent resource + detailedConsentResource.setConsentAttributes(consentAttributesMap); + detailedConsentResource.setAuthorizationResources(authorizationResources); + detailedConsentResource.setConsentMappingResources(consentMappingResources); + return detailedConsentResource; + } + + /** + * Set consent data from the result set to DetailedConsentResource object. + * + * @param resultSet result set + * @return detailedConsentResource consent resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static DetailedConsentResource setConsentDataToDetailedConsentResource(ResultSet resultSet) + throws + SQLException { + + return new DetailedConsentResource( + resultSet.getString(ConsentMgtDAOConstants.ORG_ID), + resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), + resultSet.getString(ConsentMgtDAOConstants.CLIENT_ID), + resultSet.getString(ConsentMgtDAOConstants.RECEIPT), + resultSet.getString(ConsentMgtDAOConstants.CONSENT_TYPE), + resultSet.getString(ConsentMgtDAOConstants.CURRENT_STATUS), + resultSet.getInt(ConsentMgtDAOConstants.CONSENT_FREQUENCY), + resultSet.getLong(ConsentMgtDAOConstants.VALIDITY_TIME), + resultSet.getLong(ConsentMgtDAOConstants.CONSENT_CREATED_TIME), + resultSet.getLong(ConsentMgtDAOConstants.CONSENT_UPDATED_TIME), + resultSet.getBoolean(ConsentMgtDAOConstants.RECURRING_INDICATOR), + new HashMap<>(), + new ArrayList<>(), + new ArrayList<>() + ); + } + + /** + * Set data from the result set to AuthorizationResource object. + * + * @param resultSet result set + * @param updateTimeParamName update time parameter name + * @return authorizationResource authorization resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static AuthorizationResource setAuthorizationDataWithConsentMapping(ResultSet resultSet, + String updateTimeParamName) + throws + SQLException, + JsonProcessingException { + + + AuthorizationResource authorizationResource = new AuthorizationResource( + resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), + resultSet.getString(ConsentMgtDAOConstants.USER_ID), + resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS), + resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE), + resultSet.getLong(updateTimeParamName) + ); + authorizationResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); + + ArrayList consentMappingResources = new ArrayList<>(); + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setMappingStatus(resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS)); + consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); + ObjectMapper objectMapper = new ObjectMapper(); + + + + String resource = resultSet.getString(ConsentMgtDAOConstants.RESOURCE); + if (resource != null) { + // Convert JSON string to a Map + Map map = objectMapper.readValue(resource, new TypeReference>() { + }); + // Convert Map to net.minidev.json.JSONObject + JSONObject jsonObject = new JSONObject(map); + + consentMappingResource.setResource(jsonObject); + } + + consentMappingResources.add(consentMappingResource); + + while (resultSet.next()) { + consentMappingResource.setMappingStatus(resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS)); + consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); + + consentMappingResource.setResource(new JSONObject(objectMapper.readValue(resultSet. + getString(ConsentMgtDAOConstants.RESOURCE), new TypeReference>() { + }))); + consentMappingResources.add(consentMappingResource); + + + } + authorizationResource.setConsentMappingResource(consentMappingResources); + return authorizationResource; + } + + /** + * Set data from the result set to AuthorizationResource object. + * + * @param resultSet result set + * @param updateTimeParamName update time parameter name + * @return authorizationResource authorization resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static AuthorizationResource setAuthorizationData(ResultSet resultSet, + String updateTimeParamName) + throws + SQLException { + + AuthorizationResource authorizationResource = new AuthorizationResource( + resultSet.getString(ConsentMgtDAOConstants.CONSENT_ID), + resultSet.getString(ConsentMgtDAOConstants.USER_ID), + resultSet.getString(ConsentMgtDAOConstants.AUTH_STATUS), + resultSet.getString(ConsentMgtDAOConstants.AUTH_TYPE), + resultSet.getLong(updateTimeParamName) + ); + authorizationResource.setAuthorizationID(resultSet.getString(ConsentMgtDAOConstants.AUTH_ID)); + + + return authorizationResource; + } + + /** + * Return a consent mapping resource with data set from the result set. + * + * @param resultSet result set + * @return a consent mapping resource + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static ConsentMappingResource getConsentMappingResourceWithData(ResultSet resultSet) throws + SQLException, + JsonProcessingException { + + ObjectMapper objectMapper = new ObjectMapper(); + + ConsentMappingResource consentMappingResource = new ConsentMappingResource( + resultSet.getString(ConsentMgtDAOConstants.AUTH_ID), + + + new JSONObject(objectMapper.readValue(resultSet. + getString(ConsentMgtDAOConstants.RESOURCE), new TypeReference>() { + })), + resultSet.getString(ConsentMgtDAOConstants.MAPPING_STATUS) + ); + consentMappingResource.setMappingID(resultSet.getString(ConsentMgtDAOConstants.MAPPING_ID)); + + return consentMappingResource; + } + + /** + * Construct the where clause of thr prepared statement for consent search. + * + * @param applicableConditions map of applicable conditions + * @return where clause of the prepared statement + */ + public static String constructConsentSearchPreparedStatement(Map> applicableConditions) { + + StringBuilder placeHoldersBuilder = new StringBuilder(); + StringBuilder whereClauseBuilder = new StringBuilder(); + whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); + // If all lists are empty or null, return the default term "where" + if (MapUtils.isEmpty(applicableConditions)) { + return ""; + } + for (Map.Entry> entry : applicableConditions.entrySet()) { + // Oracle only allows 1000 values to be used in a SQL "IN" clause. Since more than 1000 consent IDs + // are used in some queries, "OR" clause is used + if (entry.getKey().contains(ConsentMgtDAOConstants.CONSENT_ID)) { + for (int i = 0; i < entry.getValue().size(); i++) { + whereClauseBuilder + .append(SPACE) + .append(entry.getKey()) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER)) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); + } + // Delete last OR from the statement + whereClauseBuilder.replace(whereClauseBuilder.length() - 2, + whereClauseBuilder.length(), + DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); + } else { + for (int i = 0; i < entry.getValue().size(); i++) { + placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); + } + String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), + COMMA); + whereClauseBuilder + .append(SPACE) + .append(entry.getKey()) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.IN)) + .append(LEFT_PARENTHESIS) + .append(placeHolders) + .append(RIGHT_PARENTHESIS) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); + // Delete all content from old string builder except the starting left parenthesis + placeHoldersBuilder.delete(0, + placeHoldersBuilder.length()); + } + } + int size = whereClauseBuilder.length(); + //removing the last AND in the statement + whereClauseBuilder.replace(size - 3, + size, + ""); + return whereClauseBuilder.toString(); + } + + /** + * Construct the filter condition of the prepared statement for consent search. + * + * @param userIds map of user IDs + * @return filter condition of the prepared statement + */ + public static String constructUserIdListFilterCondition(Map> userIds) { + + StringBuilder placeHoldersBuilder = new StringBuilder(); + StringBuilder userIdFilterBuilder = new StringBuilder(); + + for (Map.Entry> entry : userIds.entrySet()) { + for (int i = 0; i < entry.getValue().size(); i++) { + placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); + } + String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), + COMMA); + userIdFilterBuilder + .append(SPACE) + .append(entry.getKey()) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.IN)) + .append(LEFT_PARENTHESIS) + .append(placeHolders) + .append(RIGHT_PARENTHESIS) + .append(SPACE); + // Delete all content from old string builder except the starting left parenthesis + placeHoldersBuilder.delete(0, + placeHoldersBuilder.length()); + } + return userIdFilterBuilder.toString(); + } + + /** + * Determine the order of parameters to set in the prepared statement. + * + * @param preparedStatement dynamically constructed prepared statement + * @param applicableConditionsMap map of applicable conditions + * @param columnsMap map of columns + * @return ordered parameters map + */ + public static TreeMap> determineOrderOfParamsToSet(String preparedStatement, + Map> + applicableConditionsMap, + Map columnsMap) { + + int indexOfConsentIDsList; + int indexOfClientIdsList; + int indexOfConsentTypesList; + int indexOfConsentStatusesList; + int indexOfUserIDsList; + + // Tree map naturally sorts values in ascending order according to the key + TreeMap> sortedIndexesMap = new TreeMap<>(); + + /* Check whether the where condition clauses are in the prepared statement and get the index if exists to + determine the order */ + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS))) { + indexOfConsentIDsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS)); + sortedIndexesMap.put(indexOfConsentIDsList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_IDS))); + } + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS))) { + indexOfClientIdsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS)); + sortedIndexesMap.put(indexOfClientIdsList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CLIENT_IDS))); + } + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES))) { + indexOfConsentTypesList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES)); + sortedIndexesMap.put(indexOfConsentTypesList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_TYPES))); + } + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES))) { + indexOfConsentStatusesList = preparedStatement + .indexOf(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES)); + sortedIndexesMap.put(indexOfConsentStatusesList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.CONSENT_STATUSES))); + } + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.ORG_ID))) { + indexOfConsentStatusesList = preparedStatement + .indexOf(columnsMap.get(ConsentMgtDAOConstants.ORG_ID)); + sortedIndexesMap.put(indexOfConsentStatusesList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.ORG_ID))); + } + if (preparedStatement.contains(columnsMap.get(ConsentMgtDAOConstants.USER_IDS))) { + indexOfUserIDsList = preparedStatement.indexOf(columnsMap.get(ConsentMgtDAOConstants.USER_IDS)); + sortedIndexesMap.put(indexOfUserIDsList, + applicableConditionsMap.get(columnsMap.get(ConsentMgtDAOConstants.USER_IDS))); + } + return sortedIndexesMap; + } + + /** + * Sets search parameters to dynamically constructed prepared statement. The outer loop is used to iterate the + * different AND clauses and the inner loop is to iterate the number of placeholders of the current AND clause. + * + * @param preparedStatement dynamically constructed prepared statement + * @param orderedParamsMap map with ordered AND conditions + * @param parameterIndex index which the parameter should be set + * @return the final parameter index + * @throws SQLException thrown if an error occurs in the process + */ + public static int setDynamicConsentSearchParameters(PreparedStatement preparedStatement, Map> orderedParamsMap, int parameterIndex) throws + SQLException { + + for (Map.Entry> entry : orderedParamsMap.entrySet()) { + for (int valueIndex = 0; valueIndex < entry.getValue().size(); valueIndex++) { + preparedStatement.setString(parameterIndex, + entry.getValue().get(valueIndex).trim()); + parameterIndex++; + } + } + return parameterIndex; + } + + /** + * Get the size of the result set. + * + * @param resultSet result set + * @return size of the result set + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static int getResultSetSize(ResultSet resultSet) throws + SQLException { + + resultSet.last(); + int resultSetSize = resultSet.getRow(); + + // Point result set back before first + resultSet.beforeFirst(); + return resultSetSize; + } + + /** + * Construct the where clause of the prepared statement for consent auth search. + * + * @param applicableConditions map of applicable conditions + * @return where clause of the prepared statement + */ + public static String constructAuthSearchPreparedStatement(Map applicableConditions) { + + StringBuilder whereClauseBuilder = new StringBuilder(); + + // If all lists are empty or null, return the default term "where" + if (MapUtils.isEmpty(applicableConditions)) { + return whereClauseBuilder.toString(); + } + + whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); + + int count = 0; + for (Map.Entry entry : applicableConditions.entrySet()) { + + if (count > 0) { + whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.AND)); + } + whereClauseBuilder + .append(SPACE) + .append(entry.getKey()) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) + .append(SPACE) + .append(PLACEHOLDER); + count++; + } + return whereClauseBuilder.toString(); + } + + /** + * Generate the tableID based on the type of the consent data record to be stored in consent history table. + * + * @param consentDataType A predefined consent data category based on each consent database table + * @return A identifier assigned for the relevant consent database table + */ + public static String generateConsentTableId(String consentDataType) throws + ConsentDataInsertionException { + + String tableId; + if (ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA.equals(consentDataType)) { + tableId = ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT); + } else if (ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA.equals(consentDataType)) { + tableId = ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_AUTH_RESOURCE); + } else if (ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA.equals(consentDataType)) { + tableId = ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_ATTRIBUTE); + } else if (ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA.equals(consentDataType)) { + tableId = ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_MAPPING); + } else { + log.error(String.format("Can not find a table matching to the provided consentDataType : %s", + consentDataType.replaceAll("[\r\n]", + ""))); + throw new ConsentDataInsertionException("Error occurred while preparing to store consent amendment " + + "history data. Invalid consentDataType provided"); + } + return tableId; + } + + /** + * Method to construct where clause for consent status audit search condition. + * + * @param consentIDs List of consent IDs + * @return Filter condition for consent status audit + */ + public static String constructConsentAuditRecordSearchPreparedStatement(ArrayList consentIDs) { + + StringBuilder whereClauseBuilder = new StringBuilder(); + if (!CollectionUtils.isEmpty(consentIDs)) { + whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); + for (int count = 0; count < consentIDs.size(); count++) { + whereClauseBuilder + .append(SPACE) + .append(ConsentMgtDAOConstants.CONSENT_ID) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLAIN_PLACEHOLDER)) + .append(SPACE) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); + } + // Delete last OR from the statement + whereClauseBuilder.replace(whereClauseBuilder.length() - 2, + whereClauseBuilder.length(), + StringUtils.SPACE); + } + return whereClauseBuilder.toString(); + } + + /** + * Construct the where clause of the prepared statement for consent history search. + * + * @param recordIdCount count of record IDs + * @return where clause of the prepared statement + */ + public static String constructConsentHistoryPreparedStatement(int recordIdCount) { + + StringBuilder whereClauseBuilder = new StringBuilder(); + whereClauseBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.WHERE)); + + for (int count = 0; count < recordIdCount; count++) { + whereClauseBuilder.append(SPACE) + .append(LEFT_PARENTHESIS) + .append(ConsentMgtDAOConstants.RECORD_ID) + .append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.EQUALS)) + .append(PLACEHOLDER) + .append(RIGHT_PARENTHESIS); + if (count < recordIdCount - 1) { + whereClauseBuilder.append(SPACE).append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.OR)); + } + + } + return whereClauseBuilder.toString(); + } + + /** + * construct a data map that includes the changed attributes of each consent amendment history entry and. + * return a map of ConsentHistoryResources including this changed attributes data map + * + * @param consentId consent Id + * @param resultSet result set + * @return a map of ConsentHistoryResources + * @throws SQLException thrown if an error occurs when getting data from the result set + */ + public static Map constructConsentHistoryRetrievalResult(String consentId, + ResultSet resultSet) + throws + SQLException { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + + while (resultSet.next()) { + String tableID = resultSet.getString(ConsentMgtDAOConstants.TABLE_ID); + String recordID = resultSet.getString(ConsentMgtDAOConstants.RECORD_ID); + String historyId = resultSet.getString(ConsentMgtDAOConstants.HISTORY_ID); + String changedAttributesString = resultSet.getString(ConsentMgtDAOConstants.CHANGED_VALUES); + String amendmentReason = resultSet.getString(ConsentMgtDAOConstants.REASON); + long timestamp = resultSet.getLong(ConsentMgtDAOConstants.EFFECTIVE_TIMESTAMP); + + ConsentHistoryResource consentHistoryResource; + Map changedAttributesJsonDataMap; + if (consentAmendmentHistoryDataMap.containsKey(historyId)) { + consentHistoryResource = consentAmendmentHistoryDataMap.get(historyId); + } else { + consentHistoryResource = new ConsentHistoryResource(consentId, + historyId); + consentHistoryResource.setTimestamp(timestamp); + consentHistoryResource.setReason(amendmentReason); + } + + changedAttributesJsonDataMap = consentHistoryResource.getChangedAttributesJsonDataMap(); + + if (ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT) + .equals(tableID)) { + changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, + changedAttributesString); + } else if (ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_ATTRIBUTE) + .equals(tableID)) { + changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, + changedAttributesString); + } else if (ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_AUTH_RESOURCE) + .equals(tableID)) { + Map consentAuthResources; + if (changedAttributesJsonDataMap.containsKey(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA)) { + consentAuthResources = (Map) changedAttributesJsonDataMap + .get(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA); + } else { + consentAuthResources = new HashMap<>(); + } + consentAuthResources.put(recordID, + changedAttributesString); + changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, + consentAuthResources); + } else if (ConsentMgtDAOConstants.TABLES_MAP.get(ConsentMgtDAOConstants.TABLE_FS_CONSENT_MAPPING) + .equals(tableID)) { + Map consentMappingResources; + if (changedAttributesJsonDataMap.containsKey(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA)) { + consentMappingResources = (Map) changedAttributesJsonDataMap + .get(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA); + } else { + consentMappingResources = new HashMap<>(); + } + consentMappingResources.put(recordID, + changedAttributesString); + changedAttributesJsonDataMap.put(ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, + consentMappingResources); + } else { + log.error(String.format("The retrieved tableId : %s has no corresponding consent data type to be" + + " matched", + tableID.replaceAll("[\r\n]", + ""))); + } + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJsonDataMap); + consentAmendmentHistoryDataMap.put(historyId, + consentHistoryResource); + } + return consentAmendmentHistoryDataMap; + } + + /** + * Method to construct excluded statuses search condition. + * + * @param statusesEligibleForExpiration List of statuses eligible for expiration + * @return Filter condition for excluded statuses + */ + public static String constructStatusesEligibleForExpirationCondition(List statusesEligibleForExpiration) { + + StringBuilder placeHoldersBuilder = new StringBuilder(); + StringBuilder statusesEligibleForExpirationFilterBuilder = new StringBuilder(); + + for (int i = 0; i < statusesEligibleForExpiration.size(); i++) { + placeHoldersBuilder.append(DB_OPERATORS_MAP.get(ConsentMgtDAOConstants.PLACEHOLDER)); + } + String placeHolders = StringUtils.removeEnd(placeHoldersBuilder.toString(), + COMMA); + statusesEligibleForExpirationFilterBuilder + .append(SPACE) + .append(LEFT_PARENTHESIS) + .append(placeHolders) + .append(RIGHT_PARENTHESIS) + .append(SPACE); + // Delete all content from old string builder except the starting left parenthesis + placeHoldersBuilder.delete(0, + placeHoldersBuilder.length()); + return statusesEligibleForExpirationFilterBuilder.toString(); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DatabaseUtils.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DatabaseUtils.java new file mode 100644 index 000000000..0950edb6e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DatabaseUtils.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.persistence.JDBCPersistenceManager; + +import java.sql.Connection; +import java.sql.SQLException; + +/** + * Utility class for database operations. + */ +public class DatabaseUtils { + + private static final Log log = LogFactory.getLog(DatabaseUtils.class); + + /** + * Get a database connection instance from the Consent Management Persistence Manager. + * @return Database Connection + * @throws ConsentMgtException Error when getting a database connection to Consent Management database + */ + public static Connection getDBConnection() throws + ConsentMgtException { + + return JDBCPersistenceManager.getInstance().getDBConnection(); + } + + public static void closeConnection(Connection dbConnection) { + + if (dbConnection != null) { + try { + dbConnection.close(); + } catch (SQLException e) { + log.error("Database error. Could not close statement. Continuing with others. - " + + + e.getMessage().replaceAll("[\r\n]", ""), e); + } + } + } + + public static void rollbackTransaction(Connection dbConnection) throws + ConsentMgtException { + + JDBCPersistenceManager.getInstance().rollbackTransaction(dbConnection); + } + + public static void commitTransaction(Connection dbConnection) throws + ConsentMgtException { + + JDBCPersistenceManager.getInstance().commitTransaction(dbConnection); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml new file mode 100644 index 000000000..edd953abf --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-exclude.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml new file mode 100644 index 000000000..aead0b83d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/main/resources/findbugs-include.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOTests.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOTests.java new file mode 100644 index 000000000..7f3341fd5 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/impl/ConsentCoreDAOTests.java @@ -0,0 +1,2365 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.impl; + +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.queries.ConsentMgtCommonDBQueries; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.ConsentManagementDAOTestDataProvider; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.ConsentMgtDAOTestData; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.DAOUtils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Map; +import java.util.UUID; + +/** + * Consent management DAO tests. + */ +public class ConsentCoreDAOTests { + + private static final String DB_NAME = "CONSENT_DB"; + + private ConsentCoreDAO consentCoreDAO; + private Connection mockedConnection; + private PreparedStatement mockedPreparedStatement; + private ResultSet mockedResultSet; + + @BeforeClass + public void initTest() throws + Exception { + + DAOUtils.initializeDataSource(DB_NAME, DAOUtils.getFilePath("dbScripts/h2.sql")); + consentCoreDAO = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + mockedConnection = Mockito.mock(Connection.class); + mockedPreparedStatement = Mockito.mock(PreparedStatement.class); + mockedResultSet = Mockito.mock(ResultSet.class); + } + + @Test + public void testStoreConsentResource() throws + Exception { + + ConsentResource storedConsentResource; + ConsentResource consentResource = new ConsentResource(); + consentResource.setReceipt(ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); + consentResource.setClientID(UUID.randomUUID().toString()); + consentResource.setConsentType(ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE); + consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + consentResource.setConsentFrequency(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY); + consentResource.setValidityPeriod(ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); + consentResource.setConsentID(UUID.randomUUID().toString()); + consentResource.setRecurringIndicator(true); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + } + Assert.assertNotNull(storedConsentResource); + Assert.assertNotNull(storedConsentResource.getConsentID()); + Assert.assertNotNull(storedConsentResource.getClientID()); + Assert.assertNotNull(storedConsentResource.getConsentType()); + Assert.assertEquals(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY, + storedConsentResource.getConsentFrequency()); + Assert.assertTrue(storedConsentResource.getValidityPeriod() > 0); + Assert.assertTrue(storedConsentResource.isRecurringIndicator()); + Assert.assertTrue(storedConsentResource.getCreatedTime() > 0L); + Assert.assertNotNull(storedConsentResource.getCurrentStatus()); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentResourceInsertionError() throws + Exception { + + Mockito.doReturn(Mockito.mock(PreparedStatement.class)).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(Mockito.mock(PreparedStatement.class)).executeUpdate(); + + consentCoreDAO.storeConsentResource(mockedConnection, ConsentMgtDAOTestData.getSampleTestConsentResource()); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentResourceSQLError() throws + Exception { + + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentResource(mockedConnection, ConsentMgtDAOTestData.getSampleTestConsentResource()); + } + + @Test + public void testRetrieveConsentResource() throws + Exception { + + ConsentResource storedConsentResource; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, + storedConsentResource.getConsentID()); + } + + Assert.assertNotNull(retrievedConsentResource); + Assert.assertEquals(retrievedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertNotNull(retrievedConsentResource.getConsentID()); + Assert.assertNotNull(retrievedConsentResource.getClientID()); + Assert.assertNotNull(retrievedConsentResource.getConsentType()); + Assert.assertEquals(consentResource.getConsentFrequency(), storedConsentResource.getConsentFrequency()); + Assert.assertTrue(retrievedConsentResource.getValidityPeriod() > 0L); + Assert.assertTrue(retrievedConsentResource.isRecurringIndicator()); + Assert.assertTrue(retrievedConsentResource.getCreatedTime() > 0L); + Assert.assertNotNull(retrievedConsentResource.getCurrentStatus()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentResourceResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentResource(mockedConnection, Mockito.anyString()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentResource(mockedConnection, Mockito.any()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentResourceWithUnmatchedConsentID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.getConsentResource(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + } + + @Test + public void testRetrieveConsentWithAttributesResource() throws + Exception { + + ConsentAttributes consentAttributesResource; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(consentResource.getConsentID()); + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + retrievedConsentResource = consentCoreDAO.getConsentResourceWithAttributes(connection, + consentResource.getConsentID()); + } + Assert.assertNotNull(retrievedConsentResource); + Assert.assertEquals(retrievedConsentResource.getConsentID(), consentResource.getConsentID()); + Assert.assertNotNull(retrievedConsentResource.getConsentID()); + Assert.assertNotNull(retrievedConsentResource.getClientID()); + Assert.assertNotNull(retrievedConsentResource.getConsentType()); + Assert.assertEquals(consentResource.getConsentFrequency(), retrievedConsentResource.getConsentFrequency()); + Assert.assertTrue(retrievedConsentResource.getValidityPeriod() > 0L); + Assert.assertTrue(retrievedConsentResource.isRecurringIndicator()); + Assert.assertTrue(retrievedConsentResource.getCreatedTime() > 0L); + Assert.assertNotNull(retrievedConsentResource.getCurrentStatus()); + Assert.assertNotNull(retrievedConsentResource.getConsentAttributes()); + + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentWithAttributesResourceResultRetrieveError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); + Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); + Mockito.doReturn(false).when(mockedResultSet).next(); + consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentWithAttributesResourceResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentWithAttributesResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString(), + Mockito.anyInt(), Mockito.anyInt()); + consentCoreDAO.getConsentResourceWithAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test + public void testRetrieveDetailedConsentResource() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + ConsentMappingResource storedConsentMappingResource; + DetailedConsentResource retrievedDetailedConsentResource; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storedConsentResource = consentCoreDAO.storeConsentResource(connection, + ConsentMgtDAOTestData.getSampleTestConsentResource()); + consentCoreDAO.storeConsentAttributes(connection, + ConsentMgtDAOTestData.getSampleTestConsentAttributesObject(storedConsentResource.getConsentID())); + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, + ConsentMgtDAOTestData.getSampleTestConsentMappingResource(storedAuthorizationResource + .getAuthorizationID())); + retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, + storedConsentResource.getConsentID()); + } + + Assert.assertNotNull(retrievedDetailedConsentResource); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertEquals(retrievedDetailedConsentResource.getClientID(), storedConsentResource.getClientID()); + Assert.assertEquals(retrievedDetailedConsentResource.getReceipt(), storedConsentResource.getReceipt()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentType(), + storedConsentResource.getConsentType()); + Assert.assertEquals(retrievedDetailedConsentResource.getCurrentStatus(), + storedConsentResource.getCurrentStatus()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentFrequency(), + storedConsentResource.getConsentFrequency()); + Assert.assertEquals(retrievedDetailedConsentResource.getValidityPeriod(), + storedConsentResource.getValidityPeriod()); + Assert.assertEquals(retrievedDetailedConsentResource.isRecurringIndicator(), + storedConsentResource.isRecurringIndicator()); + Assert.assertNotNull(retrievedDetailedConsentResource.getConsentAttributes()); + Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), + storedAuthorizationResource.getAuthorizationID()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().get(0).getMappingID(), + storedConsentMappingResource.getMappingID()); + } + + @Test + public void testRetrieveDetailedConsentResourceWithoutAttributes() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + ConsentMappingResource storedConsentMappingResource; + DetailedConsentResource retrievedDetailedConsentResource; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storedConsentResource = consentCoreDAO.storeConsentResource(connection, + ConsentMgtDAOTestData.getSampleTestConsentResource()); + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, + ConsentMgtDAOTestData.getSampleTestConsentMappingResource(storedAuthorizationResource + .getAuthorizationID())); + retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, + storedConsentResource.getConsentID()); + } + + Assert.assertNotNull(retrievedDetailedConsentResource); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertEquals(retrievedDetailedConsentResource.getClientID(), storedConsentResource.getClientID()); + Assert.assertEquals(retrievedDetailedConsentResource.getReceipt(), storedConsentResource.getReceipt()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentType(), + storedConsentResource.getConsentType()); + Assert.assertEquals(retrievedDetailedConsentResource.getCurrentStatus(), + storedConsentResource.getCurrentStatus()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentFrequency(), + storedConsentResource.getConsentFrequency()); + Assert.assertEquals(retrievedDetailedConsentResource.getValidityPeriod(), + storedConsentResource.getValidityPeriod()); + Assert.assertEquals(retrievedDetailedConsentResource.isRecurringIndicator(), + storedConsentResource.isRecurringIndicator()); + Assert.assertNotNull(retrievedDetailedConsentResource.getConsentAttributes()); + Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), + storedAuthorizationResource.getAuthorizationID()); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().get(0).getMappingID(), + storedConsentMappingResource.getMappingID()); + } + + @Test + public void testRetrieveDetailedConsentResourceWithMultipleConsentAttributeKeys() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResourceOne; + AuthorizationResource storedAuthorizationResourceTwo; + DetailedConsentResource retrievedDetailedConsentResource; + String resourceOne = "{\"accountID\": \"111\",\"permission\": \"read\"}"; + String resourceTwo = "{\"accountID\": \"222\",\"permission\": \"read\"}"; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storedConsentResource = consentCoreDAO.storeConsentResource(connection, + ConsentMgtDAOTestData.getSampleTestConsentResource()); + consentCoreDAO.storeConsentAttributes(connection, + ConsentMgtDAOTestData.getSampleTestConsentAttributesObject(storedConsentResource.getConsentID())); + // create two auth resources for same consent id + storedAuthorizationResourceOne = consentCoreDAO.storeAuthorizationResource(connection, + ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + storedAuthorizationResourceTwo = consentCoreDAO.storeAuthorizationResource(connection, + ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + // create a total of three mapping resources for created auth resources + // mapping resources for first auth resource with two account ids + consentCoreDAO.storeConsentMappingResource(connection, + ConsentMgtDAOTestData + .getSampleTestConsentMappingResourceWithResource(storedAuthorizationResourceOne + .getAuthorizationID(), resourceOne)); + consentCoreDAO.storeConsentMappingResource(connection, + ConsentMgtDAOTestData + .getSampleTestConsentMappingResourceWithResource(storedAuthorizationResourceOne + .getAuthorizationID(), resourceTwo)); + // mapping resource for second auth resource with a single account id + consentCoreDAO.storeConsentMappingResource(connection, + ConsentMgtDAOTestData + .getSampleTestConsentMappingResourceWithResource(storedAuthorizationResourceTwo + .getAuthorizationID(), resourceOne)); + retrievedDetailedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, + storedConsentResource.getConsentID()); + } + + Assert.assertNotNull(retrievedDetailedConsentResource); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentID(), storedConsentResource.getConsentID()); + Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(0).getAuthorizationID(), + storedAuthorizationResourceOne.getAuthorizationID()); + Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().get(1).getAuthorizationID(), + storedAuthorizationResourceTwo.getAuthorizationID()); + /* according to the created consent resource, retrieved consent resource should contain two auth + resources and + three mapping resources + */ + Assert.assertEquals(retrievedDetailedConsentResource.getAuthorizationResources().size(), 2); + Assert.assertEquals(retrievedDetailedConsentResource.getConsentMappingResources().size(), 3); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveDetailedConsentResourceError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getDetailedConsentResource(mockedConnection, Mockito.anyString()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveDetailedConsentResourceRetrieveError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); + Mockito.doReturn(false).when(mockedResultSet).next(); + consentCoreDAO.getDetailedConsentResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveDetailedConsentResourceResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getDetailedConsentResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test + public void testUpdateConsentStatus() throws + Exception { + + ConsentResource storedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + consentCoreDAO.updateConsentStatus(connection, storedConsentResource.getConsentID(), + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentStatusSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateConsentStatus(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentStatusWithUnmatchedConsentID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.updateConsentStatus(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + } + } + + @Test + public void testUpdateConsentReceipt() throws + Exception { + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + String newConsentReceipt = "{\"amendedReceipt\":\"amendedData\"}"; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, + consentResource); + consentCoreDAO.updateConsentReceipt(connection, storedConsentResource.getConsentID(), newConsentReceipt); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentReceiptSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateConsentReceipt(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentReceiptUpdateError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + consentCoreDAO.updateConsentReceipt(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); + } + + @Test + public void testUpdateConsentValidityTime() throws + Exception { + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + long newConsentValidityTime = 12345; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, + consentResource); + consentCoreDAO.updateConsentValidityTime(connection, storedConsentResource.getConsentID(), + newConsentValidityTime); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentValidityTimeSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateConsentValidityTime(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentValidityTimeUpdateError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + consentCoreDAO.updateConsentValidityTime(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); + } + + @Test + public void testStoreAuthorizationResource() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResource.setConsentID(storedConsentResource.getConsentID()); + authorizationResource.setAuthorizationType(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE); + authorizationResource.setUserID(ConsentMgtDAOTestData.SAMPLE_USER_ID); + authorizationResource.setAuthorizationStatus(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + } + Assert.assertNotNull(storedAuthorizationResource.getConsentID()); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationType()); + Assert.assertNotNull(storedAuthorizationResource.getUserID()); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationStatus()); + Assert.assertTrue(storedAuthorizationResource.getUpdatedTime() > 0L); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationID()); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreAuthorizationResourceInsertionError() throws + Exception { + + ConsentResource storedConsentResource = ConsentMgtDAOTestData.getSampleStoredTestConsentResource(); + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + + consentCoreDAO.storeAuthorizationResource(mockedConnection, ConsentMgtDAOTestData. + getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreAuthorizationResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + + consentCoreDAO.storeAuthorizationResource(mockedConnection, ConsentMgtDAOTestData. + getSampleTestAuthorizationResource(Mockito.anyString())); + } + + @Test + public void testRetrieveAuthorizationResource() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource authorizationResource; + AuthorizationResource storedAuthorizationResource; + AuthorizationResource retrievedAuthorizationResource; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + + retrievedAuthorizationResource = consentCoreDAO.getAuthorizationResource(connection, + storedAuthorizationResource.getAuthorizationID(), storedConsentResource.getOrgID()); + } + Assert.assertTrue(retrievedAuthorizationResource.getUpdatedTime() > 0L); +// Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationID()); + Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationStatus()); + Assert.assertNotNull(retrievedAuthorizationResource.getUserID()); + Assert.assertNotNull(retrievedAuthorizationResource.getAuthorizationType()); + Assert.assertEquals(retrievedAuthorizationResource.getConsentID(), + storedAuthorizationResource.getConsentID()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveAuthorizationResourceResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getAuthorizationResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + ConsentMgtDAOTestData.SAMPLE_ORG_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveAuthorizationResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getAuthorizationResource(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + ConsentMgtDAOTestData.SAMPLE_ORG_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveAuthorizationResourceWithUnmatchedAuthID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.getAuthorizationResource(connection, + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, ConsentMgtDAOTestData.SAMPLE_ORG_ID); + } + } + + @Test + public void testUpdateAuthorizationStatus() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource authorizationResource; + AuthorizationResource storedAuthorizationResource; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + + consentCoreDAO.updateAuthorizationStatus(connection, storedAuthorizationResource.getAuthorizationID(), + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateAuthorizationStatusSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateAuthorizationStatus(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateAuthorizationStatusWithUnmatchedAuthID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.updateAuthorizationStatus(connection, + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + } + } + + @Test + public void testUpdateAuthorizationUser() throws + Exception { + + ConsentResource storedConsentResource; + AuthorizationResource authorizationResource; + AuthorizationResource storedAuthorizationResource; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + + consentCoreDAO.updateAuthorizationUser(connection, storedAuthorizationResource.getAuthorizationID(), + ConsentMgtDAOTestData.SAMPLE_NEW_USER_ID); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateAuthorizationUserSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateAuthorizationUser(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + ConsentMgtDAOTestData.SAMPLE_USER_ID); + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateAuthorizationUserWithUnmatchedAuthID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.updateAuthorizationUser(connection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + ConsentMgtDAOTestData.SAMPLE_NEW_USER_ID); + } + } + + @Test + public void testStoreConsentMappingResource() throws + Exception { + + ConsentResource consentResource; + AuthorizationResource authorizationResource; + ConsentMappingResource consentMappingResource; + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + ConsentMappingResource storedConsentMappingResource; + + consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + + consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(storedAuthorizationResource.getAuthorizationID()); + consentMappingResource.setResource(ConsentMgtDAOTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + + storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource); + } + Assert.assertNotNull(storedConsentMappingResource.getMappingID()); + Assert.assertNotNull(storedConsentMappingResource.getAuthorizationID()); + Assert.assertNotNull(storedConsentMappingResource.getResource()); + Assert.assertNotNull(storedConsentMappingResource.getMappingStatus()); + } + + @Test + public void testStoreConsentMappingResourceWithID() throws + Exception { + + ConsentResource consentResource; + AuthorizationResource authorizationResource; + ConsentMappingResource consentMappingResource; + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + ConsentMappingResource storedConsentMappingResource; + + consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + authorizationResource.setAuthorizationID("db0b943d-38e2-47e4-bb78-8a242d279b5a"); + authorizationResource.setUpdatedTime(1669917425); + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + + consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(storedAuthorizationResource.getAuthorizationID()); + consentMappingResource.setMappingID("aa4c943d-38e2-47e5-bb78-8a242d279b5a"); + consentMappingResource.setResource(ConsentMgtDAOTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + + storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource); + } + Assert.assertEquals(storedConsentMappingResource.getMappingID(), "aa4c943d-38e2-47e5-bb78-8a242d279b5a"); + Assert.assertEquals(storedConsentMappingResource.getAuthorizationID(), "db0b943d-38e2-47e4-bb78-8a242d279b5a"); + Assert.assertNotNull(storedConsentMappingResource.getResource()); + Assert.assertNotNull(storedConsentMappingResource.getMappingStatus()); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentMappingResourceInsertionError() throws + Exception { + + ConsentMappingResource sampleConsentMappingResource = + ConsentMgtDAOTestData.getSampleTestConsentMappingResource(ConsentMgtDAOTestData + .getSampleStoredTestAuthorizationResource().getAuthorizationID()); + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + + consentCoreDAO.storeConsentMappingResource(mockedConnection, sampleConsentMappingResource); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentMappingResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentMappingResource(mockedConnection, new ConsentMappingResource()); + } + + @Test + public void testRetrieveConsentMappingResource() throws + Exception { + + ArrayList retrievedConsentMappingResources; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + AuthorizationResource authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + AuthorizationResource storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + ConsentMappingResource consentMappingResource = ConsentMgtDAOTestData + .getSampleTestConsentMappingResource(storedAuthorizationResource.getAuthorizationID()); + consentCoreDAO.storeConsentMappingResource(connection, consentMappingResource); + + retrievedConsentMappingResources = consentCoreDAO.getConsentMappingResources(connection, + storedAuthorizationResource.getAuthorizationID()); + } + Assert.assertNotNull(retrievedConsentMappingResources); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentMappingResourceResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentMappingResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentMappingResources(mockedConnection, ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); + } + + @Test + public void testUpdateConsentMappingStatus() throws + Exception { + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + AuthorizationResource authorizationResource = ConsentMgtDAOTestData + .getSampleTestAuthorizationResource(storedConsentResource.getConsentID()); + AuthorizationResource storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + ConsentMappingResource consentMappingResource = ConsentMgtDAOTestData + .getSampleTestConsentMappingResource(storedAuthorizationResource.getAuthorizationID()); + ConsentMappingResource storedConsentMappingResource = consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource); + + ArrayList mappingIDs = new ArrayList() { + { + add(storedConsentMappingResource.getMappingID()); + } + }; + + consentCoreDAO.updateConsentMappingStatus(connection, mappingIDs, + ConsentMgtDAOTestData.SAMPLE_NEW_MAPPING_STATUS); + } + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentMappingStatusSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.updateConsentMappingStatus(mockedConnection, ConsentMgtDAOTestData.UNMATCHED_MAPPING_IDS, + ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + } + + @Test + public void testStoreConsentAttributes() throws + Exception { + + ConsentResource storedConsentResource; + ConsentAttributes consentAttributesResource; + boolean isConsentAttributesStored; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + consentAttributesResource = new ConsentAttributes(); + consentAttributesResource.setConsentID(storedConsentResource.getConsentID()); + consentAttributesResource.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + } + Assert.assertTrue(isConsentAttributesStored); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentAttributesSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentAttributes(mockedConnection, ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(ConsentMgtDAOTestData.getSampleStoredTestConsentResource() + .getConsentID())); + } + + @Test + public void testRetrieveConsentAttributes() throws + Exception { + + ConsentAttributes retrievedConsentAttributesResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, + consentResource.getConsentID()); + + ConsentAttributes consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); + + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, + retrievedConsentResource.getConsentID()); + } + Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); + Assert.assertNotNull(retrievedConsentAttributesResource.getConsentAttributes()); + } + + @Test + public void testRetrieveConsentAttributesForNoAttributesScenario() throws + Exception { + + ConsentAttributes retrievedConsentAttributesResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, + consentResource.getConsentID()); + + retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, + retrievedConsentResource.getConsentID()); + } + Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); + Assert.assertTrue(retrievedConsentAttributesResource.getConsentAttributes().isEmpty()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.any()); + } + +// @Test +// public void testRetrieveConsentAttributes() throws Exception { +// +// ConsentAttributes retrievedConsentAttributesResource; +// ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); +// +// try (Connection connection = DAOUtils.getConnection(DB_NAME)) { +// consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); +// ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, +// consentResource.getConsentID()); +// +// ConsentAttributes consentAttributesResource = ConsentMgtDAOTestData +// .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); +// +// consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); +// +// retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, +// retrievedConsentResource.getConsentID(), ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); +// } +// Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); +// Assert.assertNotNull(retrievedConsentAttributesResource.getConsentAttributes()); +// } + +// @Test +// public void testRetrieveConsentAttributesForNoAttributesScenario() throws Exception { +// +// ConsentAttributes retrievedConsentAttributesResource; +// ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); +// +// try (Connection connection = DAOUtils.getConnection(DB_NAME)) { +// consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); +// ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, +// consentResource.getConsentID()); +// +// retrievedConsentAttributesResource = consentCoreDAO.getConsentAttributes(connection, +// retrievedConsentResource.getConsentID(), ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); +// } +// Assert.assertNotNull(retrievedConsentAttributesResource.getConsentID()); +// Assert.assertTrue(retrievedConsentAttributesResource.getConsentAttributes().isEmpty()); +// } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesResultSetErrorOverloadedMethod() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString(), + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesSQLErrorOverloadedMethod() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentAttributes(mockedConnection, Mockito.anyString(), + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test + public void testRetrieveConsentAttributesByName() throws + Exception { + + ConsentAttributes consentAttributesResource; + Map retrievedValuesMap; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); + + consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); + + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + retrievedValuesMap = consentCoreDAO.getConsentAttributesByName(connection, + "x-request-id"); + + } + Assert.assertTrue(retrievedValuesMap.containsKey(consentAttributesResource.getConsentID())); + Assert.assertTrue(retrievedValuesMap.containsValue(consentAttributesResource.getConsentAttributes().get("x" + + "-request-id"))); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesByNameSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentAttributesByName(mockedConnection, Mockito.any()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentAttributesByNameResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentAttributesByName(mockedConnection, Mockito.anyString()); + } + + @Test + public void testRetrieveConsentIdByConsentAttributeNameAndValue() throws + Exception { + + ArrayList consentIdList; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, + consentResource.getConsentID()); + ConsentAttributes consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + consentIdList = consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(connection, + "payment-type", "domestic-payments"); + + } + Assert.assertFalse(consentIdList.isEmpty()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentIdByConsentAttributeNameAndValueSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, "payment-type", + "domestic-payments"); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentIdByConsentAttributeNameAndValueResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, "payment-type", + "domestic-payments"); + } + + @Test + public void testRetrieveConsentIdByConsentAttributeNameAndValueNoRecordsFoundError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); + Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); + ArrayList consentIdList = consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(mockedConnection, + "payment-type", "domestic-payments"); + Assert.assertTrue(consentIdList.isEmpty()); + } + + @Test + public void testUpdateConsentAttributes() throws + Exception { + + DetailedConsentResource createdConsentResource; + DetailedConsentResource updatedConsentResource; + ConsentAttributes consentAttributesResource; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + consentAttributesResource = new ConsentAttributes(); + consentAttributesResource.setConsentID(storedConsentResource.getConsentID()); + consentAttributesResource.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + createdConsentResource = consentCoreDAO.getDetailedConsentResource(connection, + storedConsentResource.getConsentID()); + + consentCoreDAO.updateConsentAttributes(connection, storedConsentResource.getConsentID(), + ConsentMgtDAOTestData.CONSENT_ATTRIBUTES_MAP_FOR_UPDATE); + updatedConsentResource = consentCoreDAO.getDetailedConsentResource(connection, + storedConsentResource.getConsentID()); + } + Assert.assertEquals(createdConsentResource.getConsentID(), updatedConsentResource.getConsentID()); + Assert.assertNotEquals(createdConsentResource.getConsentAttributes(), + updatedConsentResource.getConsentAttributes()); + Assert.assertEquals(updatedConsentResource.getConsentAttributes().get("payment-type"), + "international-payments"); + + } + + @Test(expectedExceptions = ConsentDataUpdationException.class) + public void testUpdateConsentAttributesSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + + consentCoreDAO.updateConsentAttributes(mockedConnection, ConsentMgtDAOConstants.CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test + public void testDeleteConsentAttribute() throws + Exception { + + boolean isDeleted; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + ConsentAttributes consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(storedConsentResource.getConsentID()); + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + isDeleted = consentCoreDAO.deleteConsentAttributes(connection, storedConsentResource.getConsentID(), + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + Assert.assertTrue(isDeleted); + } + + @Test(expectedExceptions = ConsentDataDeletionException.class) + public void testDeleteConsentAttributeSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.deleteConsentAttributes(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test + public void testStoreConsentFile() throws + Exception { + + boolean isConsentFileStored; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + ConsentFile consentFileResource = new ConsentFile(); + consentFileResource.setConsentID(storedConsentResource.getConsentID()); + consentFileResource.setConsentFile(ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE); + + isConsentFileStored = consentCoreDAO.storeConsentFile(connection, consentFileResource); + } + Assert.assertTrue(isConsentFileStored); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentFileInsertionError() throws + Exception { + + ConsentFile sampleConsentFileResource = + ConsentMgtDAOTestData.getSampleConsentFileObject(ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE); + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + consentCoreDAO.storeConsentFile(mockedConnection, sampleConsentFileResource); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentFileSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentFile(mockedConnection, Mockito.any()); + } + + @Test + public void testRetrieveConsentFileResource() throws + Exception { + + ConsentFile retrievedConsentFileResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, + consentResource.getConsentID()); + + ConsentFile consentFileResource = new ConsentFile(); + consentFileResource.setConsentID(retrievedConsentResource.getConsentID()); + consentFileResource.setConsentFile(ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE); + + consentCoreDAO.storeConsentFile(connection, consentFileResource); + + retrievedConsentFileResource = consentCoreDAO.getConsentFile(connection, + consentFileResource.getConsentID()); + } + Assert.assertNotNull(retrievedConsentFileResource.getConsentID()); + Assert.assertNotNull(retrievedConsentFileResource.getConsentFile()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentFileResourceNoRecordsFoundError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); + Mockito.doReturn(false).when(mockedResultSet).next(); + consentCoreDAO.getConsentFile(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentFileResourceSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentFile(mockedConnection, Mockito.any()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentFileResourceRetrieveError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentFile(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentFileResourceWithUnmatchedConsentID() throws + Exception { + + ConsentFile consentFileResource; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); + + consentFileResource = new ConsentFile(); + consentFileResource.setConsentID(retrievedConsentResource.getConsentID()); + consentFileResource.setConsentFile(ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE); + + consentCoreDAO.storeConsentFile(connection, consentFileResource); + consentCoreDAO.getConsentFile(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + } + } + + @Test + public void testConsentSearchWithConsentIDsList() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, consentIDs, null, + null, null, null, null, null, + 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithConsentIDsListAndTime() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, consentIDs, null, + null, null, null, 1669917425L, 1669917425L, + 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + + } + + @Test + public void testConsentSearchWithClientIDsList() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, + ConsentMgtDAOTestData.SAMPLE_CLIENT_IDS_LIST, null, null, null, + null, null, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithConsentStatusesList() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, null, + null, ConsentMgtDAOTestData.SAMPLE_CONSENT_STATUSES_LIST, null, null, + null, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithConsentTypesList() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, null, + null, ConsentMgtDAOTestData.SAMPLE_CONSENT_STATUSES_LIST, null, null, + null, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithUserIDsList() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, null, + null, null, ConsentMgtDAOTestData.SAMPLE_USER_IDS_LIST, null, + null, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithoutLimitAndOffset() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, consentIDs, null, + null, null, null, null, null, null, + null); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithoutLimitButOffset() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, consentIDs, null, + null, null, null, null, null, null, + 1); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchForNullValues() throws + Exception { + + ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); + Mockito.doReturn(null).when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); + Mockito.doReturn(null).when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); + ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + ArrayList authorizationResources = new ArrayList<>(); + ArrayList consentMappingResources = new ArrayList<>(); + dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, + mockedResultSetTemp, ""); + dao.setAccountConsentMappingDataInResponse(consentMappingResources, + mockedResultSetTemp); + Assert.assertEquals(authorizationResources.size(), 0); + Assert.assertEquals(consentMappingResources.size(), 0); + } + + @Test + public void testConsentSearchForNoneNullValues() throws + Exception { + + ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.ACCOUNT_ID); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_STATUS); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.PERMISSION); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_TYPE); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_STATUS); + Mockito.doReturn("123456").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.UPDATED_TIME); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.USER_ID); + ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + ArrayList authorizationResources = new ArrayList<>(); + ArrayList consentMappingResources = new ArrayList<>(); + dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, + mockedResultSetTemp, ""); + dao.setAccountConsentMappingDataInResponse(consentMappingResources, + mockedResultSetTemp); + Assert.assertTrue(authorizationResources.size() != 0); + Assert.assertTrue(consentMappingResources.size() != 0); + } + + @Test + public void testConsentSearchForNoneNullValuesNegativeCase() throws + Exception { + + ResultSet mockedResultSetTemp = Mockito.mock(ResultSet.class); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_ID); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_ID); + Mockito.doReturn("1,2").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.ACCOUNT_ID); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.MAPPING_STATUS); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.PERMISSION); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_TYPE); + Mockito.doReturn("test").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.AUTH_STATUS); + Mockito.doReturn("123456").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.UPDATED_TIME); + Mockito.doReturn("test,test2").when(mockedResultSetTemp).getString(ConsentMgtDAOConstants.USER_ID); + ConsentCoreDAOImpl dao = new ConsentCoreDAOImpl(new ConsentMgtCommonDBQueries()); + ArrayList authorizationResources = new ArrayList<>(); + ArrayList consentMappingResources = new ArrayList<>(); + dao.setAuthorizationDataInResponseForGroupedQuery(authorizationResources, + mockedResultSetTemp, ""); + dao.setAccountConsentMappingDataInResponse(consentMappingResources, + mockedResultSetTemp); + Assert.assertTrue(authorizationResources.size() != 0); + Assert.assertTrue(consentMappingResources.size() != 0); + } + + @Test + public void testConsentSearchWithoutOffsetButLimit() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, consentIDs, null, + null, null, null, null, null, 1, + null); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithNoParams() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, null, + null, null, null, null, + null, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + } + } + + @Test + public void testConsentSearchWithTimePeriod() throws + Exception { + + ArrayList detailedConsentResources; + ArrayList consentIDs = new ArrayList<>(); + long currentTime = System.currentTimeMillis() / 1000; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + storeDataForConsentSearchTest(consentIDs, connection); + detailedConsentResources = consentCoreDAO.searchConsents(connection, null, null, null, + null, null, null, currentTime, + currentTime + 100, 10, 0); + } + + Assert.assertNotNull(detailedConsentResources); + for (DetailedConsentResource resource : detailedConsentResources) { + Assert.assertNotNull(resource.getAuthorizationResources()); + Assert.assertNotNull(resource.getConsentMappingResources()); + Assert.assertNotNull(resource.getConsentAttributes()); + + for (AuthorizationResource authResource : resource.getAuthorizationResources()) { + Assert.assertEquals(resource.getConsentID(), authResource.getConsentID()); + } + + Assert.assertTrue((currentTime <= resource.getUpdatedTime()) + && (currentTime + 100 >= resource.getUpdatedTime())); + } + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testSearchConsentsSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString(), + Mockito.anyInt(), Mockito.anyInt()); + consentCoreDAO.searchConsents(mockedConnection, null, null, null, null, + null, null, null, null, null, null); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testSearchConsentsPreparedResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.searchConsents(mockedConnection, null, null, null, null, + null, null, null, null, null, null); + } + + @Test + public void testSearchConsentAuthorizations() throws + Exception { + + ArrayList authorizationResources; + ConsentResource storedConsentResource; + AuthorizationResource storedAuthorizationResource; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, ConsentMgtDAOTestData + .getSampleTestConsentResource()); + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + ConsentMgtDAOTestData.getSampleTestAuthorizationResource(storedConsentResource.getConsentID())); + + authorizationResources = consentCoreDAO.searchConsentAuthorizations(connection, + storedConsentResource.getConsentID(), storedAuthorizationResource.getUserID()); + } + + Assert.assertNotNull(authorizationResources); + Assert.assertEquals(storedAuthorizationResource.getAuthorizationID(), + authorizationResources.get(0).getAuthorizationID()); + Assert.assertEquals(storedAuthorizationResource.getConsentID(), + authorizationResources.get(0).getConsentID()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testSearchConsentAuthorizationsSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_USER_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testSearchConsentAuthorizationsResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_USER_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testSearchConsentAuthorizationsNoRecordsFoundError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); + Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); + consentCoreDAO.searchConsentAuthorizations(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_USER_ID); + } + + @Test + public void testStoreConsentStatusAuditRecord() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); + consentStatusAuditRecord.setConsentID(storedConsentResource.getConsentID()); + consentStatusAuditRecord.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + consentStatusAuditRecord.setReason(ConsentMgtDAOTestData.SAMPLE_REASON); + consentStatusAuditRecord.setActionBy(ConsentMgtDAOTestData.SAMPLE_ACTION_BY); + consentStatusAuditRecord.setPreviousStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + } + Assert.assertNotNull(storedConsentStatusAuditRecord.getConsentID()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getCurrentStatus()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getReason()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getActionBy()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getPreviousStatus()); + Assert.assertTrue(storedConsentStatusAuditRecord.getActionTime() > 0L); + Assert.assertNotNull(storedConsentStatusAuditRecord.getStatusAuditID()); + } + + @Test + public void testStoreConsentStatusAuditRecordWithConsentId() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + consentResource.setConsentID("234ba17f-c3ac-4493-9049-d71f99c36dc2"); + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); + consentStatusAuditRecord.setConsentID(storedConsentResource.getConsentID()); + consentStatusAuditRecord.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + consentStatusAuditRecord.setReason(ConsentMgtDAOTestData.SAMPLE_REASON); + consentStatusAuditRecord.setActionBy(ConsentMgtDAOTestData.SAMPLE_ACTION_BY); + consentStatusAuditRecord.setPreviousStatus(ConsentMgtDAOTestData.SAMPLE_PREVIOUS_STATUS); + consentStatusAuditRecord.setActionTime(1669917425); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + } + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), "234ba17f-c3ac-4493-9049-d71f99c36dc2"); + Assert.assertNotNull(storedConsentStatusAuditRecord.getCurrentStatus()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getReason()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getActionBy()); + Assert.assertNotNull(storedConsentStatusAuditRecord.getPreviousStatus()); + Assert.assertTrue(storedConsentStatusAuditRecord.getActionTime() > 0L); + Assert.assertNotNull(storedConsentStatusAuditRecord.getStatusAuditID()); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentStatusAuditRecordInsertionError() throws + Exception { + + ConsentStatusAuditRecord sampleConsentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(mockedPreparedStatement).executeUpdate(); + consentCoreDAO.storeConsentStatusAuditRecord(mockedConnection, sampleConsentStatusAuditRecord); + } + + @Test(expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentStatusAuditRecordSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentStatusAuditRecord(mockedConnection, new ConsentStatusAuditRecord()); + } + + @Test + public void testRetrieveConsentStatusAuditRecordsWithConsentID() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + connection.commit(); + + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, + storedConsentStatusAuditRecord.getConsentID(), null, + null, null, null, null); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); + } + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentStatusAuditRecordsResultSetError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentStatusAuditRecords(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, ConsentMgtDAOTestData.SAMPLE_ACTION_BY, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, ConsentMgtDAOTestData.SAMPLE_AUDIT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentStatusAuditRecordsSQLError() throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentStatusAuditRecords(mockedConnection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, ConsentMgtDAOTestData.SAMPLE_ACTION_BY, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, ConsentMgtDAOTestData.SAMPLE_AUDIT_ID); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveConsentStatusAuditRecordByConsentIDWithUnmatchedConsentID() throws + Exception { + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentCoreDAO.getConsentStatusAuditRecords(connection, ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + null, null, null, null, null); + } + } + + @Test + public void testRetrieveConsentStatusAuditRecordsByConsentIDAndStatus() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, + storedConsentStatusAuditRecord.getConsentID(), storedConsentStatusAuditRecord.getCurrentStatus(), + null, null, null, null); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); + Assert.assertEquals(storedConsentStatusAuditRecord.getCurrentStatus(), record.getCurrentStatus()); + } + } + + @Test + public void testRetrieveConsentStatusAuditRecordsByConsentIDStatusAndActionBy() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, + storedConsentStatusAuditRecord.getConsentID(), storedConsentStatusAuditRecord.getCurrentStatus(), + storedConsentStatusAuditRecord.getActionBy(), null, null, null); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); + Assert.assertEquals(storedConsentStatusAuditRecord.getCurrentStatus(), record.getCurrentStatus()); + Assert.assertEquals(storedConsentStatusAuditRecord.getActionBy(), record.getActionBy()); + } + } + + @Test + public void testRetrieveConsentAuditRecordByAuditRecordID() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, + null, null, null, null, null, + storedConsentStatusAuditRecord.getStatusAuditID()); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); + Assert.assertEquals(storedConsentStatusAuditRecord.getStatusAuditID(), record.getStatusAuditID()); + } + } + + @Test + public void testRetrieveConsentAuditRecordForGivenTime() throws + Exception { + + long fromTime; + long toTime; + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + fromTime = Long.sum(storedConsentStatusAuditRecord.getActionTime(), -60); + toTime = Long.sum(storedConsentStatusAuditRecord.getActionTime(), 60); + + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, + storedConsentStatusAuditRecord.getConsentID(), null, + null, fromTime, toTime, null); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentResource.getConsentID(), record.getConsentID()); + Assert.assertTrue((record.getActionTime() >= fromTime) && (record.getActionTime() <= toTime)); + } + } + + @Test + public void testGetConsentStatusAuditRecordsByConsentId() throws + Exception { + + ConsentResource storedConsentResource; + ConsentStatusAuditRecord consentStatusAuditRecord; + ConsentStatusAuditRecord storedConsentStatusAuditRecord; + ArrayList retrievedConsentStatusAuditRecords; + ArrayList retrievedConsentStatusAuditRecordsWithLimit; + ArrayList retrievedConsentStatusAuditRecordsWithLimitAndOffset; + ArrayList retrievedConsentStatusAuditRecordsWithLimitOnly; + ArrayList retrievedConsentStatusAuditRecordsWithOffsetOnly; + + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + + storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + + consentStatusAuditRecord = ConsentMgtDAOTestData + .getSampleTestConsentStatusAuditRecord(storedConsentResource.getConsentID(), + storedConsentResource.getCurrentStatus()); + + storedConsentStatusAuditRecord = consentCoreDAO.storeConsentStatusAuditRecord(connection, + consentStatusAuditRecord); + + connection.commit(); + ArrayList consentIds = new ArrayList<>(); + consentIds.add(storedConsentStatusAuditRecord.getConsentID()); + retrievedConsentStatusAuditRecords = consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, + consentIds, null, null); + retrievedConsentStatusAuditRecordsWithLimit = + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, 0); + retrievedConsentStatusAuditRecordsWithLimitAndOffset = + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, 1); + retrievedConsentStatusAuditRecordsWithLimitOnly = + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, 10, null); + retrievedConsentStatusAuditRecordsWithOffsetOnly = + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIds, null, 1); + } + Assert.assertNotNull(retrievedConsentStatusAuditRecords); + Assert.assertNotNull(retrievedConsentStatusAuditRecordsWithLimit); + Assert.assertTrue(retrievedConsentStatusAuditRecordsWithLimit.size() > 0); + Assert.assertTrue(retrievedConsentStatusAuditRecordsWithLimitAndOffset.isEmpty()); + Assert.assertFalse(retrievedConsentStatusAuditRecordsWithLimitOnly.isEmpty()); + Assert.assertFalse(retrievedConsentStatusAuditRecordsWithOffsetOnly.isEmpty()); + for (ConsentStatusAuditRecord record : + retrievedConsentStatusAuditRecords) { + Assert.assertEquals(storedConsentStatusAuditRecord.getConsentID(), record.getConsentID()); + } + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testGetConsentStatusAuditRecordsByConsentIdSQLError() throws + Exception { + ArrayList consentIds = new ArrayList<>(); + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(mockedConnection, + consentIds, null, null); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testGetConsentStatusAuditRecordsByConsentIdSQLErrorForResults() throws + Exception { + ArrayList consentIds = new ArrayList<>(); + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getConsentStatusAuditRecordsByConsentId(mockedConnection, + consentIds, null, null); + } + + @Test(dataProvider = "storeConsentHistoryDataProvider", + dataProviderClass = ConsentManagementDAOTestDataProvider.class) + public void testStoreConsentAmendmentHistory(String historyID, String recordID, String changedAttributes, + String consentType, long amendedTimestamp, String amendmentReason) + throws + Exception { + + boolean result; + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + result = consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + recordID, consentType, changedAttributes, amendmentReason); + } + Assert.assertTrue(result); + } + + @Test(dataProvider = "storeConsentHistoryDataProvider", + dataProviderClass = ConsentManagementDAOTestDataProvider.class, + expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentAmendmentHistoryWithInvalidConsentType(String historyID, String recordID, + String changedAttributes, String consentType, + long amendedTimestamp, String amendmentReason) + throws + Exception { + + boolean result; + consentType = "sampleConsentType"; + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + result = consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + recordID, consentType, changedAttributes, amendmentReason); + } + Assert.assertTrue(result); + } + + @Test(dataProvider = "storeConsentHistoryDataProvider", + dataProviderClass = ConsentManagementDAOTestDataProvider.class, + expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentAmendmentHistoryInsertionError(String historyID, String recordID, + String changedAttributes, String consentType, + long amendedTimestamp, + String amendmentReason) + throws + Exception { + + Mockito.doReturn(Mockito.mock(PreparedStatement.class)).when(mockedConnection) + .prepareStatement(Mockito.anyString()); + Mockito.doReturn(0).when(Mockito.mock(PreparedStatement.class)).executeUpdate(); + + consentCoreDAO.storeConsentAmendmentHistory(mockedConnection, historyID, amendedTimestamp, + recordID, consentType, changedAttributes, amendmentReason); + } + + @Test(dataProvider = "storeConsentHistoryDataProvider", + dataProviderClass = ConsentManagementDAOTestDataProvider.class, + expectedExceptions = ConsentDataInsertionException.class) + public void testStoreConsentAmendmentHistorySQLError(String historyID, String recordID, + String changedAttributes, String consentType, + long amendedTimestamp, String amendmentReason) + throws + Exception { + + Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); + consentCoreDAO.storeConsentAmendmentHistory(mockedConnection, historyID, amendedTimestamp, + recordID, consentType, changedAttributes, amendmentReason); + } + +// @Test(dependsOnMethods = {"testStoreConsentAmendmentHistory"}) +// public void testRetrieveConsentAmendmentHistory() throws Exception { +// +// Map consentHistoryResourcesDataMap; +// String[] expectedConsentDataTypes = { ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, +// ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, +// ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, +// ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, +// "AmendedReason"}; +// +// List expectedConsentDataTypesList = Arrays.asList(expectedConsentDataTypes); +// +// try (Connection connection = DAOUtils.getConnection(DB_NAME)) { +// +// consentHistoryResourcesDataMap = consentCoreDAO.retrieveConsentAmendmentHistory(connection, +// ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory(), ); +// Assert.assertNotNull(consentHistoryResourcesDataMap); +// for (Map.Entry consentHistoryDataEntry : +// consentHistoryResourcesDataMap.entrySet()) { +// Assert.assertEquals(ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, consentHistoryDataEntry.getKey()); +// Map consentHistoryData = +// consentHistoryDataEntry.getValue().getChangedAttributesJsonDataMap(); +// for (Map.Entry consentHistoryDataTypeEntry : +// consentHistoryData.entrySet()) { +// Assert.assertNotNull(consentHistoryDataTypeEntry.getKey()); +// Assert.assertTrue(expectedConsentDataTypesList.contains((consentHistoryDataTypeEntry.getKey()))); +// Assert.assertNotNull(consentHistoryDataTypeEntry.getValue()); +// } +// } +// } +// } +// +// @Test (expectedExceptions = ConsentDataRetrievalException.class) +// public void testRetrieveConsentAmendmentHistoryDataRetrievalError() throws Exception { +// +// Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); +// Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); +// consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, +// ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); +// } +// +// @Test (expectedExceptions = ConsentDataRetrievalException.class) +// public void testRetrieveConsentAmendmentHistoryPrepStmtSQLError() throws Exception { +// +// Mockito.doThrow(SQLException.class).when(mockedConnection).prepareStatement(Mockito.anyString()); +// consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, +// ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); +// } +// +// @Test +// public void testRetrieveConsentAmendmentHistoryNoRecordsFound() throws Exception { +// +// Mockito.doReturn(mockedPreparedStatement).when(mockedConnection) +// .prepareStatement(Mockito.anyString()); +// Mockito.doReturn(mockedResultSet).when(mockedPreparedStatement).executeQuery(); +// Mockito.doReturn(false).when(mockedResultSet).isBeforeFirst(); +// +// Map result = consentCoreDAO.retrieveConsentAmendmentHistory(mockedConnection, +// ConsentMgtDAOTestData.getRecordIDListOfSampleConsentHistory()); +// Assert.assertEquals(result.size(), 0); +// } + + @Test + public void testRetrieveExpiringConsentsWithNoEligibility() throws + Exception { + + ConsentAttributes consentAttributesResource; + ArrayList expirationEligibleConsents; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleStoredTestConsentResource(); + consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_EXPIRED_STATUS); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); + + consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); + consentAttributesResource.getConsentAttributes().put( + ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE, "1632918113"); + + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + expirationEligibleConsents = consentCoreDAO.getExpiringConsents(connection, null, + "authorised,awaitingAuthorisation"); + + } + Assert.assertTrue(expirationEligibleConsents.isEmpty()); + } + + @Test(dependsOnMethods = {"testRetrieveExpiringConsentsWithNoEligibility"}) + public void testRetrieveExpiringConsentsWithEligibility() throws + Exception { + + ConsentAttributes consentAttributesResource; + ArrayList expirationEligibleConsents; + ConsentResource retrievedConsentResource; + ConsentResource consentResource = ConsentMgtDAOTestData.getSampleTestConsentResource(); + + try (Connection connection = DAOUtils.getConnection(DB_NAME)) { + consentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentResource.getConsentID()); + + consentAttributesResource = ConsentMgtDAOTestData + .getSampleTestConsentAttributesObject(retrievedConsentResource.getConsentID()); + consentAttributesResource.getConsentAttributes().put( + ConsentMgtDAOConstants.CONSENT_EXPIRY_TIME_ATTRIBUTE, "1632918113"); + + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + + expirationEligibleConsents = + consentCoreDAO.getExpiringConsents(connection, ConsentMgtDAOConstants.DEFAULT_ORG, + "authorised,awaitingAuthorisation"); + + } + Assert.assertFalse(expirationEligibleConsents.isEmpty()); + } + + @Test(expectedExceptions = ConsentDataRetrievalException.class) + public void testRetrieveExpiringConsentsDataRetrievalError() throws + Exception { + + Mockito.doReturn(mockedPreparedStatement).when(mockedConnection).prepareStatement(Mockito.anyString()); + Mockito.doThrow(SQLException.class).when(mockedPreparedStatement).executeQuery(); + consentCoreDAO.getExpiringConsents(mockedConnection, null, "authorised,awaitingAuthorisation"); + } + + private void storeDataForConsentSearchTest(ArrayList consentIDs, + Connection connection) throws + ConsentDataInsertionException { + + ArrayList authIDs = new ArrayList<>(); + + // Store 3 consent resources + ArrayList consentResources = ConsentMgtDAOTestData.getSampleConsentResourcesList(); + for (ConsentResource resource : consentResources) { + consentIDs.add(consentCoreDAO.storeConsentResource(connection, resource).getConsentID()); + } + + // Store 2 authorization resources for each stored consent + ArrayList authorizationResources = + ConsentMgtDAOTestData.getSampleAuthorizationResourcesList(consentIDs); + for (AuthorizationResource resource : authorizationResources) { + authIDs.add(consentCoreDAO.storeAuthorizationResource(connection, resource).getAuthorizationID()); + } + + // Store 2 consent mapping resources for each authorization resource + ArrayList consentMappingResources = + ConsentMgtDAOTestData.getSampleConsentMappingResourcesList(authIDs); + for (ConsentMappingResource resource : consentMappingResources) { + consentCoreDAO.storeConsentMappingResource(connection, resource); + } + + // Store consent attributes + for (String consentID : consentIDs) { + ConsentAttributes consentAttributesResource = new ConsentAttributes(); + consentAttributesResource.setConsentID(consentID); + consentAttributesResource.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + consentCoreDAO.storeConsentAttributes(connection, consentAttributesResource); + } + } + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOTestDataProvider.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOTestDataProvider.java new file mode 100644 index 000000000..2798fe5ce --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentManagementDAOTestDataProvider.java @@ -0,0 +1,206 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.util; + +import org.testng.annotations.DataProvider; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; + +import java.util.UUID; + +public class ConsentManagementDAOTestDataProvider { + + @DataProvider(name = "storeConsentDataProvider") + public Object[][] storeConsentResourceData() { + + return new Object[][] { + { + UUID.randomUUID().toString(), + ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY, + ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtDAOTestData.SAMPLE_RECURRING_INDICATOR, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, + } + }; + } + + @DataProvider(name = "updateConsentStatusDataProvider") + public Object[][] updateConsentStatusData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS + } + }; + } + + @DataProvider(name = "storeAuthorizationDataProvider") + public Object[][] storeAuthorizationResourceData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE, + ConsentMgtDAOTestData.SAMPLE_USER_ID, + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS + } + }; + } + + @DataProvider(name = "updateAuthorizationStatusDataProvider") + public Object[][] updateAuthorizationStatusData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS + } + }; + } + + @DataProvider(name = "updateAuthorizationUserDataProvider") + public Object[][] updateAuthorizationUsersData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_NEW_USER_ID + } + }; + } + + @DataProvider(name = "storeConsentMappingDataProvider") + public Object[][] storeConsentMappingResourceData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_ACCOUNT_ID, + ConsentMgtDAOTestData.SAMPLE_PERMISSION, + ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS + } + }; + } + + @DataProvider(name = "updateConsentMappingStatusDataProvider") + public Object[][] updateConsentMappingStatusData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_NEW_MAPPING_STATUS + } + }; + } + + @DataProvider(name = "storeConsentAttributesDataProvider") + public Object[][] storeConsentAttributesData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP + } + }; + } + + @DataProvider(name = "getConsentAttributesDataProvider") + public Object[][] getConsentAttributesData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS + } + }; + } + + @DataProvider(name = "storeConsentFileDataProvider") + public Object[][] storeConsentFileData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CONSENT_FILE + } + }; + } + + @DataProvider(name = "storeConsentStatusAuditRecordDataProvider") + public Object[][] storeConsentStatusAuditRecordData() { + + return new Object[][] { + { + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtDAOTestData.SAMPLE_REASON, + ConsentMgtDAOTestData.SAMPLE_ACTION_BY, + ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS + } + }; + } + + @DataProvider(name = "storeConsentHistoryDataProvider") + public Object[][] storeConsentHistoryData() { + + /* + * historyID + * consentID + * changedAttributes + * consentType + * amendedTimestamp + * amendmentReason + */ + return new Object[][] { + + { + ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_BASIC_DATA_CHANGED_ATTRIBUTES_JSON.toString(), + ConsentMgtDAOConstants.TYPE_CONSENT_BASIC_DATA, + ConsentMgtDAOTestData.SAMPLE_UPDATED_TIME, + ConsentMgtDAOTestData.SAMPLE_AMENDMENT_REASON + }, + { + ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_CHANGED_ATTRIBUTES_JSON.toString(), + ConsentMgtDAOConstants.TYPE_CONSENT_ATTRIBUTES_DATA, + ConsentMgtDAOTestData.SAMPLE_UPDATED_TIME, + ConsentMgtDAOTestData.SAMPLE_AMENDMENT_REASON + }, + { + ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, + ConsentMgtDAOTestData.SAMPLE_MAPPING_ID, + ConsentMgtDAOTestData.SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON.toString(), + ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, + ConsentMgtDAOTestData.SAMPLE_UPDATED_TIME, + ConsentMgtDAOTestData.SAMPLE_AMENDMENT_REASON + }, + { + ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, + ConsentMgtDAOTestData.SAMPLE_MAPPING_ID_2, + ConsentMgtDAOTestData.SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON.toString(), + ConsentMgtDAOConstants.TYPE_CONSENT_MAPPING_DATA, + ConsentMgtDAOTestData.SAMPLE_UPDATED_TIME, + ConsentMgtDAOTestData.SAMPLE_AMENDMENT_REASON + }, + { + ConsentMgtDAOTestData.SAMPLE_HISTORY_ID, + ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID, + "null", + ConsentMgtDAOConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, + ConsentMgtDAOTestData.SAMPLE_UPDATED_TIME, + ConsentMgtDAOTestData.SAMPLE_AMENDMENT_REASON + } + }; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java new file mode 100644 index 000000000..f9cdbada7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/ConsentMgtDAOTestData.java @@ -0,0 +1,358 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import net.minidev.json.JSONObject; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Consent management DAO test data. + */ +public class ConsentMgtDAOTestData { + + public static final String SAMPLE_CONSENT_RECEIPT = "{\"validUntil\": \"2020-10-20\", \"frequencyPerDay\": 1," + + " \"recurringIndicator\": false, \"combinedServiceIndicator\": true}"; + public static final String SAMPLE_CONSENT_TYPE = "accounts"; + public static final String SAMPLE_ORG_ID = "asgradeo"; + public static final int SAMPLE_CONSENT_FREQUENCY = 1; + public static final Long SAMPLE_CONSENT_VALIDITY_PERIOD = 1638337852L; + public static final String SAMPLE_CONSENT_ID = "2222"; + public static final String SAMPLE_AUTHORIZATION_ID = "3333"; + public static final boolean SAMPLE_RECURRING_INDICATOR = true; + public static final String SAMPLE_CURRENT_STATUS = "authorised"; + public static final String SAMPLE_PREVIOUS_STATUS = "Received"; + public static final String SAMPLE_AUTHORIZATION_TYPE = "authorizationType"; + public static final String SAMPLE_USER_ID = "admin@wso2.com"; + public static final String SAMPLE_AUDIT_ID = "4321234"; + public static final String SAMPLE_NEW_USER_ID = "ann@gold.com"; + public static final String SAMPLE_AUTHORIZATION_STATUS = "awaitingAuthorization"; + public static final String SAMPLE_EXPIRED_STATUS = "Expired"; + public static final String SAMPLE_ACCOUNT_ID = "123456789"; + public static final String SAMPLE_MAPPING_ID = "12345"; + public static final String SAMPLE_MAPPING_ID_2 = "67890"; + public static final String SAMPLE_MAPPING_STATUS = "active"; + public static final String SAMPLE_NEW_MAPPING_STATUS = "inactive"; + public static final String SAMPLE_PERMISSION = "samplePermission"; + + private static final ObjectMapper objectMapper = new ObjectMapper(); + public static final JSONObject SAMPLE_RESOURCE; + + static { + try { + SAMPLE_RESOURCE = new JSONObject(new JSONObject(objectMapper.readValue( + "{\"resourceId\": \"1234\", \"resourceType\": \"account\"}" + , new TypeReference>() { + }))); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + } + + public static final String SAMPLE_REASON = "sample reason"; + public static final String SAMPLE_ACTION_BY = "admin@wso2.com"; + public static final String SAMPLE_HISTORY_ID = "1234"; + public static final Long SAMPLE_UPDATED_TIME = 1638337892L; + public static final String SAMPLE_AMENDMENT_REASON = "sampleReason"; + public static final String SAMPLE_CONSENT_FILE = "sample file content"; + public static final Map SAMPLE_CONSENT_ATTRIBUTES_MAP = new HashMap() { + { + put("x-request-id", UUID.randomUUID().toString()); + put("idempotency-key", UUID.randomUUID().toString()); + put("payment-type", "domestic-payments"); + put("sessionDataKey", "{\"sessionDataKey\":\"a0c8cd6d-eca0-4c4d-9544-2b39e7e1c180\",\"userId\":\"01Z79\"}"); + } + }; + public static final Map CONSENT_ATTRIBUTES_MAP_FOR_UPDATE = new HashMap() { + { + put("payment-type", "international-payments"); + } + }; + public static final ArrayList SAMPLE_CONSENT_ATTRIBUTES_KEYS = new ArrayList() { + { + add("x-request-id"); + add("idempotency-key"); + } + }; + public static final ArrayList UNMATCHED_MAPPING_IDS = new ArrayList() { + { + add("4444"); + add("5555"); + } + }; + private static final ArrayList SAMPLE_CONSENT_RECEIPTS_LIST = new ArrayList() { + { + add("{\"element1\": \"value1\"}"); + add("{\"element2\": \"value2\"}"); + add("{\"element3\": \"value3\"}"); + } + }; + public static final ArrayList SAMPLE_CONSENT_TYPES_LIST = new ArrayList() { + { + add("accounts"); + add("payments"); + add("cof"); + } + }; + public static final ArrayList SAMPLE_CONSENT_STATUSES_LIST = new ArrayList() { + { + add("created"); + add("authorised"); + add("awaitingAuthorisation"); + + } + }; + public static final ArrayList SAMPLE_CLIENT_IDS_LIST = new ArrayList() { + { + add("clientID1"); + add("clientID2"); + add("clientID3"); + + } + }; + public static final ArrayList SAMPLE_USER_IDS_LIST = new ArrayList() { + { + add("userID1"); + add("userID2"); + add("userID3"); + } + }; + private static final ArrayList SAMPLE_VALIDITY_PERIOD_LIST = new ArrayList() { + { + add(1613454661L); + add(1623654661L); + add(1633654671L); + } + }; + public static final JSONObject SAMPLE_CONSENT_BASIC_DATA_CHANGED_ATTRIBUTES_JSON = new JSONObject() { + { + put("RECEIPT", SAMPLE_CONSENT_RECEIPT); + put("VALIDITY_TIME", SAMPLE_CONSENT_VALIDITY_PERIOD); + put("UPDATED_TIME", SAMPLE_UPDATED_TIME); + } + }; + public static final JSONObject SAMPLE_CONSENT_ATTRIBUTES_CHANGED_ATTRIBUTES_JSON = new JSONObject() { + { + put("x-request-id", UUID.randomUUID().toString()); + put("idempotency-key", UUID.randomUUID().toString()); + } + }; + public static final JSONObject SAMPLE_CONSENT_MAPPINGS_CHANGED_ATTRIBUTES_JSON = new JSONObject() { + { + put("MAPPING_STATUS", SAMPLE_MAPPING_STATUS); + } + }; + + public static List getRecordIDListOfSampleConsentHistory() { + return new ArrayList() { + { + add(ConsentMgtDAOTestData.SAMPLE_CONSENT_ID); + add(ConsentMgtDAOTestData.SAMPLE_MAPPING_ID); + add(ConsentMgtDAOTestData.SAMPLE_MAPPING_ID_2); + add(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_ID); + } + }; + } + + public static ConsentResource getSampleTestConsentResource() { + + ConsentResource consentResource = new ConsentResource(); + consentResource.setOrgID(ConsentMgtDAOConstants.DEFAULT_ORG); + consentResource.setReceipt(ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); + consentResource.setClientID(UUID.randomUUID().toString()); + consentResource.setConsentType(ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE); + consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + consentResource.setConsentFrequency(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY); + consentResource.setValidityPeriod(ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); + consentResource.setRecurringIndicator(ConsentMgtDAOTestData.SAMPLE_RECURRING_INDICATOR); + + return consentResource; + } + + public static ConsentResource getSampleStoredTestConsentResource() { + + ConsentResource consentResource = new ConsentResource(); + consentResource.setConsentID(UUID.randomUUID().toString()); + consentResource.setReceipt(ConsentMgtDAOTestData.SAMPLE_CONSENT_RECEIPT); + consentResource.setClientID(UUID.randomUUID().toString()); + consentResource.setConsentType(ConsentMgtDAOTestData.SAMPLE_CONSENT_TYPE); + consentResource.setCurrentStatus(ConsentMgtDAOTestData.SAMPLE_CURRENT_STATUS); + consentResource.setConsentFrequency(ConsentMgtDAOTestData.SAMPLE_CONSENT_FREQUENCY); + consentResource.setValidityPeriod(ConsentMgtDAOTestData.SAMPLE_CONSENT_VALIDITY_PERIOD); + consentResource.setRecurringIndicator(ConsentMgtDAOTestData.SAMPLE_RECURRING_INDICATOR); + + return consentResource; + } + + /** + * Generated three sample consent resources for testing purposes. + * + * @return sample consent resources list + */ + public static ArrayList getSampleConsentResourcesList() { + + ArrayList consentResources = new ArrayList(); + + for (int i = 0; i < 3; i++) { + ConsentResource consentResource = new ConsentResource(); + consentResource.setReceipt(SAMPLE_CONSENT_RECEIPTS_LIST.get(i)); + consentResource.setClientID(SAMPLE_CLIENT_IDS_LIST.get(i)); + consentResource.setConsentType(SAMPLE_CONSENT_TYPES_LIST.get(i)); + consentResource.setCurrentStatus(SAMPLE_CONSENT_STATUSES_LIST.get(i)); + consentResource.setConsentFrequency(0); + consentResource.setValidityPeriod(SAMPLE_VALIDITY_PERIOD_LIST.get(i)); + consentResource.setRecurringIndicator(false); + consentResources.add(consentResource); + } + return consentResources; + } + + public static ArrayList getSampleAuthorizationResourcesList(ArrayList consentIDs) { + + ArrayList authorizationResources = new ArrayList(); + + for (int i = 0; i < consentIDs.size(); i++) { + for (int j = 0; j < 2; j++) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResource.setConsentID(consentIDs.get(i)); + authorizationResource.setAuthorizationType(SAMPLE_AUTHORIZATION_TYPE); + authorizationResource.setUserID(SAMPLE_USER_IDS_LIST.get(i)); + authorizationResource.setAuthorizationStatus(SAMPLE_AUTHORIZATION_STATUS); + authorizationResources.add(authorizationResource); + } + } + return authorizationResources; + } + + public static ArrayList getSampleConsentMappingResourcesList(ArrayList authIDs) { + + ArrayList consentMappingResources = new ArrayList(); + + for (int i = 0; i < authIDs.size(); i++) { + for (int j = 0; j < 2; j++) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(authIDs.get(i)); + consentMappingResource.setAccountID(SAMPLE_ACCOUNT_ID); + consentMappingResource.setResource(SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(SAMPLE_MAPPING_STATUS); + consentMappingResources.add(consentMappingResource); + } + } + return consentMappingResources; + } + + public static AuthorizationResource getSampleTestAuthorizationResource(String consentID) { + + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResource.setConsentID(consentID); + authorizationResource.setAuthorizationType(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE); + authorizationResource.setUserID(ConsentMgtDAOTestData.SAMPLE_USER_ID); + authorizationResource.setAuthorizationStatus(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); + + ArrayList consentMappingResources = new ArrayList(); + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(consentID); + consentMappingResource.setResource(ConsentMgtDAOTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + consentMappingResources.add(consentMappingResource); + + authorizationResource.setConsentMappingResource(consentMappingResources); + + return authorizationResource; + } + + public static AuthorizationResource getSampleStoredTestAuthorizationResource() { + + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResource.setConsentID(UUID.randomUUID().toString()); + authorizationResource.setAuthorizationID(UUID.randomUUID().toString()); + authorizationResource.setAuthorizationType(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_TYPE); + authorizationResource.setUserID(ConsentMgtDAOTestData.SAMPLE_USER_ID); + authorizationResource.setAuthorizationStatus(ConsentMgtDAOTestData.SAMPLE_AUTHORIZATION_STATUS); + authorizationResource.setUpdatedTime(System.currentTimeMillis() / 1000); + + return authorizationResource; + } + + public static ConsentMappingResource getSampleTestConsentMappingResource(String authorizationID) { + + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(authorizationID); + consentMappingResource.setResource(ConsentMgtDAOTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + + return consentMappingResource; + } + + public static ConsentMappingResource getSampleTestConsentMappingResourceWithResource(String authorizationID, + String accountID) { + + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAuthorizationID(authorizationID); + consentMappingResource.setResource(ConsentMgtDAOTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtDAOTestData.SAMPLE_MAPPING_STATUS); + + return consentMappingResource; + } + + public static ConsentStatusAuditRecord getSampleTestConsentStatusAuditRecord(String consentID, + String currentStatus) { + + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(); + consentStatusAuditRecord.setConsentID(consentID); + consentStatusAuditRecord.setCurrentStatus(currentStatus); + consentStatusAuditRecord.setReason(ConsentMgtDAOTestData.SAMPLE_REASON); + consentStatusAuditRecord.setActionBy(ConsentMgtDAOTestData.SAMPLE_ACTION_BY); + consentStatusAuditRecord.setPreviousStatus(ConsentMgtDAOTestData.SAMPLE_PREVIOUS_STATUS); + + return consentStatusAuditRecord; + } + + public static ConsentAttributes getSampleTestConsentAttributesObject(String consentID) { + + ConsentAttributes consentAttributes = new ConsentAttributes(); + consentAttributes.setConsentID(consentID); + consentAttributes.setConsentAttributes(ConsentMgtDAOTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + + return consentAttributes; + } + + public static ConsentFile getSampleConsentFileObject(String fileContent) { + + ConsentFile consentFile = new ConsentFile(); + consentFile.setConsentID(UUID.randomUUID().toString()); + consentFile.setConsentFile(fileContent); + + return consentFile; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DAOUtils.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DAOUtils.java new file mode 100644 index 000000000..a640e2627 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/dao/util/DAOUtils.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.dao.util; + +import org.apache.commons.dbcp.BasicDataSource; +import org.apache.commons.lang3.StringUtils; + +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +/** + * DAO utils. + */ +public class DAOUtils { + + private static final Map dataSourceMap = new HashMap<>(); + + public static void initializeDataSource(String databaseName, String scriptPath) throws + Exception { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + dataSource.setUsername("username"); + dataSource.setPassword("password"); + dataSource.setUrl("jdbc:h2:mem:" + databaseName); + + try (Connection connection = dataSource.getConnection()) { + connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); + } + dataSourceMap.put(databaseName, + dataSource); + } + + public static Connection getConnection(String database) throws + SQLException { + if (dataSourceMap.get(database) != null) { + return dataSourceMap.get(database).getConnection(); + } + throw new RuntimeException("Invalid datasource."); + } + + public static String getFilePath(String fileName) { + if (StringUtils.isNotBlank(fileName)) { + return Paths.get(System.getProperty("user.dir"), + "src", + "test", + "resources", + fileName) + .toString(); + } + return null; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql new file mode 100644 index 000000000..7b6305d4f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/dbScripts/h2.sql @@ -0,0 +1,78 @@ +-- All the data related to time are stored in unix time stamp and therefore, the data types for the time related data +-- are represented in BIGINT. +-- Since the database systems does not support adding default unix time to the database columns, the default data +-- storing is handled within the database queries. + +CREATE TABLE IF NOT EXISTS FS_CONSENT ( + CONSENT_ID VARCHAR(255) NOT NULL, + RECEIPT CLOB NOT NULL, + CREATED_TIME BIGINT NOT NULL, + UPDATED_TIME BIGINT NOT NULL, + CLIENT_ID VARCHAR(255) NOT NULL, + CONSENT_TYPE VARCHAR(64) NOT NULL, + CURRENT_STATUS VARCHAR(64) NOT NULL, + CONSENT_FREQUENCY INT, + ORG_ID VARCHAR(255) DEFAULT 'DEFAULT_ORG', + + VALIDITY_TIME BIGINT, + RECURRING_INDICATOR BOOLEAN, + PRIMARY KEY (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_AUTH_RESOURCE ( + AUTH_ID VARCHAR(255) NOT NULL, + CONSENT_ID VARCHAR(255) NOT NULL, + AUTH_TYPE VARCHAR(255) NOT NULL, + USER_ID VARCHAR(255), + AUTH_STATUS VARCHAR(255) NOT NULL, + UPDATED_TIME BIGINT NOT NULL, + PRIMARY KEY(AUTH_ID), + CONSTRAINT FK_ID_FS_CONSENT_AUTH_RESOURCE FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_MAPPING ( + MAPPING_ID VARCHAR(255) NOT NULL, + AUTH_ID VARCHAR(255) NOT NULL, + MAPPING_STATUS VARCHAR(255) NOT NULL, + RESOURCE CLOB NOT NULL, + PRIMARY KEY(MAPPING_ID), + CONSTRAINT FK_FS_CONSENT_MAPPING FOREIGN KEY (AUTH_ID) REFERENCES FS_CONSENT_AUTH_RESOURCE (AUTH_ID) +); + + +CREATE TABLE IF NOT EXISTS FS_CONSENT_STATUS_AUDIT ( + STATUS_AUDIT_ID VARCHAR(255) NOT NULL, + CONSENT_ID VARCHAR(255) NOT NULL, + CURRENT_STATUS VARCHAR(255) NOT NULL, + ACTION_TIME BIGINT NOT NULL, + REASON VARCHAR(255), + ACTION_BY VARCHAR(255), + PREVIOUS_STATUS VARCHAR(255), + PRIMARY KEY(STATUS_AUDIT_ID), + CONSTRAINT FK_FS_CONSENT_STATUS_AUDIT FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_FILE ( + CONSENT_ID VARCHAR(255) NOT NULL, + CONSENT_FILE CLOB, + PRIMARY KEY(CONSENT_ID), + CONSTRAINT FK_FS_CONSENT_FILE FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_ATTRIBUTE ( + CONSENT_ID VARCHAR(255) NOT NULL, + ATT_KEY VARCHAR(255) NOT NULL, + ATT_VALUE VARCHAR(255) NOT NULL, + PRIMARY KEY(CONSENT_ID, ATT_KEY), + CONSTRAINT FK_FS_CONSENT_ATTRIBUTE FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_HISTORY ( + TABLE_ID VARCHAR(10) NOT NULL, + RECORD_ID VARCHAR(255) NOT NULL, + HISTORY_ID VARCHAR(255) NOT NULL, + CHANGED_VALUES CLOB NOT NULL, + REASON VARCHAR(255) NOT NULL, + EFFECTIVE_TIMESTAMP BIGINT NOT NULL, + PRIMARY KEY (TABLE_ID,RECORD_ID,HISTORY_ID) +); diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/testng.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/testng.xml new file mode 100644 index 000000000..7be357ecf --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.dao/src/test/resources/testng.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/dependency-reduced-pom.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/dependency-reduced-pom.xml new file mode 100644 index 000000000..55ae3b318 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/dependency-reduced-pom.xml @@ -0,0 +1,257 @@ + + + + financial-services-accelerator + org.wso2.financial.services.accelerator + 4.0.0-SNAPSHOT + ../../pom.xml + + 4.0.0 + org.wso2.financial.services.accelerator.consent.mgt.service + bundle + WSO2 Financial Services - Consent Service + WSO2 Financial Services - Consent Service Module + http://maven.apache.org + + + + com.github.spotbugs + spotbugs-maven-plugin + + + analyze-compile + compile + + check + + + + + Max + Low + true + true + ${project.build.directory}/spotbugs + ${project.basedir}/src/main/resources/findbugs-exclude.xml + ${project.basedir}/src/main/resources/findbugs-include.xml + + + com.h3xstream.findsecbugs + findsecbugs-plugin + ${com.h3xstream.findsecbugs.version} + + + + + + maven-surefire-plugin + + + src/test/resources/testng.xml + + + target/jacoco.exec + + true + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + default-prepare-agent + + prepare-agent + + + + default-prepare-agent-integration + + prepare-agent-integration + + + + default-report + + report + + + + default-report-integration + + report-integration + + + + default-check + + check + + + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.8 + + + + + + + + + + **/*Constants.class + **/*Component.class + **/*DataHolder.class + + + + + maven-compiler-plugin + + + maven-shade-plugin + 3.4.1 + + + package + + shade + + + + + org.wso2.financial.services.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl + + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + org.wso2.financial.services.accelerator.consent.mgt.service.internal + org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", + org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", + org.apache.commons.lang3;version="${commons-lang3.version}", + net.minidev.json.*;version="${json-smart.version}", + org.apache.commons.collections4;version="${commons-collections.version.range}", + org.apache.commons.logging;version="${commons.logging.version}", + org.wso2.carbon.identity.oauth2.*;version="${identity.inbound.auth.oauth.version.range}", + org.wso2.financial.services.accelerator.common.*;version="${project.version}", + org.wso2.financial.services.accelerator.consent.mgt.dao.*;version="${project.version}", + com.google.gson;version="${google.gson.version.range}", + org.apache.oltu.oauth2.*;version="${oltu.version}", + org.wso2.carbon.identity.application.authentication.framework.model;version="${carbon.identity.framework.version.range}", + org.wso2.carbon.user.core.util;version=${carbon.kernel.version} + !org.wso2.financial.services.accelerator.consent.mgt.service.internal, + org.wso2.financial.services.accelerator.consent.mgt.service.*;version="${project.version}", + <_dsannotations>* + + + + + + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.common + 4.0.0-SNAPSHOT + provided + + + pax-logging-log4j2 + org.wso2.org.ops4j.pax.logging + + + pax-logging-api + org.wso2.org.ops4j.pax.logging + + + pax-logging-api + org.ops4j.pax.logging + + + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.dao + 4.0.0-SNAPSHOT + provided + + + org.wso2.carbon.identity.inbound.auth.oauth2 + org.wso2.carbon.identity.oauth + 7.0.228 + provided + + + pax-logging-log4j2 + org.wso2.org.ops4j.pax.logging + + + pax-logging-api + org.wso2.org.ops4j.pax.logging + + + pax-logging-api + org.ops4j.pax.logging + + + + + org.testng + testng + 7.10.1 + test + + + jcommander + com.beust + + + jquery + org.webjars + + + + + org.mockito + mockito-core + 5.3.1 + test + + + byte-buddy + net.bytebuddy + + + byte-buddy-agent + net.bytebuddy + + + objenesis + org.objenesis + + + + + org.mockito + mockito-testng + 0.5.2 + test + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/pom.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/pom.xml new file mode 100644 index 000000000..c3024c231 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/pom.xml @@ -0,0 +1,242 @@ + + + + 4.0.0 + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.api + 4.0.0-SNAPSHOT + ../../pom.xml + + org.wso2.financial.services.accelerator.consent.mgt.service + WSO2 Financial Services - Consent Service + WSO2 Financial Services - Consent Service Module + http://maven.apache.org + jar + + + + commons-logging + commons-logging + + + + com.google.code.gson + gson + 2.12.1 + + + net.minidev + json-smart + ${json-smart.version} + + + + org.apache.commons + commons-lang3 + + + javax.servlet + servlet-api + 2.5 + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.dao + provided + + + + jakarta.ws.rs + jakarta.ws.rs-api + 2.1.6 + + + + + + org.testng + testng + test + + + org.mockito + mockito-core + test + + + org.mockito + mockito-testng + test + + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + Max + Low + true + true + ${project.build.directory}/spotbugs + ${project.basedir}/src/main/resources/findbugs-exclude.xml + ${project.basedir}/src/main/resources/findbugs-include.xml + + + com.h3xstream.findsecbugs + findsecbugs-plugin + ${com.h3xstream.findsecbugs.version} + + + + + + analyze-compile + compile + + check + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + src/test/resources/testng.xml + + + target/jacoco.exec + + true + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + **/*Constants.class + **/*Component.class + **/*DataHolder.class + **/*Exception.class + **/*ConsentCoreServiceUtil.class + + + + + + + default-prepare-agent + + prepare-agent + + + + default-prepare-agent-integration + + prepare-agent-integration + + + + default-report + + report + + + + default-report-integration + + report-integration + + + + default-check + + check + + + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.7 + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.felix + maven-bundle-plugin + true + + + + ${project.artifactId} + + + org.wso2.financial.services.accelerator.consent.mgt.service.internal + + + org.osgi.framework;version="${osgi.framework.imp.pkg.version.range}", + org.osgi.service.component;version="${osgi.service.component.imp.pkg.version.range}", + org.apache.commons.lang3;version="${commons-lang3.version}", + net.minidev.json.*;version="${json-smart.version}", + org.apache.commons.collections4;version="${commons-collections.version.range}", + org.apache.commons.logging;version="${commons.logging.version}", + org.wso2.carbon.identity.oauth2.*;version="${identity.inbound.auth.oauth.version.range}", + org.wso2.financial.services.accelerator.common.*;version="${project.version}", + org.wso2.financial.services.accelerator.consent.mgt.dao.*;version="${project.version}", + com.google.gson;version="${google.gson.version.range}", + org.apache.oltu.oauth2.*;version="${oltu.version}", + org.wso2.carbon.identity.application.authentication.framework.model;version="${carbon.identity.framework.version.range}", + org.wso2.carbon.user.core.util;version=${carbon.kernel.version} + + + !org.wso2.financial.services.accelerator.consent.mgt.service.internal, + org.wso2.financial.services.accelerator.consent.mgt.service.*;version="${project.version}", + + <_dsannotations>* + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/ConsentCoreService.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/ConsentCoreService.java new file mode 100644 index 000000000..44535691b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/ConsentCoreService.java @@ -0,0 +1,788 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service; + +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; + + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Consent core service interface. + */ +public interface ConsentCoreService { + + /** + * This method is used to create an authorizable consent. The following functionality contains in this method. + * 1. Creates a consent resource + * 2. If available, stores consent attributes + * 3. Create an audit record for consent creation + * 4. If isImplicitAuth parameter is true, creates an authorization resource + * + * @param consentResource consent resource + * @param userID user ID is optional and used to create the audit record + * @param authStatus authorization status + * @param authType authorization type (eg. authorization, cancellation) + * @param isImplicitAuth flag to determine whether authorization is implicit or not + * @return returns DetailedConsentResource + * @throws ConsentMgtException thrown if any error occur in the process + */ + DetailedConsentResource createAuthorizableConsent(ConsentResource consentResource, String userID, + String authStatus, String authType, boolean isImplicitAuth) + throws + ConsentMgtException; + + /** + * This method is used to create an authorizable consent. The following functionality contains in this method. + * 1. Creates a consent resource + * 2. If available, stores consent attributes + * 3. Create an audit record for consent creation + * 4. If isImplicitAuth parameter is true, creates an authorization resource + * + * @param consentResource consent resource + * @param authorizationResources auth resources + * @param isImplicitAuth flag to determine whether authorization is implicit or not + * @return returns DetailedConsentResource + * @throws ConsentMgtException thrown if any error occur in the process + */ + DetailedConsentResource createAuthorizableConsentWithBulkAuth(ConsentResource consentResource, + ArrayList + authorizationResources, + boolean isImplicitAuth) + throws + ConsentMgtException, + org.wso2.financial.services.accelerator.consent.mgt.service.exception.ConsentMgtException; + + /** + * This method is used to create an exclusive consent. The following functionality contains in this method. + * + * 1. Update existing consent statuses as necessary and deactivate their account mappings + * 2. Create audit records for necessary consent updates + * 3. Create a new authorizable consent + * + * @param consentResource consent resource + * @param userID user ID + * @param authStatus authorization status + * @param authType authorization type + * @param applicableExistingConsentsStatus applicable status for existing consents to be updated + * @param newExistingConsentStatus new status that the updated consents should be + * @param isImplicitAuth flag to determine whether authorization is implicit or not + * @return returns DetailedConsentResource + * @throws ConsentMgtException thrown if any error occur in the process + */ + DetailedConsentResource createExclusiveConsent(ConsentResource consentResource, String userID, String authStatus, + String authType, String applicableExistingConsentsStatus, + String newExistingConsentStatus, boolean isImplicitAuth) + throws + ConsentMgtException; + + /** + * This method is used to get a consent with or without consent attributes. The following functionality contains in + * this method. + * + * 1. Get existing consent for status validation + * 2. Optionally gets consent attributes according to the value of withConsentAttributes flag + * 3. Check whether the retrieved consent involves a file + * + * @param consentID ID of the consent + * @param withConsentAttributes flag to determine the consent should be retrieved with attributes or not + * @return returns ConsentResource + * @throws ConsentMgtException thrown if any error occur in the process + */ + ConsentResource getConsent(String consentID, boolean withConsentAttributes) + throws + ConsentMgtException; + + /** + * This method is used to get a detailed consent for the provided consent ID. The detailed consent includes + * following data if exist in addition to consent resource specific data. + * + * 1. Relative consent authorization data + * 2. Relative consent account mapping data + * 3. Relative consent attributes + * + * @param consentID ID of the consent + * @return a detailed consent resource + * @throws ConsentMgtException thrown if any error occur in the process + */ + DetailedConsentResource getDetailedConsent(String consentID) throws + ConsentMgtException; + + /** + * This method is used to get a detailed consent for the provided consent ID. The detailed consent includes + * following data if exist in addition to consent resource specific data. + * + * 1. Relative consent authorization data + * 2. Relative consent account mapping data + * 3. Relative consent attributes + * + * @param consentID ID of the consent + * @return a detailed consent resource + * @throws ConsentMgtException thrown if any error occur in the process + */ + DetailedConsentResource getConsentWithAuthorizationResources(String consentID) throws + ConsentMgtException; + + /** + * This method is used to create a consent file. The following functionality contains in this method. + * + * 1. Get the existing consent to validate the status according to the attribute "applicableStatusToFileUpload" + * 2. Create the consent file + * 3. Update the consent status + * 4. Create an audit record for consent update + * + * @param consentFileResource consent file resource + * @param newConsentStatus new consent status + * @param userID user ID (optional) + * @param applicableStatusToFileUpload status that the consent should have to upload a file + * @return true if transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean createConsentFile(ConsentFile consentFileResource, String newConsentStatus, String userID, + String applicableStatusToFileUpload) + throws + ConsentMgtException; + + /** + * This method is used to retrieve the consent file using the related consent ID. + * + * @param consentID consent ID + * @return the consent file resource + * @throws ConsentMgtException thrown if an error occurs + */ + ConsentFile getConsentFile(String consentID) throws + ConsentMgtException; + + /** + * This method is used to create an authorization for a consent. + * + * @param authorizationResource authorization resource + * @return returns AuthorizationResource + * @throws ConsentMgtException thrown if any error occurs in the process + */ + AuthorizationResource createConsentAuthorization(AuthorizationResource authorizationResource) + throws + ConsentMgtException; + + /** + * This method is to retrieve an authorization resource using a given authorization ID. + * + * @param authorizationID authorization ID + * @return an authorization resource + * @throws ConsentMgtException thrown if an error occurs in the process + */ + AuthorizationResource getAuthorizationResource(String authorizationID, String orgID) throws + ConsentMgtException; + + /** + * This method is used to search authorization resources for a given input parameter. Both consent ID and + * user ID are optional. If both are null, all authorization resources will be returned. + * + * @param consentID consent ID + * @param userID user ID + * @return a list of authorization resources + * @throws ConsentMgtException thrown if any error occurs in the process + */ + ArrayList searchAuthorizations(String consentID, String userID) + throws + ConsentMgtException; + + /** + * This method is used to search authorization resources for a given consent ID. + * + * @param consentID consent ID + * @return a list of authorization resources + * @throws ConsentMgtException thrown if any error occurs in the process + */ + ArrayList searchAuthorizations(String consentID) + throws + ConsentMgtException; + + /** + * This method is used to search authorization resources for a userId. + * + * @param userID user ID + * @return a list of authorization resources + * @throws ConsentMgtException thrown if any error occurs in the process + */ + ArrayList searchAuthorizationsForUser(String userID) + throws + ConsentMgtException; + + /** + * This method is used to update the status of an authorization resource by providing the authorization Id and + * the new authorization status. + * + * @param authorizationId the authorization Id of the authorization resource need to be updated + * @param newAuthorizationStatus the new authorization resource + * @return the updated authorization resource + * @throws ConsentMgtException thrown if any error occur while updating + */ + AuthorizationResource updateAuthorizationStatus(String authorizationId, String newAuthorizationStatus, String orgID) + throws + ConsentMgtException; + + /** + * This method is used to update the user of an authorization resource by providing the authorization ID and + * the user ID. + * + * @param authorizationID the authorization ID of the authorization resource that needs to be updated + * @param userID the user of the authorization resource + * @return the updated authorization resource + * @throws ConsentMgtException thrown if any error occurs while updating + */ + AuthorizationResource updateAuthorizationUser(String authorizationID, String userID, String orgID) + throws + ConsentMgtException; + + /** + * This method is used to bind user and accounts to the consent. + * + * @param consentResource consent resource + * @param userID user ID + * @param authID ID of the authorization resource + * @param accountIDsMapWithPermissions account IDs list with relevant permissions + * @param newAuthStatus new authorization status + * @param newCurrentConsentStatus the new status of the current consent + * @return true if all operations are successful + * @throws ConsentMgtException thrown if an error occurs in the process + */ + boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, String authID, + Map> accountIDsMapWithPermissions, String newAuthStatus, + String newCurrentConsentStatus) throws + ConsentMgtException; + + /** + * This method is used to bind user and accounts to the consent where permissions for each account is not relevant. + * + * @param consentResource consent resource + * @param userID user ID + * @param authID ID of the authorization resource + * @param accountIDs account IDs list + * @param newAuthStatus new authorization status + * @param newCurrentConsentStatus the new status of the current consent + * @return true if all operations are successful + * @throws ConsentMgtException thrown if an error occurs in the process + */ + boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, + String authID, ArrayList accountIDs, + String newAuthStatus, + String newCurrentConsentStatus) + throws + ConsentMgtException; + + /** + * This method is used to update status of the consent for a given consentId and userId. + * @param consentId consent ID + * @param newConsentStatus new consent status + * @return the updated consent resource + * @throws ConsentMgtException thrown if any error occurs in the process + */ + DetailedConsentResource updateConsentStatus(String consentId, String newConsentStatus) + throws + ConsentMgtException; + + /** + * This method is used to update status of the consent for a given consentId and userId. + * @param consentId consent ID + * @param newConsentStatus new consent status + * @param userId user ID + * @param reason reason + * @throws ConsentMgtException thrown if any error occurs in the process + */ + void updateConsentStatusWithImplicitReasonAndUserId(String consentId, + String newConsentStatus, String userId, + String reason, String orgID) + throws + ConsentMgtException; + + /** + * This method is used to update status of the consent for a given clientId and userId. + * @param clientId + * @param status + * @param reason + * @param userId + */ + void bulkUpdateConsentStatus(String orgID, String clientId, String status, String reason, String userId, + String consentType, ArrayList applicableExistingStatus) + throws + ConsentMgtException; + + + /** + * This method is used to create account ID and permission mappings for the relevant authorized user. A map is + * used to represent permissions related to each accountID. + * + * @param authID authorization ID + * @param accountIDsMapWithPermissions account IDs with relative permissions + * @return returns the list of created consent mapping resources + * @throws ConsentMgtException thrown if any error occurs + */ + ArrayList createConsentAccountMappings(String authID, Map> + accountIDsMapWithPermissions) + throws + ConsentMgtException; + + /** + * This method is used to deactivate account bindings of provided account mapping IDs. + * + * @param accountMappingIDs list of account mapping IDs to be deactivated + * @return true is deactivation is a success, false otherwise + * @throws ConsentMgtException thrown if any error occurs + */ + boolean deactivateAccountMappings(ArrayList accountMappingIDs) throws + ConsentMgtException; + + /** + * This method is used to update the status of account bindings of provided account mapping IDs. + * + * @param accountMappingIDs list of account mapping IDs to be updated + * @param newMappingStatus new mapping status + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occurs + */ + boolean updateAccountMappingStatus(ArrayList accountMappingIDs, String newMappingStatus) throws + ConsentMgtException; + + /** + * This method is used to revoke a consent. The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsent(String consentID, String revokedConsentStatus) + throws + ConsentMgtException; + + /** + * This method is used to revoke a consent by adding a revoke reason. + * The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @param revokedReason the reason for consent revocation + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String revokedReason) + throws + ConsentMgtException; + + /** + * This method is used to revoke a consent. The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @param userID user ID + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsent(String consentID, String revokedConsentStatus, String userID) + throws + ConsentMgtException; + + /** + * This method is used to revoke a consent by adding a revoke reason. + * The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @param userID user ID + * @param revokedReason the reason for consent revocation + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, String revokedReason) + throws + ConsentMgtException; + + /** + * This method is used to revoke a consent. The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * 5. Revoke tokens related to the consent if the flag 'shouldRevokeTokens' is true + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @param userID user ID + * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsent(String consentID, String revokedConsentStatus, String userID, boolean shouldRevokeTokens) + throws + ConsentMgtException; + + /** + * This method is used to revoke a consent. The following functionality contains in this method. + * + * 1. Get existing consent for status validation + * 2. Update existing consent status + * 3. Create an audit record for consent update + * 4. Update account mapping status as inactive + * 5. Revoke tokens related to the consent if the flag 'shouldRevokeTokens' is true + * + * @param consentID ID of the consent + * @param revokedConsentStatus the status of the consent after revoked + * @param userID user ID + * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent + * @param revokedReason the reason for consent revocation + * @return true is the transaction is a success, throws an exception otherwise + * @throws ConsentMgtException thrown if any error occur in the process + */ + boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, + boolean shouldRevokeTokens, String revokedReason) + throws + ConsentMgtException; + + /** + * This method is used to revoke existing consents for the given clientID, userID, consent type and status + * combination. Also revokes the tokens related to the consents which are revoked if the flag + * 'shouldRevokeTokens' is true. + * + * @param clientID ID of the client + * @param userID ID of the user + * @param consentType consent type + * @param applicableStatusToRevoke the status that a consent should have for revoking + * @param revokedConsentStatus the status should be updated the consent with after revoking + * @param shouldRevokeTokens the check to revoke tokens or not when revoking consent + * @return returns true if successful + * @throws ConsentMgtException thrown if an error occurs in the process + */ + boolean revokeExistingApplicableConsents(String clientID, String userID, String consentType, + String applicableStatusToRevoke, String revokedConsentStatus, + boolean shouldRevokeTokens) + throws + ConsentMgtException; + + /** + * This method is used in consent re-authorization scenarios to update the account mappings according to the + * additional/removed accounts from the new authorization. Also, the consent status is updated with a provided + * status. Also, can be used to amend accounts. + * + * @param consentID consent ID + * @param authID authorization ID + * @param userID user ID for creating the audit record + * @param accountIDsMapWithPermissions accounts IDs with relative permissions + * @param currentConsentStatus current status of the consent for creating audit record + * @param newConsentStatus new consent status after re-authorization + * @return true if all operations are successful + * @throws ConsentMgtException thrown if any error occurs in the process + */ + boolean reAuthorizeExistingAuthResource(String consentID, String authID, String userID, Map> accountIDsMapWithPermissions, String currentConsentStatus, String newConsentStatus) + throws + ConsentMgtException; + + /** + * This method is used in consent re-authorization scenarios to update the account mappings according to the + * additional/removed accounts from the new authorization. A new authorization resource will be created when + * re authorizing using this method. Existing authorizations will be updated with a provided status. Also, the + * consent status is updated with a provided status. Also, can be used to amend accounts. + * + * @param consentID consent ID + * @param userID user ID + * @param accountIDsMapWithPermissions account IDs with relative permissions + * @param currentConsentStatus current status of the consent for creating audit record + * @param newConsentStatus new consent status after re-authorization + * @param newExistingAuthStatus new status of the existing authorizations + * @param newAuthStatus new status of the new authorization + * @param newAuthType new authorization type + * @return true if all operations are successful + * @throws ConsentMgtException thrown if any error occurs in the process + */ + boolean reAuthorizeConsentWithNewAuthResource(String consentID, String userID, Map> accountIDsMapWithPermissions, String currentConsentStatus, String newConsentStatus, + String newExistingAuthStatus, String newAuthStatus, + String newAuthType) + throws + ConsentMgtException; + + + /** + * This method is used to store consent attributes related to a particular consent. + * + * @param consentID consent ID + * @param consentAttributes consent attribute key and values map + * @return a consent attributes resource + * @throws ConsentMgtException thrown if an error occurs in the process + */ + boolean storeConsentAttributes(String consentID, Map consentAttributes) + throws + ConsentMgtException; + + /** + * This method is used to get consent attributes for a provided attribute keys list related to a particular consent. + * + * @param consentID consent ID + * @param consentAttributeKeys consent attribute keys list + * @return a consent attributes resource + * @throws ConsentMgtException thrown if an error occurs in the process + */ + ConsentAttributes getConsentAttributes(String consentID, ArrayList consentAttributeKeys) + throws + ConsentMgtException; + + /** + * This method is used to get consent attributes related to a particular consent. + * + * @param consentID consent ID + * @return a consent attributes resource + * @throws ConsentMgtException thrown if an error occurs in the process + */ + ConsentAttributes getConsentAttributes(String consentID) throws + ConsentMgtException; + + /** + * This method is used to get consent attributes for a provided attribute name. + * + * @param attributeName attribute name + * @return a map with related consent ID and the attribute values + * @throws ConsentMgtException thrown if an error occurs in the process + */ + Map getConsentAttributesByName(String attributeName) throws + ConsentMgtException; + + + /** + * This method is used to get consent attributes for a provided attribute name and attribute value. + * + * @param attributeName attribute name + * @param attributeValue attribute value + * @return Consent ID related to the given attribute key and value + * @throws ConsentMgtException thrown if an error occurs in the process + */ + ArrayList getConsentIdByConsentAttributeNameAndValue(String attributeName, String attributeValue) + throws + ConsentMgtException; + + /** + * This method is used to delete the provided consent attributes for a particular consent. + * + * @param consentID consent ID + * @param consentAttributes attributes to update + * @return updated consent attributes + * @throws ConsentMgtException thrown if an error occurs in the process + */ + ConsentAttributes updateConsentAttributes(String consentID, Map consentAttributes) + throws + ConsentMgtException; + + /** + * This method is used to delete the provided consent attributes for a particular consent. + * + * @param consentID consent ID + * @param attributeKeysList attributes to delete + * @return true if deletion is successful + * @throws ConsentMgtException thrown if an error occurs in the process + */ + boolean deleteConsentAttributes(String consentID, ArrayList attributeKeysList) + throws + ConsentMgtException; + + /** + * This method is used to search audit records. Useful for auditing purposes. All the input parameters are + * optional. If all parameters are null, all the audit records will be returned. + * + * @param consentID consent ID + * @param status status of the audit records needed + * @param actionBy user who performed the status change + * @param fromTime from time + * @param toTime to time + * @param statusAuditID ID of a specific audit record that need to be searched + * @return a list of consent status audit records + * @throws ConsentMgtException thrown if an error occurs + */ + ArrayList searchConsentStatusAuditRecords(String consentID, String status, + String actionBy, Long fromTime, Long toTime, + String statusAuditID) + throws + ConsentMgtException; + + /** + * This method is used to retrieve a list of consent status audit records by consent_id. + * + * @param consentIDs list of consentIDs (optional) + * @param limit limit + * @param offset offset + * @return returns a list of consent status audit records. + * @throws ConsentMgtException thrown if a database error occurs + */ + ArrayList getConsentStatusAuditRecords(ArrayList consentIDs, Integer limit, + Integer offset) + throws + ConsentMgtException; + + /** + * This method is used to store the details of the previous consent when an consent amendment happens. + * The consent ID is mandatory. The detailed consent resource for the previous consent and the amendedTimestamp + * is mandatory to be set in the ConsentHistoryResource. + * + * @param consentID consent ID + * @param consentHistoryResource detailed consent resource and other history parameters of the previous consent + * @param currentConsentResource detailed consent resource of the current (new) consent + * @return true if all operations are successful + * @throws ConsentMgtException thrown if any error occurs in the process + */ + boolean storeConsentAmendmentHistory(String consentID, ConsentHistoryResource consentHistoryResource, + DetailedConsentResource currentConsentResource) + throws + ConsentMgtException; + + /** + * This method is used to retrieve consent amendment history for a given consentId. Consent ID is mandatory. + * + * @param consentID consent ID + * @return a map of consent history resources + * @throws ConsentMgtException thrown if any error occurs in the process + */ + Map getConsentAmendmentHistoryData( + List statusAuditRecordIds, + String consentID) + throws + ConsentMgtException; + + /** + * This method is used to search detailed consents for the given lists of parameters. Following optional lists + * can be passed to retrieve detailed consents. The search will be performed according to the provided input. Any + * list can contain any number of elements. The conjunctive result will be returned. If all lists are passed as + * null, all the consents related to other search parameters will be returned. + * + * 1. A list of consent IDs + * 2. A list of client IDs + * 3. A list of consent types + * 4. A list of consent statuses + * 5. A list of user IDs + * + * (All above lists are optional) + * + * @param consentIDs consent IDs optional list + * @param clientIDs client IDs optional list + * @param consentTypes consent types optional list + * @param consentStatuses consent statuses optional list + * @param userIDs user IDs optional list + * @param fromTime from time + * @param toTime to time + * @param limit limit + * @param offset offset + * @return a list of detailed consent resources according to the provided parameters + * @throws ConsentMgtException thrown if any error occur + */ + ArrayList searchDetailedConsents(String orgID, ArrayList consentIDs, + ArrayList clientIDs, + ArrayList consentTypes, + ArrayList consentStatuses, + ArrayList userIDs, Long fromTime, Long toTime, + Integer limit, Integer offset) + throws + ConsentMgtException; + + + /** + * This method is used to amend the selected properties of the entire detailed consent. The consent ID is mandatory. + * One of consent receipt or validity period must be provided. + * An audit record is created to indicate that the consent is + * amended. But the consent status won't be changed (since when an authorized consent is amended, the status + * remains the same) + * + * @param consentID consent ID + * @param consentReceipt new consent receipt + * @param consentValidityTime new consent validity time + * @param authID authorization ID + * @param accountIDsMapWithPermissions accounts IDs with relative permissions + * @param newConsentStatus new consent status + * @param consentAttributes new consent attributes key and values map + * @param userID user ID to create audit record + * @param additionalAmendmentData A Data Map to pass any additional data that needs to be amended in the + * consent + * @return the updated detailed consent resource + * @throws ConsentMgtException thrown if any error occurs in the process + */ + DetailedConsentResource amendDetailedConsent(String consentID, String consentReceipt, Long consentValidityTime, + String authID, Map> accountIDsMapWithPermissions, + String newConsentStatus, Map consentAttributes, + String userID, Map additionalAmendmentData) + throws + ConsentMgtException; + + /** + * + * @param orgId + * @param consentID + * @param consentReceipt + * @param consentValidityTime + * @param reAuthorizationResources + * @param newConsentStatus + * @param consentAttributes + * @param userID + * @param newAuthResources + * @return + * @throws ConsentMgtException + */ + DetailedConsentResource amendDetailedConsentWithBulkAuthResource(String orgId, String consentID, + String consentReceipt, + Long consentValidityTime, + ArrayList + reAuthorizationResources, + + String newConsentStatus, + Map consentAttributes, + String userID, + ArrayList newAuthResources) + throws + ConsentMgtException; + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java new file mode 100644 index 000000000..df4f4cef1 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/constants/ConsentCoreServiceConstants.java @@ -0,0 +1,140 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.constants; + +/** + * Consent Core Service Constants. + */ +public class ConsentCoreServiceConstants { + + public static final String TEST = "test123v3"; + public static final String CONSENT_RESOURCE = "ConsentResource"; + public static final String DETAILED_CONSENT_RESOURCE = "DetailedConsentResource"; + public static final String CONSENT_AMENDMENT_HISTORY_RESOURCE = "ConsentAmendmentHistory"; + public static final String CONSENT_AMENDMENT_TIME = "ConsentAmendmentTime"; + public static final String ACTIVE_MAPPING_STATUS = "active"; + public static final String INACTIVE_MAPPING_STATUS = "inactive"; + public static final String RECEIPT = "RECEIPT"; + public static final String VALIDITY_TIME = "VALIDITY_TIME"; + public static final String UPDATED_TIME = "UPDATED_TIME"; + public static final String CURRENT_STATUS = "CURRENT_STATUS"; + public static final String MAPPING_STATUS = "MAPPING_STATUS"; + public static final String CONSENT_AMENDED_STATUS = "amended"; + public static final String TYPE_CONSENT_BASIC_DATA = "ConsentData"; + public static final String TYPE_CONSENT_ATTRIBUTES_DATA = "ConsentAttributesData"; + public static final String TYPE_CONSENT_MAPPING_DATA = "ConsentMappingData"; + public static final String TYPE_CONSENT_AUTH_RESOURCE_DATA = "ConsentAuthResourceData"; + public static final String CREATE_CONSENT_REASON = "Create consent"; + public static final String CREATE_EXCLUSIVE_AUTH_CONSENT_REASON = "Create exclusive authorization consent"; + public static final String CONSENT_FILE_UPLOAD_REASON = "Upload consent file"; + public static final String USER_ACCOUNTS_BINDING_REASON = "Bind user accounts to consent"; + public static final String CONSENT_REVOKE_REASON = "Revoke the consent"; + public static final String CONSENT_REAUTHORIZE_REASON = "Reauthorize consent"; + public static final String CONSENT_AMEND_REASON = "Amend consent"; + public static final String DEFAULT_PERMISSION_VALUE = "n/a"; + public static final String ADDITIONAL_AUTHORIZATION_RESOURCES = "AdditionalAuthorizationResources"; + public static final String ADDITIONAL_MAPPING_RESOURCES = "AdditionalMappingResources"; + public static final String AMENDMENT_REASON_CONSENT_AMENDMENT_FLOW = "ConsentAmendmentFlow"; + public static final String AMENDMENT_REASON_CONSENT_REVOCATION = "ConsentRevocation"; + + // Error Constants + public static final String ORGANIZATION_MISMATCH_ERROR_MSG = + "OrgInfo does not match, please provide the correct OrgInfo"; + public static final String DATA_INSERTION_ROLLBACK_ERROR_MSG = "Error occurred while inserting data. Rolling" + + " back the transaction"; + public static final String DATABASE_CONNECTION_CLOSE_LOG_MSG = "Closing database connection"; + public static final String TRANSACTION_COMMITTED_LOG_MSG = "Transaction committed"; + public static final String CANNOT_PROCEED_WITH_CONSENT_CREATION = "Cannot proceed since client ID, receipt, " + + "consent type or consent status is missing."; + public static final String CANNOT_PROCEED_WITH_IMPLICIT_AUTH = "Cannot proceed with implicit authorization" + + " creation without authorizationStatus or authorizationType or userId provided"; + public static final String CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR = "One or more of following" + + " data are missing (Client ID, receipt, consent type, consent status, auth status, auth type, applicable " + + "existing consent status, new existing consent status, new current consent status), cannot proceed"; + public static final String DATA_RETRIEVE_ERROR_MSG = "Error occurred while retrieving data"; + public static final String DATA_UPDATE_ROLLBACK_ERROR_MSG = "Error occurred while updating consent data. Rolling " + + "back the transaction"; + public static final String NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR = "New consent status or " + + "applicable status for file upload is missing. Cannot proceed"; + + public static final String ATTRIBUTE_UPDATE_ERROR_MSG = "Error occurred while updating consent attributes. " + + "Rolling back the transaction"; + public static final String DATA_DELETE_ROLLBACK_ERROR_MSG = "Error occurred while deleting consent data. Rolling " + + "back the transaction"; + public static final String CONSENT_ATTRIBUTES_DELETE_ERROR_MSG = "Error occurred while deleting consent " + + "attributes in the database"; + + public static final String CONSENT_ID_MISSING_ERROR_MSG = "Consent ID is missing, cannot proceed"; + public static final String CONSENT_FILE_MISSING_ERROR_MSG = "Consent ID or Consent File content is missing. " + + "Cannot proceed."; + public static final String CONSENT_INVALID_STATUS_ERROR_MSG = "The consent is not in required state to proceed"; + public static final String AUTH_DETAILS_MISSING_ERROR_MSG = "Consent ID, authorization type, user ID " + + "or authorization status is missing, cannot proceed"; + public static final String AUTH_ID_MISSING_ERROR_MSG = "Authorization ID is missing, cannot proceed"; + public static final String AUTH_RESOURCE_SEARCH_ERROR_MSG = "Error occurred while searching authorization" + + " resources"; + public static final String AUTH_STATUS_MISSING_ERROR_MSG = "Authorization ID or newAuthorizationStatus" + + " is missing. Cannot proceed."; + public static final String AUTH_USER_ID_MISSING_ERROR_MSG = "Authorization ID or user ID is missing. " + + "Cannot proceed."; + public static final String USER_BIND_DETAILS_MISSING_ERROR_MSG = "Consent ID, client ID, consent type, user ID," + + " authorization ID, new authorization status or new consent status is missing, cannot proceed."; + public static final String ACC_ID_PERMISSION_DETAILS_MISSING_ERROR = "Account IDs and relative permissions" + + " are not present, cannot proceed"; + public static final String CONSENT_UPDATE_DETAILS_MISSING_ERROR = "Consent ID, userID or newConsentStatus" + + " is missing. Cannot proceed."; + public static final String ACC_MAPPING_DETAILS_MISSING_ERROR = "Authorization ID, accountID/permission map" + + " is not found, cannot proceed"; + public static final String ACC_MAPPING_ID_MISSING_ERROR_MSG = "Account mapping IDs are not provided, " + + "cannot proceed"; + public static final String CONSENT_STATUS_MISSING_ERROR_MSG = "New consent status is missing," + + " cannot proceed"; + + public static final String USER_ID_MISSING_ERROR_MSG = "User ID is required for token revocation, cannot proceed"; + public static final String USER_ID_MISMATCH_ERROR_MSG = "Requested UserID %s and Consent UserID %s do not match," + + " cannot proceed."; + public static final String REVOKE_DETAILS_MISSING_ERROR_MSG = "Client ID, new consent status, consent type," + + " user ID or applicable consent status to revoke is missing, cannot proceed"; + public static final String RE_AUTH_DETAILS_MISSING_ERROR_MSG = "Consent ID, auth ID, user ID, account permissions" + + " map, applicable consent status, new consent status or current consent status is not present," + + " cannot proceed"; + public static final String RE_AUTH_RESOURCE_DETAILS_MISSING_ERROR = "Consent ID, user ID, account" + + " permissions map, current consent status, new consent status, new existing auth status, " + + "new auth status or new auth type is not present, cannot proceed"; + public static final String CONSENT_ATTRIBUTES_MISSING_ERROR_MSG = "ConsentID or consentAttributes is missing," + + " cannot proceed"; + public static final String CONSENT_ATTRIBUTE_KEYS_MISSING_ERROR_MSG = "Consent ID or consent attributes keys" + + " are missing, cannot proceed"; + public static final String CONSENT_ATTRIBUTE_NAME_MISSING_ERROR_MSG = "Attribute name is not provided," + + " cannot proceed"; + public static final String ATTRIBUTE_NAME_VALUE_MISSING_ERROR_MSG = "Attribute name or value is not provided," + + " cannot proceed"; + public static final String ATTRIBUTE_MAP_MISSING_ERROR_MSG = "Consent ID or attributes map is not provided," + + " cannot proceed"; + public static final String ATTRIBUTE_LIST_MISSING_ERROR_MSG = "Consent ID or attributes list is not provided," + + " cannot proceed"; + public static final String AUDIT_RECORD_SEARCH_ERROR_MSG = "Error occurred while searching audit records"; + public static final String AMEND_DETAILS_MISSING_ERROR_MSG = "Consent ID or detailed consent resource or " + + "amendment reason or amended timestamp in consent history resource is empty/zero"; + public static final String DETAIL_CONSENT_SEARCH_ERROR_MSG = "Error occurred while searching detailed consents"; + public static final String CONSENT_DATA_MISSING_ERROR_MSG = "Consent ID or both consent receipt and consent" + + " validity period are not provided, cannot proceed"; + public static final String DETAILED_CONSENT_DATA_MISSING_ERROR_MSG = "Auth ID, user ID, account permissions map," + + " new consent status or new consent attributes is not present, cannot proceed"; +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/exception/ConsentMgtException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/exception/ConsentMgtException.java new file mode 100644 index 000000000..985f7e261 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/exception/ConsentMgtException.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.exception; + +import javax.ws.rs.core.Response; + +/** + * Used for creating runtime exceptions for financial services modules. + */ +public class ConsentMgtException extends Exception { + + private static final long serialVersionUID = -5686395831712095972L; + private Response.Status errorCode; + + public ConsentMgtException(Response.Status errorCode, Throwable cause) { + + super(cause); + this.errorCode = errorCode; + } + + public ConsentMgtException(Response.Status errorCode, String message) { + + super(message); + this.errorCode = errorCode; + } + + + public ConsentMgtException(Response.Status status, String message, Throwable cause) { + super(message, cause); + this.errorCode = status; + + } + + public Response.Status getErrorCode() { + + return errorCode; + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java new file mode 100644 index 000000000..ba132c518 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImpl.java @@ -0,0 +1,2475 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.impl; + +import net.minidev.json.JSONObject; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.persistence.ConsentStoreInitializer; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.DatabaseUtils; +import org.wso2.financial.services.accelerator.consent.mgt.service.ConsentCoreService; +import org.wso2.financial.services.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; +import org.wso2.financial.services.accelerator.consent.mgt.service.util.ConsentCoreServiceUtil; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.Response; + + +/** + * Consent core service implementation. + */ +public class ConsentCoreServiceImpl implements ConsentCoreService { + + private static final Log log = LogFactory.getLog(ConsentCoreServiceImpl.class); + + private static ConsentCoreServiceImpl consentCoreService = null; + + public static ConsentCoreServiceImpl getInstance() { + if (consentCoreService == null) { + consentCoreService = new ConsentCoreServiceImpl(); + } + return consentCoreService; + } + + @Override + public DetailedConsentResource createAuthorizableConsentWithBulkAuth(ConsentResource consentResource, + ArrayList + authorizationResources, + boolean isImplicitAuth) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentResource.getClientID()) || StringUtils.isBlank(consentResource.getReceipt()) || + StringUtils.isBlank(consentResource.getConsentType()) || + StringUtils.isBlank(consentResource.getCurrentStatus())) { + + log.error(ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_CONSENT_CREATION); + + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_CONSENT_CREATION); + } + + if (isImplicitAuth) { + + for (AuthorizationResource authorizationResource : authorizationResources) { + if (StringUtils.isBlank(authorizationResource.getAuthorizationStatus()) || + StringUtils.isBlank(authorizationResource.getAuthorizationType()) || + StringUtils.isBlank(authorizationResource.getUserID())) { + log.error(ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + } + } + + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + DetailedConsentResource detailedConsentResource = ConsentCoreServiceUtil + .createAuthorizableConsentWithAuditRecordWithBulkAuthResources(connection, + consentCoreDAO, consentResource, + authorizationResources, isImplicitAuth); + DatabaseUtils.commitTransaction(connection); + return detailedConsentResource; + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, + e); + } catch (ConsentDataRetrievalException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public DetailedConsentResource createAuthorizableConsent(ConsentResource consentResource, String userID, + String authStatus, String authType, + boolean isImplicitAuth) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentResource.getClientID()) || StringUtils.isBlank(consentResource.getReceipt()) || + StringUtils.isBlank(consentResource.getConsentType()) || + StringUtils.isBlank(consentResource.getCurrentStatus())) { + + log.error(ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_CONSENT_CREATION); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_CONSENT_CREATION); + } + + if (isImplicitAuth) { + if (StringUtils.isBlank(authStatus) || StringUtils.isBlank(authType)) { + log.error(ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + } + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + DetailedConsentResource detailedConsentResource = ConsentCoreServiceUtil + .createAuthorizableConsentWithAuditRecord(connection, consentCoreDAO, consentResource, + userID, authStatus, authType, isImplicitAuth); + DatabaseUtils.commitTransaction(connection); + return detailedConsentResource; + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataRetrievalException e) { + throw new RuntimeException(e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public DetailedConsentResource createExclusiveConsent(ConsentResource consentResource, String userID, + String authStatus, String authType, + String applicableExistingConsentsStatus, + String newExistingConsentStatus, + boolean isImplicitAuth) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentResource.getClientID()) || StringUtils.isBlank(consentResource.getReceipt()) || + StringUtils.isBlank(consentResource.getConsentType()) || + StringUtils.isBlank(consentResource.getCurrentStatus()) || StringUtils.isBlank(userID) + || StringUtils.isBlank(applicableExistingConsentsStatus) + || StringUtils.isBlank(newExistingConsentStatus)) { + + log.error(ConsentCoreServiceConstants.CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants + .CREATE_EXCLUSIVE_CONSENT_MANDATORY_PARAMETER_MISSING_ERROR); + } + + if (isImplicitAuth) { + if (StringUtils.isBlank(authStatus) || StringUtils.isBlank(authType)) { + log.error(ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + } + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + // Update existing consent statuses and revoke their account mappings + ConsentCoreServiceUtil.updateExistingConsentStatusesAndRevokeAccountMappings(connection, + consentCoreDAO, consentResource, userID, applicableExistingConsentsStatus, + newExistingConsentStatus); + + // Create a new consent, audit record and authorization resource if allowed + DetailedConsentResource storedDetailedConsentResource = ConsentCoreServiceUtil + .createAuthorizableConsentWithAuditRecord(connection, consentCoreDAO, consentResource, + userID, authStatus, authType, isImplicitAuth); + + // Commit the transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return storedDetailedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ConsentResource getConsent(String consentID, boolean withAttributes) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + ConsentResource retrievedConsentResource; + + // Get consent attributes if needed + if (!withAttributes) { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving consent for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentID); + } else { + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving consent with consent attributes for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + retrievedConsentResource = consentCoreDAO.getConsentResourceWithAttributes(connection, consentID); + } + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public DetailedConsentResource getDetailedConsent(String consentID) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + + // Retrieve the detailed consent resource + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving detailed consent for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + DetailedConsentResource retrievedDetailedConsentResource = consentCoreDAO + .getDetailedConsentResource(connection, consentID); + + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedDetailedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + if (e.getMessage() != null) { + if (e.getMessage().equals(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG)) { + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG, e); + } + } + + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public DetailedConsentResource getConsentWithAuthorizationResources(String consentID) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + + // Retrieve the detailed consent resource + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving detailed consent for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + DetailedConsentResource retrievedDetailedConsentResource = consentCoreDAO + .getConsentResourceWithAuthorizationResources(connection, consentID); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedDetailedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + if (e.getMessage() != null) { + if (e.getMessage().equals(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG)) { + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG, e); + } + } + + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean createConsentFile(ConsentFile consentFileResource, String newConsentStatus, String userID, + String applicableStatusToFileUpload) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentFileResource.getConsentID()) || + StringUtils.isBlank(consentFileResource.getConsentFile())) { + + log.error(ConsentCoreServiceConstants.CONSENT_FILE_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_FILE_MISSING_ERROR_MSG); + } + + String consentID = consentFileResource.getConsentID(); + + if (StringUtils.isBlank(newConsentStatus) || StringUtils.isBlank(applicableStatusToFileUpload)) { + log.error(ConsentCoreServiceConstants.NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants + .NEW_CONSENT_STATUS_OR_APPLICABLE_STATUS_MISSING_ERROR); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Get the existing consent to validate status + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving the consent for ID: %s to validate status", + consentID.replaceAll("[\r\n]", ""))); + } + ConsentResource existingConsentResource = consentCoreDAO.getConsentResource(connection, consentID); + + String existingConsentStatus = existingConsentResource.getCurrentStatus(); + + // Validate status of the consent + if (!applicableStatusToFileUpload.equals(existingConsentResource.getCurrentStatus())) { + log.error(ConsentCoreServiceConstants.CONSENT_INVALID_STATUS_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_INVALID_STATUS_ERROR_MSG); + } + + // Store the consent file + if (log.isDebugEnabled()) { + log.debug(String.format("Creating the consent file for the consent of ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.storeConsentFile(connection, consentFileResource); + + // Update consent status with new status + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the consent for ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); + + // Create audit record and execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_RESOURCE, existingConsentResource); +// ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, +// newConsentStatus, +// existingConsentStatus, ConsentCoreServiceConstants.CONSENT_FILE_UPLOAD_REASON, +// existingConsentResource.getClientID(), consentDataMap); + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ConsentFile getConsentFile(String consentId) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentId)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + try { + //Retrieve consent status audit records. + return consentCoreDAO.getConsentFile(connection, consentId); + + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public AuthorizationResource createConsentAuthorization(AuthorizationResource authorizationResource) + throws + ConsentMgtException { + + if (authorizationResource == null || StringUtils.isBlank(authorizationResource.getConsentID()) || + StringUtils.isBlank(authorizationResource.getAuthorizationType()) || + StringUtils.isBlank(authorizationResource.getAuthorizationStatus())) { + + log.error(ConsentCoreServiceConstants.AUTH_DETAILS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.AUTH_DETAILS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Create authorization resource + if (log.isDebugEnabled()) { + log.debug(String.format("Creating authorization resource for the consent of ID: %s", + authorizationResource.getConsentID().replaceAll("[\r\n]", ""))); + } + AuthorizationResource storedAuthorizationResource = + consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); + + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return storedAuthorizationResource; + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, + e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public AuthorizationResource getAuthorizationResource(String authorizationID, String orgID) throws + ConsentMgtException { + + if (StringUtils.isBlank(authorizationID)) { + log.error(ConsentCoreServiceConstants.AUTH_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.AUTH_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + AuthorizationResource retrievedAuthorizationResource; + + // Get consent file + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving authorization resource for authorization ID: %s", + authorizationID.replaceAll("[\r\n]", ""))); + } + retrievedAuthorizationResource = consentCoreDAO.getAuthorizationResource(connection, authorizationID, + orgID); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedAuthorizationResource; + } catch (ConsentDataRetrievalException e) { + if (e.getMessage().equals(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG)) { + throw new ConsentMgtException(Response.Status.NOT_FOUND, e.getMessage()); + } + + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, + e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ArrayList searchAuthorizations(String consentID) + throws + ConsentMgtException { + return searchAuthorizations(consentID, null); + } + + @Override + public ArrayList searchAuthorizationsForUser(String userID) + throws + ConsentMgtException { + return searchAuthorizations(null, userID); + } + + @Override + public ArrayList searchAuthorizations(String consentID, String userID) + throws + ConsentMgtException { + + ArrayList authorizationResources; + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + log.debug("Searching authorization resources"); + authorizationResources = consentCoreDAO.searchConsentAuthorizations(connection, consentID, userID); + + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.AUTH_RESOURCE_SEARCH_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.AUTH_RESOURCE_SEARCH_ERROR_MSG, e); + } + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + return authorizationResources; + } + + @Override + public AuthorizationResource updateAuthorizationStatus(String authorizationId, String newAuthorizationStatus, + String orgID) + throws + ConsentMgtException { + + if (StringUtils.isBlank(authorizationId) || StringUtils.isBlank(newAuthorizationStatus)) { + + log.error(ConsentCoreServiceConstants.AUTH_STATUS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.AUTH_STATUS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Update authorization status with new status + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the authorization for ID: %s", + authorizationId.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateAuthorizationStatus(connection, authorizationId, newAuthorizationStatus); + AuthorizationResource updatedAuthorizationResource = consentCoreDAO + .getAuthorizationResource(connection, authorizationId, orgID); + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return updatedAuthorizationResource; + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public AuthorizationResource updateAuthorizationUser(String authorizationID, String userID, String orgID) + throws + ConsentMgtException { + + if (StringUtils.isBlank(authorizationID) || StringUtils.isBlank(userID)) { + + log.error(ConsentCoreServiceConstants.AUTH_USER_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.AUTH_USER_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Updating the authorized user + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the user for authorization ID: %s", + authorizationID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateAuthorizationUser(connection, authorizationID, userID); + AuthorizationResource updatedAuthResource = consentCoreDAO + .getAuthorizationResource(connection, authorizationID, orgID); + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return updatedAuthResource; + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, + String authID, ArrayList accountIDs, + String newAuthStatus, String newCurrentConsentStatus) + throws + ConsentMgtException { + + Map> accountIDsMapWithPermissions = new HashMap<>(); + ArrayList permissionsDefault = new ArrayList<>(); + permissionsDefault.add(ConsentCoreServiceConstants.DEFAULT_PERMISSION_VALUE); + + for (String accountId : accountIDs) { + accountIDsMapWithPermissions.put(accountId, permissionsDefault); + } + + return bindUserAccountsToConsent(consentResource, userID, authID, accountIDsMapWithPermissions, newAuthStatus, + newCurrentConsentStatus); + } + + @Override + public boolean bindUserAccountsToConsent(ConsentResource consentResource, String userID, + String authID, Map> accountIDsMapWithPermissions, + String newAuthStatus, String newCurrentConsentStatus) + throws + ConsentMgtException { + + String consentID = consentResource.getConsentID(); + String clientID = consentResource.getClientID(); + String consentType = consentResource.getConsentType(); + + if (StringUtils.isBlank(consentID) || StringUtils.isBlank(clientID) || StringUtils.isBlank(consentType) + || StringUtils.isBlank(userID) || StringUtils.isBlank(authID) || StringUtils.isBlank(newAuthStatus) + || StringUtils.isBlank(newCurrentConsentStatus)) { + log.error(ConsentCoreServiceConstants.USER_BIND_DETAILS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.USER_BIND_DETAILS_MISSING_ERROR_MSG); + } + + if (MapUtils.isEmpty(accountIDsMapWithPermissions)) { + log.error(ConsentCoreServiceConstants.ACC_ID_PERMISSION_DETAILS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.ACC_ID_PERMISSION_DETAILS_MISSING_ERROR); + } + + Connection connection = DatabaseUtils.getDBConnection(); + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + // Update authorization resource of current consent + if (log.isDebugEnabled()) { + log.debug(String.format("Update authorization status and authorization user for current " + + "consent ID : %s", consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateAuthorizationUser(connection, authID, userID); + consentCoreDAO.updateAuthorizationStatus(connection, authID, newAuthStatus); + + // Create account mappings for current consent + if (log.isDebugEnabled()) { + log.debug(String.format("Creating account mappings for current consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + for (Map.Entry> entry : accountIDsMapWithPermissions.entrySet()) { + String accountID = entry.getKey(); + for (String value : entry.getValue()) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAccountID(accountID); + consentMappingResource.setPermission(value); + consentMappingResource.setAuthorizationID(authID); + consentMappingResource.setMappingStatus(ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); + consentCoreDAO.storeConsentMappingResource(connection, consentMappingResource); + } + } + + // Update current consent status + if (log.isDebugEnabled()) { + log.debug(String.format("Update the status of the current consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateConsentStatus(connection, consentID, newCurrentConsentStatus); + + // Create audit record for the consent status update and execute the state change listener +// HashMap consentDataMap = new HashMap<>(); +// consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, consentResource); +// ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, +// newCurrentConsentStatus, consentResource.getCurrentStatus(), +// ConsentCoreServiceConstants.USER_ACCOUNTS_BINDING_REASON, clientID, consentDataMap); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public DetailedConsentResource updateConsentStatus(String consentId, String newConsentStatus) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentId) || StringUtils.isBlank(newConsentStatus)) { + + log.error(ConsentCoreServiceConstants.CONSENT_UPDATE_DETAILS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_UPDATE_DETAILS_MISSING_ERROR); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Get the existing consent to validate status + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving the consent for ID: %s to validate status", + consentId.replaceAll("[\r\n]", ""))); + } + + // Update consent status with new status + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the consent for ID: %s", + consentId.replaceAll("[\r\n]", ""))); + } + + consentCoreDAO.updateConsentStatus(connection, consentId, newConsentStatus); + DetailedConsentResource existingConsentResource = consentCoreDAO + .getDetailedConsentResource(connection, consentId); + String existingConsentStatus = existingConsentResource.getCurrentStatus(); + ArrayList authResources = existingConsentResource.getAuthorizationResources(); + + // Previous consent status is not added in reason because it can be null + String auditMessage = "Consent status updated to " + newConsentStatus; + for (AuthorizationResource authResource : authResources) { + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, existingConsentResource); + ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentId, + authResource.getUserID(), newConsentStatus, existingConsentStatus, auditMessage, + existingConsentResource.getClientID(), consentDataMap); + } + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + + return existingConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataInsertionException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public void updateConsentStatusWithImplicitReasonAndUserId(String consentId, + String newConsentStatus, + String reason, String userID, String orgID) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentId) || StringUtils.isBlank(newConsentStatus) || StringUtils.isBlank(userID)) { + + log.error(ConsentCoreServiceConstants.CONSENT_UPDATE_DETAILS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_UPDATE_DETAILS_MISSING_ERROR); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Get the existing consent to validate status + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving the consent for ID: %s to validate status", + consentId.replaceAll("[\r\n]", ""))); + } + + // Update consent status with new status + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the consent for ID: %s", + consentId.replaceAll("[\r\n]", ""))); + } + DetailedConsentResource existingConsentResource = consentCoreDAO + .getDetailedConsentResource(connection, consentId); + + + + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgID, existingConsentResource.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + consentCoreDAO.updateConsentStatus(connection, consentId, newConsentStatus); + String existingConsentStatus = existingConsentResource.getCurrentStatus(); + ArrayList authResources = existingConsentResource.getAuthorizationResources(); + + // Previous consent status is not added in reason because it can be null + String auditMessage = "Consent status updated to " + newConsentStatus; + + //TODO: it correct? + + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, + existingConsentResource); + DetailedConsentResource newConsentResource = existingConsentResource.clone(); + newConsentResource.setCurrentStatus(newConsentStatus); + + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, newConsentResource); + ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentId, + userID, newConsentStatus, existingConsentStatus, auditMessage, + existingConsentResource.getClientID(), consentDataMap); + + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + existingConsentResource.setCurrentStatus(newConsentStatus); + + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + if (e.getMessage().equals(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG)) { + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG, e); + } + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public void bulkUpdateConsentStatus(String orgID, String clientId, String status, String reason, String userId, + String consentType, ArrayList applicableExistingStatus) throws + ConsentMgtException { + + + ArrayList clientIds = new ArrayList<>(); + if (clientId != null) { + clientIds.add(clientId); + } + ArrayList userIds = new ArrayList<>(); + if (userId != null) { + userIds.add(userId); + } + ArrayList consentTypes = new ArrayList<>(); + + if (consentType != null) { + consentTypes.add(consentType); + } + ArrayList detailedConsentResources; + + + // get consents by client id and update status + Connection connection = DatabaseUtils.getDBConnection(); + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + detailedConsentResources = consentCoreDAO.searchConsents(connection, orgID, new ArrayList<>(), + clientIds, + consentTypes, applicableExistingStatus, null, null, + null, null, null); + + } catch (ConsentDataRetrievalException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + + if (detailedConsentResources.isEmpty()) { + throw new ConsentMgtException(Response.Status.NOT_FOUND, + ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG); + } + for (DetailedConsentResource consent : detailedConsentResources) { + updateConsentStatusWithImplicitReasonAndUserId(consent.getConsentID(), status, reason, userId, orgID); + + } + + + } + + + @Override + public ArrayList createConsentAccountMappings(String authID, Map> accountIDsMapWithPermissions) throws + ConsentMgtException { + + if (StringUtils.isBlank(authID) || MapUtils.isEmpty(accountIDsMapWithPermissions)) { + log.error(ConsentCoreServiceConstants.ACC_MAPPING_DETAILS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.ACC_MAPPING_DETAILS_MISSING_ERROR); + } + + ArrayList storedConsentMappingResources = new ArrayList<>(); + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Create account mapping resources + if (log.isDebugEnabled()) { + log.debug(String.format("Creating consent account mapping resources for authorization ID: %s", + authID.replaceAll("[\r\n]", ""))); + } + for (Map.Entry> entry : accountIDsMapWithPermissions.entrySet()) { + String accountID = entry.getKey(); + for (String value : entry.getValue()) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAccountID(accountID); + consentMappingResource.setPermission(value); + consentMappingResource.setAuthorizationID(authID); + consentMappingResource.setMappingStatus(ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); + storedConsentMappingResources.add(consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource)); + } + } + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return storedConsentMappingResources; + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean deactivateAccountMappings(ArrayList accountMappingIDs) throws + ConsentMgtException { + + if (accountMappingIDs.isEmpty()) { + log.error(ConsentCoreServiceConstants.ACC_MAPPING_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.ACC_MAPPING_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Deactivate account mapping resources + log.debug("Deactivating consent account mapping resources for given mapping IDs"); + + consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDs, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean updateAccountMappingStatus(ArrayList accountMappingIDs, + String newMappingStatus) + throws + ConsentMgtException { + + if (accountMappingIDs.isEmpty()) { + log.error(ConsentCoreServiceConstants.ACC_MAPPING_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.ACC_MAPPING_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // update account mapping resources + log.debug("Deactivating consent account mapping resources for given mapping IDs"); + + consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDs, + newMappingStatus); + + // Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean revokeConsent(String consentID, String revokedConsentStatus) + throws + ConsentMgtException { + return revokeConsentWithReason(consentID, revokedConsentStatus, null, true, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + @Override + public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String revokedReason) + throws + ConsentMgtException { + return revokeConsentWithReason(consentID, revokedConsentStatus, null, true, + revokedReason); + } + + @Override + public boolean revokeConsent(String consentID, String revokedConsentStatus, String userID) + throws + ConsentMgtException { + return revokeConsentWithReason(consentID, revokedConsentStatus, userID, true, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + @Override + public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, + String revokedReason) + throws + ConsentMgtException { + return revokeConsentWithReason(consentID, revokedConsentStatus, userID, true, revokedReason); + } + + @Override + public boolean revokeConsent(String consentID, String revokedConsentStatus, String userID, + boolean shouldRevokeTokens) + throws + ConsentMgtException { + return revokeConsentWithReason(consentID, revokedConsentStatus, userID, shouldRevokeTokens, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + @Override + public boolean revokeConsentWithReason(String consentID, String revokedConsentStatus, String userID, + boolean shouldRevokeTokens, String revokedReason) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || StringUtils.isBlank(revokedConsentStatus)) { + log.error(ConsentCoreServiceConstants.CONSENT_STATUS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_STATUS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + // Get existing detailed consent + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving existing consent of ID: %s for status validation", + consentID.replaceAll("[\r\n]", ""))); + } + DetailedConsentResource retrievedDetailedConsentResource = consentCoreDAO + .getDetailedConsentResource(connection, consentID); + String previousConsentStatus = retrievedDetailedConsentResource.getCurrentStatus(); + + //if previous status is same as the new status, return true +// if (previousConsentStatus.equals(revokedConsentStatus)) { +// throw new ConsentMgtException(Response.Status.BAD_REQUEST, +// "Consent is already revoked: " + revokedConsentStatus); +// } + // Update consent status as revoked + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the status of the consent of ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateConsentStatus(connection, consentID, revokedConsentStatus); + + if (shouldRevokeTokens) { + // Extract userId from authorizationResources + ArrayList authorizationResources = retrievedDetailedConsentResource + .getAuthorizationResources(); + //TODO : check this + String consentUserID = ""; + if (authorizationResources != null && !authorizationResources.isEmpty()) { + consentUserID = authorizationResources.get(0).getUserID(); + } + + if (StringUtils.isBlank(consentUserID)) { + log.error(ConsentCoreServiceConstants.USER_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.USER_ID_MISSING_ERROR_MSG); + } + +// if (!ConsentCoreServiceUtil.isValidUserID(userID, consentUserID)) { +// final String errorMsg = String.format(ConsentCoreServiceConstants.USER_ID_MISMATCH_ERROR_MSG, +// userID.replaceAll("[\r\n]", ""), +// consentUserID.replaceAll("[\r\n]", "")); +// log.error(errorMsg); +// throw new ConsentMgtException(errorMsg); +// } +// TokenRevocationUtil.revokeTokens(retrievedDetailedConsentResource, consentUserID); + } + + ArrayList consentMappingResources = retrievedDetailedConsentResource + .getConsentMappingResources(); + ArrayList mappingIDs = new ArrayList<>(); + + if (!consentMappingResources.isEmpty()) { + for (ConsentMappingResource resource : consentMappingResources) { + mappingIDs.add(resource.getMappingID()); + } + + // Update account mapping status as inactive + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the account mappings of consent ID: %s as inactive", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateConsentMappingStatus(connection, mappingIDs, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + } + + HashMap consentDataMap = new HashMap<>(); + // Get detailed consent status after the updates + DetailedConsentResource newDetailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, + newDetailedConsentResource); + + // Pass the previous status consent to persist as consent history + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, + retrievedDetailedConsentResource); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME, System.currentTimeMillis()); + + if (userID == null) { + if (!retrievedDetailedConsentResource.getAuthorizationResources().isEmpty()) { + userID = retrievedDetailedConsentResource.getAuthorizationResources().get(0).getUserID(); + + } else { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "please provide a userId"); + } + } + // Create an audit record execute state change listener + ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, + revokedConsentStatus, previousConsentStatus, revokedReason, + retrievedDetailedConsentResource.getClientID(), consentDataMap); + + //Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, + e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + return true; + } + + @Override + public boolean revokeExistingApplicableConsents(String clientID, String userID, String consentType, + String applicableStatusToRevoke, + String revokedConsentStatus, boolean shouldRevokeTokens) + throws + ConsentMgtException { + + if (StringUtils.isBlank(clientID) || StringUtils.isBlank(revokedConsentStatus) || StringUtils.isBlank(userID) + || StringUtils.isBlank(applicableStatusToRevoke) || StringUtils.isBlank(consentType)) { + log.error(ConsentCoreServiceConstants.REVOKE_DETAILS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.REVOKE_DETAILS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + + ArrayList accountMappingIDsList = new ArrayList<>(); + ArrayList clientIDsList = ConsentCoreServiceUtil.constructArrayList(clientID); + ArrayList userIDsList = ConsentCoreServiceUtil.constructArrayList(userID); + ArrayList consentTypesList = ConsentCoreServiceUtil.constructArrayList(consentType); + ArrayList consentStatusesList = ConsentCoreServiceUtil + .constructArrayList(applicableStatusToRevoke); + + // Get existing consents + log.debug("Retrieving existing consents"); + + // Only parameters needed for the search are provided, others are made null + ArrayList retrievedDetailedConsentResources = consentCoreDAO + .searchConsents(connection, null, null, clientIDsList, consentTypesList, + consentStatusesList, userIDsList, null, null, null, null); + + // Revoke existing consents and create audit records + for (DetailedConsentResource resource : retrievedDetailedConsentResources) { + String previousConsentStatus = resource.getCurrentStatus(); + + // Update consent status + if (log.isDebugEnabled()) { + log.debug(String.format("Updating consent status for consent ID: %s", + resource.getConsentID().replaceAll("[\r\n]", ""))); + } + consentCoreDAO.updateConsentStatus(connection, resource.getConsentID(), revokedConsentStatus); + + if (shouldRevokeTokens) { +// TokenRevocationUtil.revokeTokens(resource, userID); + } + + // Create an audit record for consent update + if (log.isDebugEnabled()) { + log.debug(String.format("Creating audit record for the status change of consent ID: %s", + resource.getConsentID().replaceAll("[\r\n]", ""))); + } + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, resource); +// ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, resource.getConsentID(), +// userID, +// revokedConsentStatus, previousConsentStatus, +// ConsentCoreServiceConstants.CONSENT_REVOKE_REASON, resource.getClientID(), +// consentDataMap); + + // Extract account mapping IDs for retrieved applicable consents + if (log.isDebugEnabled()) { + log.debug(String.format("Extracting account mapping IDs from consent ID: %s", + resource.getConsentID().replaceAll("[\r\n]", ""))); + } + for (ConsentMappingResource mappingResource : resource.getConsentMappingResources()) { + accountMappingIDsList.add(mappingResource.getMappingID()); + } + } + + // Update account mappings as inactive + log.debug("Deactivating account mappings"); + consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDsList, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + + //Commit transaction + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean reAuthorizeExistingAuthResource(String consentID, String authID, String userID, + Map> accountIDsMapWithPermissions, + String currentConsentStatus, String newConsentStatus) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || StringUtils.isBlank(authID) || StringUtils.isBlank(userID) + || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) + || StringUtils.isBlank(currentConsentStatus)) { + log.error(ConsentCoreServiceConstants.RE_AUTH_DETAILS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.RE_AUTH_DETAILS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + // Get detailed consent to retrieve account mappings + DetailedConsentResource detailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + +// // Update accounts if required +// ConsentCoreServiceUtil.updateAccounts(connection, consentCoreDAO, authID, +// accountIDsMapWithPermissions, +// detailedConsentResource, false); + + // Update consent status + consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); + + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); +// ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, +// newConsentStatus, +// currentConsentStatus, ConsentCoreServiceConstants.CONSENT_REAUTHORIZE_REASON, +// detailedConsentResource.getClientID(), consentDataMap); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean reAuthorizeConsentWithNewAuthResource(String consentID, String userID, Map> accountIDsMapWithPermissions, + String currentConsentStatus, String newConsentStatus, + String newExistingAuthStatus, String newAuthStatus, + String newAuthType) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || StringUtils.isBlank(userID) + || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) + || StringUtils.isBlank(currentConsentStatus) || StringUtils.isBlank(newExistingAuthStatus) + || StringUtils.isBlank(newAuthStatus) || StringUtils.isBlank(newAuthType)) { + log.error(ConsentCoreServiceConstants.RE_AUTH_RESOURCE_DETAILS_MISSING_ERROR); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.RE_AUTH_RESOURCE_DETAILS_MISSING_ERROR); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + + // Get authorizations related to current consent to revoke + ArrayList authorizationResources = + consentCoreDAO.searchConsentAuthorizations(connection, consentID, userID); + + ArrayList mappingResourcesToDeactivate + = new ArrayList(); + for (AuthorizationResource resource : authorizationResources) { + // Update existing authorizations + consentCoreDAO.updateAuthorizationStatus(connection, resource.getAuthorizationID(), + newExistingAuthStatus); + mappingResourcesToDeactivate.addAll(consentCoreDAO.getConsentMappingResources(connection, + resource.getAuthorizationID())); + } + + // Deactivate account mappings of old auth resource. + ArrayList mappingIdsToDeactivate = new ArrayList<>(); + mappingResourcesToDeactivate.forEach(resource -> + mappingIdsToDeactivate.add(resource.getMappingID())); + consentCoreDAO.updateConsentMappingStatus(connection, mappingIdsToDeactivate, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + + // Create a new authorization resource for the consent + AuthorizationResource newAuthorizationResource = new AuthorizationResource(); + newAuthorizationResource.setConsentID(consentID); + newAuthorizationResource.setAuthorizationType(newAuthType); + newAuthorizationResource.setAuthorizationStatus(newAuthStatus); + newAuthorizationResource.setUserID(userID); + consentCoreDAO.storeAuthorizationResource(connection, newAuthorizationResource); + + // Retrieve the detailed consent for obtaining relative account mappings + DetailedConsentResource detailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + // Update accounts if required +// ConsentCoreServiceUtil.updateAccounts(connection, consentCoreDAO, +// newAuthorizationResource.getAuthorizationID(), accountIDsMapWithPermissions, +// detailedConsentResource, true); + + // Update consent status + consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); + + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); +// ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, +// newConsentStatus, +// currentConsentStatus, ConsentCoreServiceConstants.CONSENT_REAUTHORIZE_REASON, +// detailedConsentResource.getClientID(), consentDataMap); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean storeConsentAttributes(String consentID, Map consentAttributes) + throws + ConsentMgtException { + + boolean isConsentAttributesStored; + + if (StringUtils.isBlank(consentID) || consentAttributes == null || consentAttributes.isEmpty()) { + + log.error(ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + ConsentAttributes consentAttributesObject = new ConsentAttributes(); + consentAttributesObject.setConsentID(consentID); + consentAttributesObject.setConsentAttributes(consentAttributes); + + if (log.isDebugEnabled()) { + log.debug(String.format("Storing consent attributes for the consent of ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributesObject); + DatabaseUtils.commitTransaction(connection); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + + return isConsentAttributesStored; + } + + @Override + public ConsentAttributes getConsentAttributes(String consentID, ArrayList consentAttributeKeys) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || CollectionUtils.isEmpty(consentAttributeKeys)) { + log.error(ConsentCoreServiceConstants.CONSENT_ATTRIBUTE_KEYS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTE_KEYS_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + try { + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentID); + if (retrievedConsentResource == null) { + String errorMessage = String.format("Consent ID : %s is not available in the database", + consentID.replaceAll("[\r\n]", "")); + log.error(errorMessage); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + errorMessage); + } + if (log.isDebugEnabled()) { + log.debug(String.format("Consent ID : %s is available in the database", + consentID.replaceAll("[\r\n]", ""))); + } + ConsentAttributes retrievedConsentAttributes; + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving consent attributes for given keys for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + retrievedConsentAttributes = consentCoreDAO.getConsentAttributes(connection, consentID, + consentAttributeKeys); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedConsentAttributes; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ConsentAttributes getConsentAttributes(String consentID) throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + try { + ConsentResource retrievedConsentResource = consentCoreDAO.getConsentResource(connection, consentID); + if (retrievedConsentResource == null) { + String errorMessage = String.format("Consent ID : %s is not available in the database", + consentID.replaceAll("[\r\n]", "")); + log.error(errorMessage); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, errorMessage); + } + if (log.isDebugEnabled()) { + log.debug(String.format("Consent ID : %s is available in the database", + consentID.replaceAll("[\r\n]", ""))); + } + + ConsentAttributes retrievedConsentAttributes; + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving consent attributes for consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + retrievedConsentAttributes = consentCoreDAO.getConsentAttributes(connection, consentID); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedConsentAttributes; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public Map getConsentAttributesByName(String attributeName) throws + ConsentMgtException { + + if (StringUtils.isBlank(attributeName)) { + log.error(ConsentCoreServiceConstants.CONSENT_ATTRIBUTE_NAME_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTE_NAME_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + Map retrievedAttributeValuesMap; + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving attribute values for the provided attribute key: %s", + attributeName.replaceAll("[\r\n]", ""))); + } + retrievedAttributeValuesMap = consentCoreDAO.getConsentAttributesByName(connection, attributeName); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedAttributeValuesMap; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ArrayList getConsentIdByConsentAttributeNameAndValue(String attributeName, String attributeValue) + throws + ConsentMgtException { + + if (StringUtils.isBlank(attributeName) || StringUtils.isBlank(attributeValue)) { + log.error(ConsentCoreServiceConstants.ATTRIBUTE_NAME_VALUE_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.ATTRIBUTE_NAME_VALUE_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + ArrayList retrievedConsentIdList; + if (log.isDebugEnabled()) { + log.debug(String.format("Retrieving consent Id for the provided attribute key : %s and " + + "attribute value : %s", attributeName.replaceAll("[\r\n]", ""), + attributeValue.replaceAll("[\r\n]", ""))); + } + retrievedConsentIdList = consentCoreDAO.getConsentIdByConsentAttributeNameAndValue(connection, + attributeName, attributeValue); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return retrievedConsentIdList; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ConsentAttributes updateConsentAttributes(String consentID, Map consentAttributes) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || consentAttributes == null || consentAttributes.isEmpty()) { + log.error(ConsentCoreServiceConstants.ATTRIBUTE_MAP_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.ATTRIBUTE_MAP_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + ConsentAttributes updatedAttributes; + if (log.isDebugEnabled()) { + if (log.isDebugEnabled()) { + log.debug(String.format("Updating the attributes of the consent for ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + } + consentCoreDAO.updateConsentAttributes(connection, consentID, consentAttributes); + updatedAttributes = consentCoreDAO.getConsentAttributes(connection, consentID); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return updatedAttributes; + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.ATTRIBUTE_UPDATE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.ATTRIBUTE_UPDATE_ERROR_MSG, e); + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + + } + + @Override + public boolean deleteConsentAttributes(String consentID, ArrayList attributeKeysList) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || CollectionUtils.isEmpty(attributeKeysList)) { + log.error(ConsentCoreServiceConstants.ATTRIBUTE_LIST_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.ATTRIBUTE_LIST_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + if (log.isDebugEnabled()) { + log.debug(String.format("Deleting attributes for the consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.deleteConsentAttributes(connection, consentID, attributeKeysList); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataDeletionException e) { + log.error(ConsentCoreServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG); + } + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ArrayList searchConsentStatusAuditRecords(String consentID, String status, + String actionBy, Long fromTime, + Long toTime, String statusAuditID) + throws + ConsentMgtException { + + ArrayList auditRecords; + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + log.debug("Searching audit records"); + auditRecords = consentCoreDAO.getConsentStatusAuditRecords(connection, consentID, status, actionBy, + fromTime, toTime, statusAuditID); + + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.AUDIT_RECORD_SEARCH_ERROR_MSG, e); + if (e.getMessage() != null) { + if (e.getMessage().contains(ConsentMgtDAOConstants.NO_RECORDS_FOUND_ERROR_MSG)) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, e); + } + } + + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.AUDIT_RECORD_SEARCH_ERROR_MSG, e); + } + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + return auditRecords; + } + + @Override + public ArrayList getConsentStatusAuditRecords(ArrayList consentIDs, + Integer limit, Integer offset) + throws + ConsentMgtException { + + Connection connection = DatabaseUtils.getDBConnection(); + + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + try { + //Retrieve consent status audit records. + return consentCoreDAO.getConsentStatusAuditRecordsByConsentId(connection, consentIDs, limit, offset); + + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public boolean storeConsentAmendmentHistory(String statusAuditRecordId, + ConsentHistoryResource consentHistoryResource, + DetailedConsentResource detailedCurrentConsent) + throws + ConsentMgtException { + + if (StringUtils.isBlank(statusAuditRecordId) || consentHistoryResource == null || + StringUtils.isBlank(consentHistoryResource.getReason()) || + consentHistoryResource.getTimestamp() == 0) { + log.error(ConsentCoreServiceConstants.AMEND_DETAILS_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.AMEND_DETAILS_MISSING_ERROR_MSG); + } + + String historyID = consentHistoryResource.getHistoryID(); + if (StringUtils.isBlank(historyID)) { + historyID = String.valueOf(UUID.randomUUID()); + } + long amendedTimestamp = consentHistoryResource.getTimestamp(); + String amendmentReason = consentHistoryResource.getReason(); + + Connection connection = DatabaseUtils.getDBConnection(); + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + if (detailedCurrentConsent == null) { + detailedCurrentConsent = consentCoreDAO.getDetailedConsentResource(connection, statusAuditRecordId); + } + + DetailedConsentResource detailedHistoryConsent = consentHistoryResource.getDetailedConsentResource(); + // store only the changes in basic consent data to CA history + + JSONObject changedConsentDataJson = ConsentCoreServiceUtil + .getChangedBasicConsentDataJSON(detailedCurrentConsent, detailedHistoryConsent); + if (!changedConsentDataJson.isEmpty()) { + consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + statusAuditRecordId, + ConsentCoreServiceConstants.TYPE_CONSENT_BASIC_DATA, String.valueOf(changedConsentDataJson), + amendmentReason); + } + + if (detailedCurrentConsent.getConsentAttributes() != null) { + // store only the changes in consent attributes to CA history + JSONObject changedConsentAttributesJson = ConsentCoreServiceUtil.getChangedConsentAttributesDataJSON( + detailedCurrentConsent.getConsentAttributes(), detailedHistoryConsent.getConsentAttributes()); + if (!changedConsentAttributesJson.isEmpty()) { + consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + statusAuditRecordId, ConsentCoreServiceConstants.TYPE_CONSENT_ATTRIBUTES_DATA, + String.valueOf(changedConsentAttributesJson), amendmentReason); + } + } + + + if (detailedCurrentConsent.getConsentMappingResources() != null) { + // store only the changes in consent mappings to CA history + Map changedConsentMappingsJsonDataMap = ConsentCoreServiceUtil + .getChangedConsentMappingDataJSONMap(detailedCurrentConsent.getConsentMappingResources(), + detailedHistoryConsent.getConsentMappingResources()); + for (Map.Entry changedConsentMapping : + changedConsentMappingsJsonDataMap.entrySet()) { + consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + changedConsentMapping.getKey(), ConsentCoreServiceConstants.TYPE_CONSENT_MAPPING_DATA, + String.valueOf(changedConsentMapping.getValue()), amendmentReason); + } + } + + + // store only the changes in consent Auth Resources to CA history + Map changedConsentAuthResourcesJsonDataMap = ConsentCoreServiceUtil + .getChangedConsentAuthResourcesDataJSONMap(detailedCurrentConsent.getAuthorizationResources(), + detailedHistoryConsent.getAuthorizationResources()); + for (Map.Entry changedConsentAuthResource : + changedConsentAuthResourcesJsonDataMap.entrySet()) { + consentCoreDAO.storeConsentAmendmentHistory(connection, historyID, amendedTimestamp, + changedConsentAuthResource.getKey(), + ConsentCoreServiceConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA, + String.valueOf(changedConsentAuthResource.getValue()), amendmentReason); + } + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return true; + } catch (ConsentDataInsertionException | ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public Map getConsentAmendmentHistoryData(List statusAuditRecordIds, + String consentID) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID)) { + log.error(ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ID_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + try { + //Retrieve the current detailed consent to build the detailed consent amendment history resources + DetailedConsentResource currentConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + Map consentAmendmentHistoryRetrievalResult = + consentCoreDAO.retrieveConsentAmendmentHistory(connection, + statusAuditRecordIds, consentID); + + Map consentAmendmentHistory = new LinkedHashMap<>(); + if (!consentAmendmentHistoryRetrievalResult.isEmpty()) { + consentAmendmentHistory = ConsentCoreServiceUtil.processConsentAmendmentHistoryData( + consentAmendmentHistoryRetrievalResult, currentConsentResource); + } + return consentAmendmentHistory; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + @Override + public ArrayList searchDetailedConsents(String orgID, ArrayList consentIDs, + ArrayList clientIDs, + ArrayList consentTypes, + ArrayList consentStatuses, + ArrayList userIDs, Long fromTime, + Long toTime, + Integer limit, Integer offset) throws + ConsentMgtException { + + // Input parameters except limit and offset are not validated since they are validated in the DAO method + ArrayList detailedConsentResources; + + Connection connection = DatabaseUtils.getDBConnection(); + + try { + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + + log.debug("Searching detailed consents"); + detailedConsentResources = consentCoreDAO.searchConsents(connection, orgID, consentIDs, clientIDs, + consentTypes, consentStatuses, userIDs, fromTime, toTime, limit, offset); + + } catch (ConsentDataRetrievalException | ConsentMgtException e) { + log.error(ConsentCoreServiceConstants.DETAIL_CONSENT_SEARCH_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DETAIL_CONSENT_SEARCH_ERROR_MSG, e); + } + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + return detailedConsentResources; + } + + + @Override + public DetailedConsentResource amendDetailedConsent(String consentID, String consentReceipt, + Long consentValidityTime, String authID, + Map> accountIDsMapWithPermissions, + String newConsentStatus, Map consentAttributes, + String userID, Map additionalAmendmentData) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || + (StringUtils.isBlank(consentReceipt) && (consentValidityTime == null))) { + log.error(ConsentCoreServiceConstants.CONSENT_DATA_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_DATA_MISSING_ERROR_MSG); + } + + if (StringUtils.isBlank(authID) || StringUtils.isBlank(userID) + || MapUtils.isEmpty(accountIDsMapWithPermissions) || StringUtils.isBlank(newConsentStatus) + || consentAttributes == null) { + log.error(ConsentCoreServiceConstants.DETAILED_CONSENT_DATA_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.DETAILED_CONSENT_DATA_MISSING_ERROR_MSG); + } + + Connection connection = DatabaseUtils.getDBConnection(); + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + // Retrieve the current detailed consent before the amendment for the consent amendment history persistence + DetailedConsentResource detailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + // Update receipt and validity time + if (StringUtils.isNotBlank(consentReceipt)) { + consentCoreDAO.updateConsentReceipt(connection, consentID, consentReceipt); + } + if (consentValidityTime != null) { + consentCoreDAO.updateConsentValidityTime(connection, consentID, consentValidityTime); + } + + // Update consent status and record the updated time + consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); + +// // Update accounts if required +// ConsentCoreServiceUtil.updateAccounts(connection, consentCoreDAO, authID, accountIDsMapWithPermissions, +// detailedConsentResource, false); + + // Update consent attributes + ConsentCoreServiceUtil.updateConsentAttributes(connection, consentCoreDAO, consentID, consentAttributes); + + // Update consent accordingly if additional amendment data passed +// if (!additionalAmendmentData.isEmpty()) { +// ConsentCoreServiceUtil.processAdditionalConsentAmendmentData(connection, consentCoreDAO, +// additionalAmendmentData); +// } + + // Get detailed consent status after update + DetailedConsentResource newDetailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + /* Even if the consent is amended, the status remains same as Authorized. For tracking purposes, an + audit record is created as the consent status of "amended". But still the real consent status will + remain as it is */ + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, newDetailedConsentResource); + + // Pass the previous consent to persist as consent amendment history + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, detailedConsentResource); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME, System.currentTimeMillis()); + + ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, + ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS, detailedConsentResource.getCurrentStatus(), + ConsentCoreServiceConstants.CONSENT_AMEND_REASON, detailedConsentResource.getClientID(), + consentDataMap); + + + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return newDetailedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataDeletionException e) { + log.error(ConsentCoreServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + } + + // + @Override + public DetailedConsentResource amendDetailedConsentWithBulkAuthResource(String orgId, String consentID, + String consentReceipt, + Long consentValidityTime, + ArrayList + reAuthorizationResources, + + String newConsentStatus, + Map consentAttributes, + String userID, + ArrayList + newAuthResources) + throws + ConsentMgtException { + + if (StringUtils.isBlank(consentID) || + (StringUtils.isBlank(consentReceipt) && (consentValidityTime == null))) { + log.error(ConsentCoreServiceConstants.CONSENT_DATA_MISSING_ERROR_MSG); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CONSENT_DATA_MISSING_ERROR_MSG); + } + + for (AuthorizationResource authorizationResource : reAuthorizationResources) { + if (StringUtils.isBlank(authorizationResource.getAuthorizationID()) || + StringUtils.isBlank(authorizationResource.getAuthorizationStatus()) || + StringUtils.isBlank(authorizationResource.getAuthorizationType()) || + StringUtils.isBlank(authorizationResource.getUserID()) || StringUtils.isBlank(newConsentStatus)) { + log.error(ConsentCoreServiceConstants.DETAILED_CONSENT_DATA_MISSING_ERROR_MSG); + throw new + ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.DETAILED_CONSENT_DATA_MISSING_ERROR_MSG); + } + } + + + Connection connection = DatabaseUtils.getDBConnection(); + try { + ConsentCoreDAO consentCoreDAO = ConsentStoreInitializer.getInitializedConsentCoreDAOImpl(); + // Retrieve the current detailed consent before the amendment for the consent amendment history persistence + DetailedConsentResource detailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgId, detailedConsentResource.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + + // Update receipt and validity time + if (StringUtils.isNotBlank(consentReceipt)) { + consentCoreDAO.updateConsentReceipt(connection, consentID, consentReceipt); + } + if (consentValidityTime != null) { + consentCoreDAO.updateConsentValidityTime(connection, consentID, consentValidityTime); + } + + // Update consent status and record the updated time + consentCoreDAO.updateConsentStatus(connection, consentID, newConsentStatus); + + ArrayList updatedConsentMappingResources = new ArrayList<>(); + + // iterate through the authresources and get the persomins for each account and call updateAccounts + for (AuthorizationResource authorizationResource : reAuthorizationResources) { + + + AuthorizationResource existingAuthorizationResource = + consentCoreDAO.getAuthorizationResource(connection, + authorizationResource.getAuthorizationID(), orgId); + + //validate consentId + if (!consentID.equals(existingAuthorizationResource.getConsentID())) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + String.format("Consent ID %s does not match with the consent ID %s of the " + + "authorization ID %s", consentID, + existingAuthorizationResource.getConsentID(), + authorizationResource.getAuthorizationID())); + } + + + consentCoreDAO.updateAuthorizationStatus(connection, authorizationResource.getAuthorizationID(), + authorizationResource.getAuthorizationStatus()); + + consentCoreDAO.updateAuthorizationUser(connection, authorizationResource.getAuthorizationID(), + authorizationResource.getUserID()); + + Map> accountIDsMapWithPermissions = new HashMap<>(); + + ArrayList exitingConsentMappingResources = consentCoreDAO + .getConsentMappingResources(connection, authorizationResource.getAuthorizationID()); + ArrayList newConsentResourceIds = new ArrayList<>(); + for (ConsentMappingResource consentMappingResource : + authorizationResource.getConsentMappingResource()) { + consentMappingResource.setMappingStatus("active"); + consentMappingResource.setAuthorizationID(authorizationResource.getAuthorizationID()); + // validate the mappingID + if (consentMappingResource.getMappingID() != null) { + // check whether the mappingID is already available in the database + if (exitingConsentMappingResources.stream().noneMatch( + consentMappingResource1 -> consentMappingResource1.getMappingID() + .equals(consentMappingResource.getMappingID()))) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + String.format("Mapping ID %s does not match with the mapping IDs of the " + + "authorization ID %s", consentMappingResource.getMappingID(), + consentMappingResource.getMappingID())); + + } + updatedConsentMappingResources.add(consentMappingResource); + newConsentResourceIds.add(consentMappingResource.getMappingID()); + + + } else { + updatedConsentMappingResources.add(consentCoreDAO. + storeConsentMappingResource(connection, + consentMappingResource)); + newConsentResourceIds.add(consentMappingResource.getMappingID()); + + } + + } + + // deactivating removed resources + ArrayList inactiveMappings = new ArrayList<>(); + for (ConsentMappingResource consentMappingResource : exitingConsentMappingResources) { + if (!newConsentResourceIds.contains(consentMappingResource.getMappingID())) { + consentMappingResource.setMappingStatus("inactive"); + inactiveMappings.add(consentMappingResource.getMappingID()); + updatedConsentMappingResources.add(consentMappingResource); + } + } + if (!inactiveMappings.isEmpty()) { + consentCoreDAO.updateConsentMappingStatus(connection, inactiveMappings, "inactive"); + + } + + } + + // Update consent attributes + if (!consentAttributes.isEmpty()) { + ConsentCoreServiceUtil.updateConsentAttributes(connection, consentCoreDAO, consentID, + consentAttributes); + + } + + // Update consent accordingly if additional amendment data passed + if (!newAuthResources.isEmpty()) { + ConsentCoreServiceUtil.processAdditionalConsentAmendmentData(connection, consentCoreDAO, + newAuthResources); + } + + // Get detailed consent status after update + DetailedConsentResource newDetailedConsentResource = + consentCoreDAO.getDetailedConsentResource(connection, consentID); + + newDetailedConsentResource.setConsentMappingResources(updatedConsentMappingResources); + + + + + /* Even if the consent is amended, the status remains same as Authorized. For tracking purposes, an + audit record is created as the consent status of "amended". But still the real consent status will + remain as it is */ + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, newDetailedConsentResource); + + // Pass the previous consent to persist as consent amendment history + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, detailedConsentResource); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_TIME, System.currentTimeMillis()); + + //TODO : what is this userId? what value to pass? + ConsentCoreServiceUtil.postStateChange(connection, consentCoreDAO, consentID, userID, + ConsentCoreServiceConstants.CONSENT_AMENDED_STATUS, detailedConsentResource.getCurrentStatus(), + ConsentCoreServiceConstants.CONSENT_AMEND_REASON, detailedConsentResource.getClientID(), + consentDataMap); + + // Commit transactions + DatabaseUtils.commitTransaction(connection); + log.debug(ConsentCoreServiceConstants.TRANSACTION_COMMITTED_LOG_MSG); + return newDetailedConsentResource; + } catch (ConsentDataRetrievalException e) { + log.error(ConsentCoreServiceConstants.DATA_RETRIEVE_ERROR_MSG, e); + throw new ConsentMgtException(Response.Status.NOT_FOUND, + e.getMessage(), + e); + } catch (ConsentDataInsertionException e) { + log.error(ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_INSERTION_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataUpdationException e) { + log.error(ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.DATA_UPDATE_ROLLBACK_ERROR_MSG, e); + } catch (ConsentDataDeletionException e) { + log.error(ConsentCoreServiceConstants.DATA_DELETE_ROLLBACK_ERROR_MSG, e); + DatabaseUtils.rollbackTransaction(connection); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + ConsentCoreServiceConstants.CONSENT_ATTRIBUTES_DELETE_ERROR_MSG); + } catch (ConsentMgtException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } finally { + log.debug(ConsentCoreServiceConstants.DATABASE_CONNECTION_CLOSE_LOG_MSG); + DatabaseUtils.closeConnection(connection); + } + + + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceUtil.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceUtil.java new file mode 100644 index 000000000..7dd0ddeaa --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceUtil.java @@ -0,0 +1,927 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.util; + +import com.google.gson.Gson; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.minidev.json.JSONObject; +import net.minidev.json.parser.JSONParser; +import net.minidev.json.parser.ParseException; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.constants.ConsentMgtDAOConstants; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; +import org.wso2.financial.services.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.Response; + + +/** + * Consent Core Service Util. + */ +@SuppressFBWarnings("CRLF_INJECTION_LOGS") +public class ConsentCoreServiceUtil { + + private static final Log log = LogFactory.getLog(ConsentCoreServiceUtil.class); + + + /** + * Create an authorizable consent with audit record. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param consentResource Consent resource + * @param authorizationResources auth resources + * @param isImplicitAuthorization Is implicit authorization + * @return DetailedConsentResource + * @throws ConsentDataInsertionException Consent data insertion exception + * @throws ConsentMgtException Consent management exception + */ + public static DetailedConsentResource createAuthorizableConsentWithAuditRecordWithBulkAuthResources( + Connection connection, + ConsentCoreDAO consentCoreDAO, + ConsentResource consentResource, + List authorizationResources, + boolean isImplicitAuthorization) + throws + ConsentDataInsertionException, + ConsentMgtException, + ConsentDataRetrievalException { + + boolean isConsentAttributesStored = false; + AuthorizationResource storedAuthorizationResource = null; + + // Create consent + if (log.isDebugEnabled()) { + log.debug(("Creating the consent for ID:" + consentResource.getConsentID()) + .replaceAll("[\r\n]", "")); + } + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + String consentID = storedConsentResource.getConsentID(); + + // Store consent attributes if available + if (MapUtils.isNotEmpty(consentResource.getConsentAttributes())) { + ConsentAttributes consentAttributes = new ConsentAttributes(consentID, + consentResource.getConsentAttributes()); + + if (log.isDebugEnabled()) { + log.debug(String.format("Storing consent attributes for the consent of ID: %s", consentAttributes + .getConsentID().replaceAll("[\r\n]", ""))); + } + isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributes); + } + + + //TODO: authorizationResources.get(0).getUserID() + /// authorizationResources is null and get the userId + + String userId = authorizationResources != null ? + !authorizationResources.isEmpty() ? authorizationResources.get(0).getUserID() : null : null; + + + ArrayList storedAuthorizationResources = new ArrayList<>(); + ArrayList storedConsentMappingResources = new ArrayList<>(); + + // Create an authorization resource if isImplicitAuth parameter is true + if (isImplicitAuthorization) { + /* Setting userID as null since at this point, there is no userID in this flow. User ID can be + updated in authorization flow */ + + // loop through authorizationResources + assert authorizationResources != null; + assert !authorizationResources.isEmpty(); + + for (AuthorizationResource authorizationResource : authorizationResources) { + authorizationResource.setUpdatedTime(System.currentTimeMillis()); + authorizationResource.setConsentID(consentID); + + + if (log.isDebugEnabled()) { + log.debug(("Storing authorization resource for consent of ID: " + authorizationResource + .getConsentID()).replaceAll("[\r\n]", "")); + } + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, + authorizationResource); + for (ConsentMappingResource consentMappingResource : + authorizationResource.getConsentMappingResource()) { + consentMappingResource.setAuthorizationID(storedAuthorizationResource.getAuthorizationID()); + ConsentMappingResource storedConsentMappingResource = + consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource); + storedConsentMappingResources.add(storedConsentMappingResource); + } + storedAuthorizationResource.setConsentMappingResource(storedConsentMappingResources); + + + storedAuthorizationResources.add(storedAuthorizationResource); + } + } + + DetailedConsentResource detailedConsentResource = + new DetailedConsentResource(storedConsentResource.getOrgID(), consentID, + storedConsentResource.getClientID(), storedConsentResource.getReceipt(), + storedConsentResource.getConsentType(), storedConsentResource.getCurrentStatus(), + storedConsentResource.getConsentFrequency(), storedConsentResource.getValidityPeriod(), + storedConsentResource.getCreatedTime(), storedConsentResource.getUpdatedTime(), + storedConsentResource.isRecurringIndicator(), consentResource.getConsentAttributes(), + new ArrayList<>(), + new ArrayList<>()); + + + if (isConsentAttributesStored) { + detailedConsentResource.setConsentAttributes(consentResource.getConsentAttributes()); + } + if (isImplicitAuthorization) { + detailedConsentResource.setAuthorizationResources(storedAuthorizationResources); + detailedConsentResource.setConsentMappingResources(storedConsentMappingResources); + } + /* Create audit record, setting previous consent status as null since this is the first time the + consent is created and execute state change listener */ + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); + DetailedConsentResource oldDetailedConsent = new DetailedConsentResource(); + oldDetailedConsent.setConsentAttributes(new HashMap<>()); + oldDetailedConsent.setAuthorizationResources(new ArrayList<>()); + oldDetailedConsent.setConsentMappingResources(new ArrayList<>()); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, oldDetailedConsent); + + postStateChange(connection, consentCoreDAO, consentID, userId, + consentResource.getCurrentStatus(), + null, ConsentCoreServiceConstants.CREATE_CONSENT_REASON, + consentResource.getClientID(), consentDataMap); + return detailedConsentResource; + } + + /** + * Create an authorizable consent with audit record. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param consentResource Consent resource + * @param userID User ID + * @param authStatus Auth Status + * @param authType Auth Type + * @param isImplicitAuthorization Is implicit authorization + * @return DetailedConsentResource + * @throws ConsentDataInsertionException Consent data insertion exception + * @throws ConsentMgtException Consent management exception + */ + public static DetailedConsentResource createAuthorizableConsentWithAuditRecord(Connection connection, + ConsentCoreDAO consentCoreDAO, + ConsentResource consentResource, + String userID, String authStatus, + String authType, + boolean isImplicitAuthorization) + throws + ConsentDataInsertionException, + ConsentMgtException, + ConsentDataRetrievalException { + + boolean isConsentAttributesStored = false; + AuthorizationResource storedAuthorizationResource = null; + + // Create consent + if (log.isDebugEnabled()) { + log.debug(("Creating the consent for ID:" + consentResource.getConsentID()) + .replaceAll("[\r\n]", "")); + } + ConsentResource storedConsentResource = consentCoreDAO.storeConsentResource(connection, consentResource); + String consentID = storedConsentResource.getConsentID(); + + // Store consent attributes if available + if (MapUtils.isNotEmpty(consentResource.getConsentAttributes())) { + ConsentAttributes consentAttributes = new ConsentAttributes(consentID, + consentResource.getConsentAttributes()); + + if (log.isDebugEnabled()) { + log.debug(String.format("Storing consent attributes for the consent of ID: %s", consentAttributes + .getConsentID().replaceAll("[\r\n]", ""))); + } + isConsentAttributesStored = consentCoreDAO.storeConsentAttributes(connection, consentAttributes); + } + + + // Create an authorization resource if isImplicitAuth parameter is true + if (isImplicitAuthorization) { + /* Setting userID as null since at this point, there is no userID in this flow. User ID can be + updated in authorization flow */ + String userIdValue = StringUtils.isNotBlank(userID) ? userID : null; + + AuthorizationResource authorizationResource = new AuthorizationResource(consentID, userIdValue, authStatus, + authType, System.currentTimeMillis()); + + if (log.isDebugEnabled()) { + log.debug(("Storing authorization resource for consent of ID: " + authorizationResource + .getConsentID()).replaceAll("[\r\n]", "")); + } + + storedAuthorizationResource = consentCoreDAO.storeAuthorizationResource(connection, authorizationResource); + } + + DetailedConsentResource detailedConsentResource = + new DetailedConsentResource(storedConsentResource.getOrgID(), consentID, + storedConsentResource.getClientID(), storedConsentResource.getReceipt(), + storedConsentResource.getConsentType(), storedConsentResource.getCurrentStatus(), + storedConsentResource.getConsentFrequency(), storedConsentResource.getValidityPeriod(), + storedConsentResource.getCreatedTime(), storedConsentResource.getUpdatedTime(), + storedConsentResource.isRecurringIndicator(), new HashMap<>(), new ArrayList<>(), + new ArrayList<>()); + + if (isConsentAttributesStored) { + detailedConsentResource.setConsentAttributes(consentResource.getConsentAttributes()); + } + if (isImplicitAuthorization) { + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(storedAuthorizationResource); + detailedConsentResource.setAuthorizationResources(authorizationResources); + } + + /* Create audit record, setting previous consent status as null since this is the first time the + consent is created and execute state change listener */ + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, detailedConsentResource); + DetailedConsentResource oldDetailedConsent = new DetailedConsentResource(); + oldDetailedConsent.setConsentAttributes(new HashMap<>()); + oldDetailedConsent.setAuthorizationResources(new ArrayList<>()); + oldDetailedConsent.setConsentMappingResources(new ArrayList<>()); + consentDataMap.put(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE, oldDetailedConsent); + + postStateChange(connection, consentCoreDAO, consentID, userID, consentResource.getCurrentStatus(), + null, ConsentCoreServiceConstants.CREATE_CONSENT_REASON, + consentResource.getClientID(), consentDataMap); + return detailedConsentResource; + } + + /** + * Update existing consent statuses and revoke their account mappings. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param consentResource Consent resource + * @param userID User ID + * @param applicableExistingConsentsStatus Applicable existing consents status + * @param newExistingConsentStatus New existing consent status + * @throws ConsentDataRetrievalException If an error occurs when retrieving existing consents + * @throws ConsentDataUpdationException If an error occurs when updating existing consents + * @throws ConsentDataInsertionException If an error occurs when inserting data + * @throws ConsentMgtException Consent management exception + */ + public static void updateExistingConsentStatusesAndRevokeAccountMappings(Connection connection, + ConsentCoreDAO consentCoreDAO, + ConsentResource consentResource, + String userID, + String applicableExistingConsentsStatus, + String newExistingConsentStatus) + throws + ConsentDataRetrievalException, + ConsentDataUpdationException, + ConsentDataInsertionException, + ConsentMgtException { + + ArrayList accountMappingIDsList = new ArrayList<>(); + + ArrayList clientIDsList = constructArrayList(consentResource.getClientID()); + ArrayList userIDsList = constructArrayList(userID); + ArrayList consentTypesList = constructArrayList(consentResource.getConsentType()); + ArrayList consentStatusesList = constructArrayList(applicableExistingConsentsStatus); + + // Get existing applicable consents + log.debug("Retrieving existing authorized consents"); + ArrayList retrievedExistingAuthorizedConsentsList = + consentCoreDAO.searchConsents(connection, null, null, clientIDsList, consentTypesList, + consentStatusesList, userIDsList, null, null, null, + null); + + for (DetailedConsentResource resource : retrievedExistingAuthorizedConsentsList) { + + String previousConsentStatus = resource.getCurrentStatus(); + + // Update existing consents as necessary + if (log.isDebugEnabled()) { + log.debug(("Updating existing consent statuses with the new status provided for consent ID: " + + resource.getConsentID()).replaceAll("[\r\n]", "")); + } + consentCoreDAO.updateConsentStatus(connection, resource.getConsentID(), newExistingConsentStatus); + + // Create audit record for each consent update + if (log.isDebugEnabled()) { + log.debug(("Creating audit record for the consent update of consent ID: " + + resource.getConsentID()).replaceAll("[\r\n]", "")); + } + // Create an audit record execute state change listener + HashMap consentDataMap = new HashMap<>(); + consentDataMap.put(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE, resource); + postStateChange(connection, consentCoreDAO, resource.getConsentID(), userID, + newExistingConsentStatus, previousConsentStatus, + ConsentCoreServiceConstants.CREATE_EXCLUSIVE_AUTH_CONSENT_REASON, resource.getClientID(), + consentDataMap); + + // Extract account mapping IDs for retrieved applicable consents + if (log.isDebugEnabled()) { + log.debug(("Extracting account mapping IDs from consent ID: " + + resource.getConsentID()).replaceAll("[\r\n]", "")); + } + resource.getConsentMappingResources().forEach(mappingResource -> + accountMappingIDsList.add(mappingResource.getMappingID())); + } + + // Update account mappings as inactive + log.debug("Deactivating account mappings"); + consentCoreDAO.updateConsentMappingStatus(connection, accountMappingIDsList, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + } + + /** + * Method to create an audit record in post consent state change. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param consentID Consent ID + * @param userID User ID + * @param newConsentStatus New consent status + * @param previousConsentStatus Previous consent status + * @param reason Reason for the status change + * @param clientId Client ID + * @param consentDataMap Consent data map + * @throws ConsentDataInsertionException If an error occurs when storing the audit record + * @throws ConsentMgtException Consent management exception + */ + public static void postStateChange(Connection connection, ConsentCoreDAO consentCoreDAO, String consentID, + String userID, String newConsentStatus, String previousConsentStatus, + String reason, String clientId, Map consentDataMap) + throws + ConsentDataInsertionException, + ConsentMgtException, + ConsentDataRetrievalException { + + ConsentStatusAuditRecord consentStatusAuditRecord = createAuditRecord(connection, consentCoreDAO, consentID, + userID, + newConsentStatus, + previousConsentStatus, + reason); + + DetailedConsentResource detailedCurrentConsent = (DetailedConsentResource) + consentDataMap.get(ConsentCoreServiceConstants.DETAILED_CONSENT_RESOURCE); + DetailedConsentResource detailedHistoryConsent = (DetailedConsentResource) + consentDataMap.get(ConsentCoreServiceConstants.CONSENT_AMENDMENT_HISTORY_RESOURCE); + + if (detailedCurrentConsent == null) { + // get the current consent details + detailedCurrentConsent = consentCoreDAO.getDetailedConsentResource(connection, consentID); + } + + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setDetailedConsentResource(detailedHistoryConsent); + consentHistoryResource.setReason(reason); + consentHistoryResource.setTimestamp(System.currentTimeMillis()); + + ConsentCoreServiceImpl consentCoreService = new ConsentCoreServiceImpl(); + boolean result = consentCoreService.storeConsentAmendmentHistory( + consentStatusAuditRecord.getStatusAuditID(), + consentHistoryResource, + detailedCurrentConsent); + + if (result) { + if (log.isDebugEnabled()) { + log.debug(String.format("Consent Amendment History of consentID: %s persisted successfully.", + consentID)); + } + } else { + log.error(String.format("Failed to persist Consent Amendment History of consentID : %s. ", + consentID)); + } + + + } + + /** + * Create an audit record for the consent status change. + * + * @param connection database connection + * @param consentCoreDAO consent core DAO + * @param consentID consent ID + * @param userID user ID + * @param newConsentStatus new consent status + * @param previousConsentStatus previous consent status + * @param reason reason for the status change + * @return + * @throws ConsentDataInsertionException thrown if an error occurs when storing the audit record + */ + public static ConsentStatusAuditRecord createAuditRecord(Connection connection, ConsentCoreDAO consentCoreDAO, + String consentID, + String userID, String newConsentStatus, + String previousConsentStatus, + String reason) throws + ConsentDataInsertionException { + + // Create an audit record + String actionBy = StringUtils.isNotEmpty(userID) ? userID : null; + ConsentStatusAuditRecord consentStatusAuditRecord = new ConsentStatusAuditRecord(consentID, newConsentStatus, + 0, reason, actionBy, previousConsentStatus); + + consentStatusAuditRecord.setStatusAuditID(String.valueOf(UUID.randomUUID())); + if (log.isDebugEnabled()) { + log.debug(("Storing audit record for consent of ID: " + + consentStatusAuditRecord.getConsentID()).replaceAll("[\r\n]", "")); + } + return consentCoreDAO.storeConsentStatusAuditRecord(connection, consentStatusAuditRecord); + } + + + /** + * Construct an ArrayList with a single field. + * + * @param field Field to be added to the ArrayList + * @return ArrayList with a single field + */ + public static ArrayList constructArrayList(String field) { + return new ArrayList() { + { + add(field); + } + }; + } + + /** + * Method to update the accounts of a consent. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param authID Authorization ID + * @param accountIDsMapWithPermissions Account IDs map with permissions + * @param detailedConsentResource Detailed consent resource + * @param isNewAuthResource Is new authorization resource + * @throws ConsentDataInsertionException If an error occurs when inserting data + * @throws ConsentDataUpdationException If an error occurs when updating data + */ + public static void updateAccounts(Connection connection, ConsentCoreDAO consentCoreDAO, String authID, + Map> accountIDsMapWithPermissions, + DetailedConsentResource detailedConsentResource, boolean isNewAuthResource) + throws + ConsentDataInsertionException, + ConsentDataUpdationException { + + // Get existing consent account mappings + log.debug("Retrieve existing active account mappings"); + ArrayList existingAccountMappings = + detailedConsentResource.getConsentMappingResources(); + + // Determine unique account IDs + HashSet existingAccountIDs = new HashSet<>(); + existingAccountMappings.forEach(mapping -> existingAccountIDs.add( + mapping.getAccountID())); + + ArrayList existingAccountIDsList = new ArrayList<>(existingAccountIDs); + + ArrayList reAuthorizedAccounts = new ArrayList<>(); + accountIDsMapWithPermissions.forEach((accountID, permissions) -> + reAuthorizedAccounts.add(accountID)); + + // Determine whether the account should be removed or added + ArrayList accountsToRevoke = new ArrayList<>(existingAccountIDsList); + accountsToRevoke.removeAll(reAuthorizedAccounts); + + ArrayList accountsToAdd = new ArrayList<>(reAuthorizedAccounts); + + if (isNewAuthResource) { + ArrayList commonAccountsFromReAuth = new ArrayList<>(existingAccountIDs); + commonAccountsFromReAuth.retainAll(accountsToAdd); + accountsToAdd.removeAll(existingAccountIDs); + accountsToAdd.addAll(commonAccountsFromReAuth); + } else { + accountsToAdd.removeAll(existingAccountIDs); + } + + if (!accountsToAdd.isEmpty()) { + // Store accounts as consent account mappings + log.debug("Add extra accounts as account mappings"); + for (String accountID : accountsToAdd) { + ArrayList permissions = accountIDsMapWithPermissions.get(accountID); + for (String permission : permissions) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource( + authID, accountID, permission, ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); + ConsentMappingResource storedConsentMappingResource = + consentCoreDAO.storeConsentMappingResource(connection, + consentMappingResource); + existingAccountMappings.add(storedConsentMappingResource); + } + } + } + if (!accountsToRevoke.isEmpty()) { + // Update mapping statuses of revoking accounts to inactive + log.debug("Deactivate unwanted account mappings"); + ArrayList mappingIDsToUpdate = new ArrayList<>(); + for (String accountID : accountsToRevoke) { + existingAccountMappings.stream() + .filter(resource -> accountID.equals(resource.getAccountID())) + .forEach(resource -> mappingIDsToUpdate.add(resource.getMappingID())); + } + consentCoreDAO.updateConsentMappingStatus(connection, mappingIDsToUpdate, + ConsentCoreServiceConstants.INACTIVE_MAPPING_STATUS); + } + } + + /** + * Method to update the consent attributes. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param consentID Consent ID + * @param consentAttributes Consent attributes + * @throws ConsentDataInsertionException If an error occurs when inserting data + * @throws ConsentDataDeletionException If an error occurs when deleting data + */ + public static void updateConsentAttributes(Connection connection, ConsentCoreDAO consentCoreDAO, + String consentID, Map consentAttributes) + throws + ConsentDataInsertionException, + ConsentDataDeletionException { + + // delete existing consent attributes + if (log.isDebugEnabled()) { + log.debug(String.format("Deleting attributes for the consent ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.deleteConsentAttributes(connection, consentID, new ArrayList<>(consentAttributes.keySet())); + + // store new set of consent attributes + ConsentAttributes consentAttributesObject = new ConsentAttributes(consentID, consentAttributes); + if (log.isDebugEnabled()) { + log.debug(String.format("Storing consent attributes for the consent of ID: %s", + consentID.replaceAll("[\r\n]", ""))); + } + consentCoreDAO.storeConsentAttributes(connection, consentAttributesObject); + } + + /** + * Method to get the changed values from consent amendment compared to the original consent. + * + * @param newConsentResource New Consent Resource after the amendment + * @param oldConsentResource Existing Consent Resource + * @return JSON object with the changed values + */ + public static JSONObject getChangedBasicConsentDataJSON(DetailedConsentResource newConsentResource, + DetailedConsentResource oldConsentResource) { + + JSONObject changedConsentDataJson = new JSONObject(); + if (!newConsentResource.getReceipt().equals(oldConsentResource.getReceipt())) { + changedConsentDataJson.put(ConsentCoreServiceConstants.RECEIPT, oldConsentResource.getReceipt()); + } + if (newConsentResource.getValidityPeriod() != oldConsentResource.getValidityPeriod()) { + changedConsentDataJson.put(ConsentCoreServiceConstants.VALIDITY_TIME, + String.valueOf(oldConsentResource.getValidityPeriod())); + } + if (newConsentResource.getUpdatedTime() != oldConsentResource.getUpdatedTime()) { + changedConsentDataJson.put(ConsentCoreServiceConstants.UPDATED_TIME, + String.valueOf(oldConsentResource.getUpdatedTime())); + } + if (!newConsentResource.getCurrentStatus().equals(oldConsentResource.getCurrentStatus())) { + changedConsentDataJson.put(ConsentCoreServiceConstants.CURRENT_STATUS, + String.valueOf(oldConsentResource.getCurrentStatus())); + } + return changedConsentDataJson; + } + + /** + * Method to get the changed consent attribute values from consent amendment compared to the original consent. + * + * @param newConsentAttributes New consent attributes after the amendment + * @param oldConsentAttributes Existing consent attributes + * @return JSON object with the changed consent attributes + */ + public static JSONObject getChangedConsentAttributesDataJSON(Map newConsentAttributes, + Map oldConsentAttributes) { + + JSONObject changedConsentAttributesJson = new JSONObject(); + + oldConsentAttributes.entrySet().stream() + .filter(oldConsentAttribute -> !newConsentAttributes.containsKey( + oldConsentAttribute.getKey())) + .forEach(oldConsentAttribute -> { + //store any removed consent attribute in current consent to the changedConsentAttributesJson of + //the immediate past consent amendment history with a null value + changedConsentAttributesJson.put(oldConsentAttribute.getKey(), oldConsentAttribute.getValue()); + }); + + newConsentAttributes.entrySet().stream().filter(newConsentAttribute -> !oldConsentAttributes + .containsKey(newConsentAttribute.getKey())).forEach(newConsentAttribute -> { + //store any new consent attribute in current consent to the changedConsentAttributesJson of + //the immediate past consent amendment history with a null value + changedConsentAttributesJson.put(newConsentAttribute.getKey(), newConsentAttribute.getValue()); + }); + return changedConsentAttributesJson; + } + + /** + * Method to get the changed consent mappings from consent amendment compared to the original consent. + * + * @param newConsentMappings New consent mappings after the amendment + * @param oldConsentMappings Existing consent mappings + * @return JSON object with the changed consent mappings + */ + public static Map getChangedConsentMappingDataJSONMap(ArrayList + newConsentMappings, + ArrayList + oldConsentMappings) { + + Map changedConsentMappingsJsonDataMap = new HashMap<>(); + ArrayList existingConsentMappingIds = new ArrayList<>(); + for (ConsentMappingResource newMapping : newConsentMappings) { + JSONObject changedConsentMappingJson = new JSONObject(); + for (ConsentMappingResource oldMapping : oldConsentMappings) { + if (newMapping.getMappingID().equals(oldMapping.getMappingID())) { + existingConsentMappingIds.add(newMapping.getMappingID()); + if (!newMapping.getMappingStatus().equals(oldMapping.getMappingStatus())) { + //store only the mapping-ids with a changed Mapping Status to the consent amendment history + changedConsentMappingJson.put(ConsentCoreServiceConstants.MAPPING_STATUS, + oldMapping.getMappingStatus()); + } + break; + } + } + if (!changedConsentMappingJson.isEmpty()) { + changedConsentMappingsJsonDataMap.put(newMapping.getMappingID(), changedConsentMappingJson); + } + // store any new mapping-ids in current consent to the immediate past consent amendment history with + // 'null' value + if (!existingConsentMappingIds.contains(newMapping.getMappingID())) { + changedConsentMappingsJsonDataMap.put(newMapping.getMappingID(), null); + } + } + return changedConsentMappingsJsonDataMap; + } + + /** + * Method to get the changed consent auth resources from consent amendment compared to the original consent. + * + * @param newConsentAuthResources New consent auth resources after the amendment + * @param oldConsentAuthResources Existing auth resources + * @return JSON object with the changed consent mappings + */ + public static Map getChangedConsentAuthResourcesDataJSONMap(ArrayList + newConsentAuthResources, + ArrayList + oldConsentAuthResources) { + + Map changedConsentAuthResourcesJsonDataMap = new HashMap<>(); + + ArrayList existingConsentAuthResourceIds = new ArrayList<>(); + for (AuthorizationResource newAuthResource : newConsentAuthResources) { + oldConsentAuthResources.stream() + .filter(oldAuthResource -> newAuthResource.getAuthorizationID(). + equals(oldAuthResource.getAuthorizationID())) + .forEach(oldAuthResource -> + existingConsentAuthResourceIds.add(newAuthResource.getAuthorizationID())); + + // store any new authorization-ids in current consent (an Auth Resource not available in previous consent, + // but newly added in current consent) to the immediate past consent amendment history with 'null' value + if (!existingConsentAuthResourceIds.contains(newAuthResource.getAuthorizationID())) { + changedConsentAuthResourcesJsonDataMap.put(newAuthResource.getAuthorizationID(), null); + } + } + return changedConsentAuthResourcesJsonDataMap; + } + + /** + * Method to get the consent mapping id and consent auth resource id as a list for consent history retrieval. + * + * @param detailedConsentResource Changed attribute JSON string + * @return List of record IDs + */ + public static List getRecordIdListForConsentHistoryRetrieval( + DetailedConsentResource detailedConsentResource) { + + List recordIdsList = new ArrayList<>(); + recordIdsList.add(detailedConsentResource.getConsentID()); + + for (ConsentMappingResource mappingResource : detailedConsentResource.getConsentMappingResources()) { + recordIdsList.add(mappingResource.getMappingID()); + } + for (AuthorizationResource authResource : detailedConsentResource.getAuthorizationResources()) { + recordIdsList.add(authResource.getAuthorizationID()); + } + return recordIdsList; + } + + /** + * Method to process the consent amendment history data. + * + * @param consentAmendmentHistoryRetrievalResult Consent amendment history retrieval result + * @param currentConsentResource Current consent resource + * @return Consent amendment history data map + * @throws ConsentMgtException Consent management exception + */ + public static Map processConsentAmendmentHistoryData( + Map consentAmendmentHistoryRetrievalResult, + DetailedConsentResource currentConsentResource) throws + ConsentMgtException { + + Gson gson = new Gson(); + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + + for (Map.Entry consentHistoryDataEntry : + consentAmendmentHistoryRetrievalResult.entrySet()) { + String historyId = consentHistoryDataEntry.getKey(); + ConsentHistoryResource consentHistoryResource = consentHistoryDataEntry.getValue(); + + for (Map.Entry consentHistoryDataTypeEntry : + consentHistoryResource.getChangedAttributesJsonDataMap().entrySet()) { + String consentDataType = consentHistoryDataTypeEntry.getKey(); + Object changedAttributes = consentHistoryDataTypeEntry.getValue(); + + if (ConsentCoreServiceConstants.TYPE_CONSENT_BASIC_DATA.equals(consentDataType)) { + JSONObject changedValuesJSON = parseChangedAttributeJsonString(changedAttributes.toString()); + if (changedValuesJSON.containsKey(ConsentCoreServiceConstants.RECEIPT)) { + currentConsentResource.setReceipt( + (String) changedValuesJSON.get(ConsentCoreServiceConstants.RECEIPT)); + } + if (changedValuesJSON.containsKey(ConsentCoreServiceConstants.VALIDITY_TIME)) { + currentConsentResource.setValidityPeriod(Long.parseLong((String) + changedValuesJSON.get(ConsentCoreServiceConstants.VALIDITY_TIME))); + } + if (changedValuesJSON.containsKey(ConsentCoreServiceConstants.UPDATED_TIME)) { + currentConsentResource.setUpdatedTime(Long.parseLong((String) + changedValuesJSON.get(ConsentCoreServiceConstants.UPDATED_TIME))); + } + if (changedValuesJSON.containsKey(ConsentCoreServiceConstants.CURRENT_STATUS)) { + currentConsentResource.setCurrentStatus((String) + changedValuesJSON.get(ConsentCoreServiceConstants.CURRENT_STATUS)); + } + + } else if (ConsentCoreServiceConstants.TYPE_CONSENT_ATTRIBUTES_DATA.equals(consentDataType)) { + JSONObject changedValuesJSON = parseChangedAttributeJsonString(changedAttributes.toString()); + for (Map.Entry attribute : changedValuesJSON.entrySet()) { + Object attributeValue = attribute.getValue(); + if (attributeValue == null) { + //Ignore the consent attribute from the consent history if it's value is stored as null + currentConsentResource.getConsentAttributes().remove(attribute.getKey()); + } else { + currentConsentResource.getConsentAttributes().put(attribute.getKey(), + attributeValue.toString()); + } + } + + } else if (ConsentCoreServiceConstants.TYPE_CONSENT_MAPPING_DATA.equals(consentDataType)) { + Map changedConsentMappingsDataMap = (Map) changedAttributes; + ArrayList consentMappings = + currentConsentResource.getConsentMappingResources(); + ArrayList consentMappingsHistory = new ArrayList<>(); + for (ConsentMappingResource mapping : consentMappings) { + String mappingID = mapping.getMappingID(); + if (changedConsentMappingsDataMap.containsKey(mappingID)) { + JSONObject changedValuesJSON = parseChangedAttributeJsonString( + changedConsentMappingsDataMap.get(mappingID).toString()); + if (changedValuesJSON.isEmpty()) { + //Skip setting the mapping to consent history if the value is null + continue; + } + //set the value available in the history as the mapping status + mapping.setMappingStatus( + changedValuesJSON.get(ConsentCoreServiceConstants.MAPPING_STATUS).toString()); + } + consentMappingsHistory.add(gson.fromJson(gson.toJson(mapping), ConsentMappingResource.class)); + } + currentConsentResource.setConsentMappingResources(consentMappingsHistory); + + } else if (ConsentCoreServiceConstants.TYPE_CONSENT_AUTH_RESOURCE_DATA.equals(consentDataType)) { + Map changedConsentAuthResourceDataMap = (Map) changedAttributes; + ArrayList consentAuthResources = currentConsentResource + .getAuthorizationResources(); + ArrayList consentAuthResourceHistory = new ArrayList<>(); + for (AuthorizationResource authResource : consentAuthResources) { + String authID = authResource.getAuthorizationID(); + if (changedConsentAuthResourceDataMap.containsKey(authID)) { + JSONObject changedValuesJSON = parseChangedAttributeJsonString( + changedConsentAuthResourceDataMap.get(authID).toString()); + if (changedValuesJSON.isEmpty()) { + //Skip setting the auth resource to consent history if the value is null + continue; + } + } + consentAuthResourceHistory.add(gson.fromJson(gson.toJson(authResource), + AuthorizationResource.class)); + } + currentConsentResource.setAuthorizationResources(consentAuthResourceHistory); + } + } + consentHistoryResource.setDetailedConsentResource(currentConsentResource.clone()); + consentAmendmentHistoryDataMap.put(historyId, consentHistoryResource); + } + return consentAmendmentHistoryDataMap; + } + + + /** + * Method to parse the changed attribute JSON string to a JSON Object. + * + * @param changedAttributes Changed attribute JSON string + * @return JSON object with the changed attributes + * @throws ConsentMgtException If there is an error while parsing the JSON String + */ + static JSONObject parseChangedAttributeJsonString(String changedAttributes) + throws + ConsentMgtException { + + Object changedValues; + try { + changedValues = new JSONParser(JSONParser.MODE_PERMISSIVE).parse(changedAttributes); + } catch (ParseException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + "Changed Values is not a valid JSON object", e); + } + if (changedValues == null) { + return new JSONObject(); + } + return (JSONObject) changedValues; + + } + + /** + * Method to process the additional consent amendment data. + * + * @param connection Database connection + * @param consentCoreDAO Consent core DAO + * @param newAuthorizationResources new Authorization resources + * @throws ConsentMgtException If an error occurs when processing the additional amendment data + * @throws ConsentDataInsertionException If an error occurs when inserting data + */ + public static void processAdditionalConsentAmendmentData(Connection connection, ConsentCoreDAO consentCoreDAO, + ArrayList newAuthorizationResources) + throws + ConsentMgtException, + ConsentDataInsertionException { + for (AuthorizationResource authResource : newAuthorizationResources) { + + + if (StringUtils.isBlank(authResource.getConsentID()) || + StringUtils.isBlank(authResource.getAuthorizationType()) || + StringUtils.isBlank(authResource.getAuthorizationStatus())) { + log.error("Consent ID, authorization type or authorization status is missing, cannot proceed"); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + "Cannot proceed since consent ID, authorization type or " + + "authorization status is missing"); + } + // create authorization resource + AuthorizationResource authorizationResource = + consentCoreDAO.storeAuthorizationResource(connection, authResource); + + for (ConsentMappingResource mappingResource : authResource.getConsentMappingResource()) { + + + mappingResource.setAuthorizationID(authorizationResource.getAuthorizationID()); + mappingResource.setMappingStatus("active"); + // create mapping resource + consentCoreDAO.storeConsentMappingResource(connection, mappingResource); + } + } + } + + public static boolean validateOrgInfo(String headerOrg, String orgId) throws ConsentMgtException { + + if (headerOrg == null) { + headerOrg = ConsentMgtDAOConstants.DEFAULT_ORG; + } + return headerOrg.equals(orgId); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-exclude.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-exclude.xml new file mode 100644 index 000000000..edb5c7091 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-exclude.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml new file mode 100644 index 000000000..aead0b83d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/main/resources/findbugs-include.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImplTest.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImplTest.java new file mode 100644 index 000000000..02b43378b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentCoreServiceImplTest.java @@ -0,0 +1,2208 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.impl; + +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataDeletionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.persistence.ConsentStoreInitializer; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.DatabaseUtils; +import org.wso2.financial.services.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; +import org.wso2.financial.services.accelerator.consent.mgt.service.util.ConsentMgtServiceTestData; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mockStatic; + +/** + * Test for FS consent management core service. + */ +public class ConsentCoreServiceImplTest { + + private ConsentCoreServiceImpl consentCoreServiceImpl; + @Mock + private ConsentCoreDAO mockedConsentCoreDAO; + @Mock + private ConsentCoreServiceImpl consentServiceMock; + private String sampleID; + @Mock + Connection connectionMock; + @Mock + ConsentResource consentResourceMock; + MockedStatic databaseUtilMockedStatic; + MockedStatic consentStoreInitializerMockedStatic; + + + @BeforeClass + public void initTest() { + + connectionMock = Mockito.mock(Connection.class); + consentCoreServiceImpl = new ConsentCoreServiceImpl(); + mockedConsentCoreDAO = Mockito.mock(ConsentCoreDAO.class); + consentResourceMock = Mockito.mock(ConsentResource.class); + consentServiceMock = Mockito.mock(ConsentCoreServiceImpl.class); + } + + @BeforeMethod + public void mock() { + + sampleID = UUID.randomUUID().toString(); + } + + @BeforeMethod + private void mockStaticClasses() { + + databaseUtilMockedStatic = mockStatic(DatabaseUtils.class); + databaseUtilMockedStatic.when(DatabaseUtils::getDBConnection).thenReturn(connectionMock); + + consentStoreInitializerMockedStatic = mockStatic(ConsentStoreInitializer.class); + consentStoreInitializerMockedStatic.when(ConsentStoreInitializer::getInitializedConsentCoreDAOImpl) + .thenReturn(mockedConsentCoreDAO); + + } + + @AfterMethod + public void tearDown() { + // Closing the mockStatic after each test + Mockito.reset(mockedConsentCoreDAO); + + databaseUtilMockedStatic.close(); + consentStoreInitializerMockedStatic.close(); + + } + + + @Test + public void testBindUserAccountsToConsentWithAccountIdList() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationUser(any(), anyString(), + anyString()); + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + Assert.assertTrue(consentCoreServiceImpl + .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID_LIST, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test + public void testBindUserAccountsToConsent() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationUser(any(), anyString(), + anyString()); + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + Assert.assertTrue(consentCoreServiceImpl + .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutNewCurrentConsentStatus() throws + Exception { + + consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutConsentID() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + consentResource.setConsentID(null); + + consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutClientID() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + consentResource.setClientID(null); + + consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutConsentType() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + consentResource.setConsentType(null); + + consentCoreServiceImpl.bindUserAccountsToConsent(consentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutUserID() throws + Exception { + + consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource(), + null, "authID", ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutAuthID() throws + Exception { + + consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, null, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithoutNewAuthStatus() throws + Exception { + + consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentWithEmptyAccountsAndPermissionsMap() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .bindUserAccountsToConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", new HashMap<>(), + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testBindUserAccountsToConsentDataUpdateError() throws + Exception { + + doThrow(ConsentDataUpdationException.class) + .when(mockedConsentCoreDAO).updateAuthorizationUser(any(), anyString(), + anyString()); + consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + +// @Test(expectedExceptions = ConsentMgtException.class) +// public void testBindUserAccountsToConsentDataInsertError() throws +// Exception { +// +// doThrow(ConsentDataInsertionException.class) +// .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), +// any(ConsentStatusAuditRecord.class)); +// consentCoreServiceImpl.bindUserAccountsToConsent(ConsentMgtServiceTestData +// .getSampleStoredConsentResource(), +// ConsentMgtServiceTestData.SAMPLE_USER_ID, "authID", +// ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, +// ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); +// } +// +// @Test +// public void testUpdateConsentStatus() throws +// Exception { +// +// DetailedConsentResource retrievedDetailedConsentResource = +// ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); +// +// doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( +// retrievedDetailedConsentResource.getConsentID(), +// retrievedDetailedConsentResource.getCurrentStatus())) +// .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), +// any(ConsentStatusAuditRecord.class)); +// +// consentCoreServiceImpl.updateConsentStatus(retrievedDetailedConsentResource.getConsentID(), +// ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); +// } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusDataRetrievalError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + + consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusDataUpdateError() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doThrow(ConsentDataUpdationException.class) + .when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + + consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusDataInsertError() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusWithoutConsentId() throws + Exception { + + consentCoreServiceImpl.updateConsentStatus(null, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusWithoutConsentStatus() throws + Exception { + + consentCoreServiceImpl.updateConsentStatus(ConsentMgtServiceTestData.CONSENT_ID, + null); + } + + @Test + public void testCreateConsentAccountMapping() throws + Exception { + + AuthorizationResource storedAuthorizationResource = + ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource(); + + ConsentMappingResource storedConsentMappingResource = + ConsentMgtServiceTestData.getSampleStoredTestConsentMappingResource(sampleID); + + doReturn(storedConsentMappingResource).when(mockedConsentCoreDAO) + .storeConsentMappingResource(any(), any()); + + ArrayList storedConsentMappingResources = + consentCoreServiceImpl.createConsentAccountMappings(storedAuthorizationResource.getAuthorizationID(), + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); + + Assert.assertNotNull(storedConsentMappingResources); + for (ConsentMappingResource resource : storedConsentMappingResources) { + Assert.assertNotNull(resource.getResource()); + Assert.assertNotNull(resource.getAuthorizationID()); + Assert.assertEquals(resource.getMappingStatus(), ConsentCoreServiceConstants.ACTIVE_MAPPING_STATUS); + } + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAccountMappingRollBackWhenCreation() throws + Exception { + + AuthorizationResource storedAuthorizationResource = + ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource(); + + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentMappingResource(any(), any()); + + consentCoreServiceImpl.createConsentAccountMappings(storedAuthorizationResource.getAuthorizationID(), + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAccountMappingWithoutAuthID() throws + Exception { + + consentCoreServiceImpl.createConsentAccountMappings(null, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAccountMappingWithoutAccountAndPermissionsMap() throws + Exception { + + consentCoreServiceImpl.createConsentAccountMappings(sampleID, new HashMap<>()); + } + + @Test + public void testDeactivateAccountMappings() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), any()); + Assert.assertTrue(consentCoreServiceImpl + .deactivateAccountMappings(ConsentMgtServiceTestData.UNMATCHED_MAPPING_IDS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testDeactivateAccountMappingsWithEmptyMappingIDList() throws + Exception { + + consentCoreServiceImpl.deactivateAccountMappings(new ArrayList<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testDeactivateAccountMappingsRollback() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentMappingStatus(any(), any(), any()); + consentCoreServiceImpl.deactivateAccountMappings(ConsentMgtServiceTestData.UNMATCHED_MAPPING_IDS); + } + + @Test + public void testUpdateAccountMappingStatus() throws + Exception { + + doNothing().when(mockedConsentCoreDAO) + .updateConsentMappingStatus(any(), any(), any()); + + consentCoreServiceImpl.updateAccountMappingStatus(ConsentMgtServiceTestData.MAPPING_IDS_LIST, + ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAccountMappingStatusWithoutMappingIds() throws + Exception { + + doNothing().when(mockedConsentCoreDAO) + .updateConsentMappingStatus(any(), any(), any()); + + consentCoreServiceImpl.updateAccountMappingStatus(new ArrayList<>(), + ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAccountMappingStatusDataUpdateError() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentMappingStatus(any(), any(), any()); + + consentCoreServiceImpl.updateAccountMappingStatus(ConsentMgtServiceTestData.MAPPING_IDS_LIST, + ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + } + + @Test + public void testRevokeConsent() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsentWithReason( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_USER_ID, false, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + + Assert.assertTrue(isConsentRevoked); + } + + @Test + public void testRevokeConsentWithReason() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsentWithReason( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + + Assert.assertTrue(isConsentRevoked); + } + + @Test + public void testRevokeConsentWithUserId() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsentWithReason( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + + Assert.assertTrue(isConsentRevoked); + } + + @Test + public void testRevokeConsentAndTokens() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsent( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + true); + + Assert.assertTrue(isConsentRevoked); + } + + @Test + public void testRevokeConsentAndTokensTokenRevokeError() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + try { + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsentWithReason( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_USER_ID, true, + ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + Assert.assertTrue(isConsentRevoked); + } catch (Exception e) { + Assert.assertTrue(e instanceof ConsentMgtException); + } + + } + + @Test + public void testRevokeConsentWithoutConsentAttributes() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + retrievedDetailedConsentResource.setConsentAttributes(null); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsent( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + false); + + Assert.assertTrue(isConsentRevoked); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeConsentWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.revokeConsentWithReason(null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeConsentWithoutNewConsentStatus() throws + Exception { + + consentCoreServiceImpl.revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + null, ConsentMgtServiceTestData.SAMPLE_USER_ID, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeConsentDataRetrievalError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + + consentCoreServiceImpl.revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeConsentDataInsertionError() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.revokeConsent(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeConsentDataUpdateError() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentStatus(any(), anyString(), anyString()); + + consentCoreServiceImpl.revokeConsentWithReason(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + false, ConsentCoreServiceConstants.CONSENT_REVOKE_REASON); + } + + + @Test + public void testRevokeConsentWithoutReason() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsent( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + + Assert.assertTrue(isConsentRevoked); + } + + @Test(priority = 1) + public void testRevokeConsentWithUserIDWithoutReason() throws + Exception { + + DetailedConsentResource retrievedDetailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + + doReturn(retrievedDetailedConsentResource).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentStatusAuditRecord( + retrievedDetailedConsentResource.getConsentID(), + retrievedDetailedConsentResource.getCurrentStatus())) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + boolean isConsentRevoked = consentCoreServiceImpl.revokeConsent( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID); + + Assert.assertTrue(isConsentRevoked); + } + + @Test + public void testRevokeExistingApplicableConsents() throws + Exception { + + ArrayList detailedConsentResources = new ArrayList<>(); + detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); + + doReturn(detailedConsentResources).when(mockedConsentCoreDAO) + .searchConsents(any(), any(), any(), any(), any(), any(), + any(), anyLong(), anyLong(), anyInt(), anyInt()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), any()); + + Assert.assertTrue(consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + false)); + } + + @Test + public void testRevokeExistingApplicableConsentsWithTokens() throws + Exception { + + ArrayList detailedConsentResources = new ArrayList<>(); + detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); + + doReturn(detailedConsentResources).when(mockedConsentCoreDAO) + .searchConsents(any(), any(), any(), any(), any(), any(), + any(), anyLong(), anyLong(), anyInt(), anyInt()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), any()); + + Assert.assertTrue(consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + true)); + } + + @Test + public void testRevokeExistingApplicableConsentsWithConsentsWithNoAttributes() throws + Exception { + + DetailedConsentResource detailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + detailedConsentResource.setConsentAttributes(null); + + ArrayList detailedConsentResources = new ArrayList<>(); + detailedConsentResources.add(detailedConsentResource); + + doReturn(detailedConsentResources).when(mockedConsentCoreDAO) + .searchConsents(any(), any(), any(), any(), any(), any(), + any(), anyLong(), anyLong(), anyInt(), anyInt()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), any()); + + consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .searchConsents(any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), any()); + + consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsUpdateError() throws + Exception { + + ArrayList detailedConsentResources = new ArrayList<>(); + detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); + + doReturn(detailedConsentResources).when(mockedConsentCoreDAO) + .searchConsents(any(), any(), any(), any(), any(), any(), + any(), any(), any(), any(), any()); + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentStatus(any(), anyString(), anyString()); + + consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); + } + +// @Test(expectedExceptions = ConsentMgtException.class) +// public void testRevokeExistingApplicableConsentsInsertionError() throws +// Exception { +// +// ArrayList detailedConsentResources = new ArrayList<>(); +// detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); +// +// doReturn(detailedConsentResources).when(mockedConsentCoreDAO) +// .searchConsents(any(), any(), any(), any(), any(), any(), +// any(), any(), any(), any(), any()); +// doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), +// anyString()); +// doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) +// .storeConsentStatusAuditRecord(any(), any()); +// +// consentCoreServiceImpl.revokeExistingApplicableConsents(sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, +// ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); +// } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsWithoutClientID() throws + Exception { + + consentCoreServiceImpl.revokeExistingApplicableConsents(null, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsWithoutRevokedConsentStatus() throws + Exception { + + consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsWithoutUserID() throws + Exception { + + consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, + null, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS + , false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsWithoutConsentType() throws + Exception { + + consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS + , false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testRevokeExistingApplicableConsentsWithoutApplicableStatusToRevoke() throws + Exception { + + consentCoreServiceImpl.revokeExistingApplicableConsents(ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS + , false); + } + + @Test + public void testReAuthorizeExistingAuthResources() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); + } + + @Test + public void testReAuthorizeExistingAuthResourceAccountsAddScenario() throws + Exception { + + ConsentMappingResource consentMappingResource = + ConsentMgtServiceTestData.getSampleTestConsentMappingResource(sampleID); + consentMappingResource.setAccountID("accountID1"); + ArrayList mappingResources = new ArrayList<>(); + mappingResources.add(consentMappingResource); + + DetailedConsentResource detailedConsentResource = + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource(); + detailedConsentResource.setConsentMappingResources(mappingResources); + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + doReturn(detailedConsentResource) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); + } + + @Test + public void testReAuthorizeExistingAuthResourceNoAccountsRemoveOrAddScenario() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP2, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); + } + + @Test + public void testReAuthorizeExistingAuthResourceAccountsRemoveScenario() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP3, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, consentResource.getCurrentStatus())); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutConsentID() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl.reAuthorizeExistingAuthResource(null, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutAuthID() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + null, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutUserID() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + sampleID, null, ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutCurrentConsentStatus() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + sampleID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutNewConsentStatus() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesWithoutAccountsAndPermissionsMap() throws + Exception { + + Assert.assertTrue(consentCoreServiceImpl + .reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>(), ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } +// +// @Test(expectedExceptions = ConsentMgtException.class) +// public void testReAuthorizeExistingAuthResourcesDataInsertError() throws +// Exception { +// +// doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) +// .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); +// doReturn(ConsentMgtServiceTestData +// .getSampleConsentMappingResourcesList(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST)) +// .when(mockedConsentCoreDAO).getConsentMappingResources(any(), anyString()); +// doThrow(ConsentDataInsertionException.class) +// .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), +// any()); +// consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, +// ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, +// ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); +// } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeExistingAuthResourcesDataUpdateError() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleConsentMappingResourcesList(ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST)) + .when(mockedConsentCoreDAO).getConsentMappingResources(any(), anyString()); + doThrow(ConsentDataUpdationException.class) + .when(mockedConsentCoreDAO).updateConsentStatus(any(), any(), + anyString()); + consentCoreServiceImpl.reAuthorizeExistingAuthResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + @Test + public void testReAuthorizeConsentWithNewAuthResource() throws + Exception { + + AuthorizationResource authorizationResource = ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(sampleID, null); + ArrayList consentIDs = new ArrayList<>(); + consentIDs.add(sampleID); + + doReturn(ConsentMgtServiceTestData.getSampleAuthorizationResourcesList(consentIDs)) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), anyString(), + anyString()); + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doReturn(authorizationResource).when(mockedConsentCoreDAO).storeAuthorizationResource(any(), + any(AuthorizationResource.class)); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(sampleID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), any(), any()); + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceDataUpdateError() throws + Exception { + + ArrayList consentIDs = new ArrayList<>(); + consentIDs.add(sampleID); + doReturn(ConsentMgtServiceTestData.getSampleAuthorizationResourcesList(consentIDs)) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), any(), any()); + doThrow(ConsentDataUpdationException.class) + .when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceDataInsertError() throws + Exception { + + AuthorizationResource authorizationResource = ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(sampleID, null); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), anyLong(), anyLong(), anyInt(), + anyInt()); + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doReturn(authorizationResource).when(mockedConsentCoreDAO).storeAuthorizationResource(any(), + any(AuthorizationResource.class)); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), + any()); + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(null, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutUserID() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, null, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutAccountsMap() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutCurrentConsentStatus() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutNewConsentStatus() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutNewExistingAuthStatus() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutNewAuthStatus() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + null, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testReAuthorizeConsentWithNewAuthResourceWithoutNewAuthType() throws + Exception { + + consentCoreServiceImpl.reAuthorizeConsentWithNewAuthResource(sampleID, sampleID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null); + } + + @Test + public void storeConsentAttributes() throws + Exception { + + consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void storeConsentAttributesWithoutParameters() throws + Exception { + + consentCoreServiceImpl.storeConsentAttributes(null, null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void storeConsentAttributesWithoutConsentId() throws + Exception { + + consentCoreServiceImpl.storeConsentAttributes(null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void storeConsentAttributesWithoutAttributeMap() throws + Exception { + + consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, + null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void storeConsentAttributesEmptyAttributeMap() throws + Exception { + + consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void storeConsentAttributesDataInsertError() throws + Exception { + + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeConsentAttributes(any(), any()); + + consentCoreServiceImpl.storeConsentAttributes(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test + public void testGetConsentAttributesWithAttributeKeys() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentAttributesObject(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString(), + any()); + ConsentAttributes consentAttributes = + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + Assert.assertNotNull(consentAttributes); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.getConsentAttributes(null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesWithEmptyAttributeKeys() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + new ArrayList<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesConsentResourceReteivealError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString(), any()); + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesDataRetrieveError() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString(), any()); + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test + public void testGetConsentAttributes() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentAttributesObject(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + ConsentAttributes consentAttributes = + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); + Assert.assertNotNull(consentAttributes); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesWithoutAttributeKeys() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesWithoutAttributesWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.getConsentAttributes(null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesConsentResourceRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentAttributesObject(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + ConsentAttributes consentAttributes = + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); + Assert.assertNotNull(consentAttributes); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesWithDataRetrieveError() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentAttributes(any(), anyString()); + ConsentAttributes consentAttributes = + consentCoreServiceImpl.getConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); + Assert.assertNotNull(consentAttributes); + } + + @Test + public void testGetConsentAttributesByName() throws + Exception { + + doReturn(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP) + .when(mockedConsentCoreDAO).getConsentAttributesByName(any(), anyString()); + Map retrievedAttributesMap = + consentCoreServiceImpl.getConsentAttributesByName("x-request-id"); + Assert.assertTrue(retrievedAttributesMap.containsKey("x-request-id")); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesByNameWithoutAttributeName() throws + Exception { + + consentCoreServiceImpl.getConsentAttributesByName(null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAttributesByNameDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentAttributesByName(any(), anyString()); + consentCoreServiceImpl.getConsentAttributesByName("x-request-id"); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentIdByConsentAttributeNameAndValueWithoutAttributeName() throws + Exception { + + consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue(null, + "domestic-payments"); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentIdByConsentAttributeNameAndValueWithoutAttributeValues() throws + Exception { + + consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue("payment-type", + null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentIdByConsentAttributeNameAndValueDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).getConsentIdByConsentAttributeNameAndValue(any(), + anyString(), anyString()); + consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue("payment-type", + "domestic-payments"); + } + + @Test + public void testGetConsentIdByConsentAttributeNameAndValue() throws + Exception { + + doReturn(ConsentMgtServiceTestData.SAMPLE_CONSENT_IS_ARRAY) + .when(mockedConsentCoreDAO).getConsentIdByConsentAttributeNameAndValue(any(), + anyString(), anyString()); + ArrayList consentIdList = consentCoreServiceImpl.getConsentIdByConsentAttributeNameAndValue( + "payment-type", "domestic-payments"); + Assert.assertFalse(consentIdList.isEmpty()); + } + + @Test + public void testUpdateConsentAttributes() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentAttributes(any(), + anyString(), anyMap()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentAttributesObject( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + consentCoreServiceImpl.updateConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentAttributesWithoutConsentId() throws + Exception { + + consentCoreServiceImpl.updateConsentAttributes(null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentAttributesWithoutAttributes() throws + Exception { + + consentCoreServiceImpl.updateConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentAttributesWithEmptyAttributes() throws + Exception { + + consentCoreServiceImpl.updateConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentAttributesWithDataUpdateError() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentAttributes(any(), anyString(), anyMap()); + doReturn(ConsentMgtServiceTestData.getSampleTestConsentAttributesObject( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID)) + .when(mockedConsentCoreDAO).getConsentAttributes(any(), anyString()); + consentCoreServiceImpl.updateConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentAttributesWithDataRetrieveError() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentAttributes(any(), + anyString(), anyMap()); + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentAttributes(any(), anyString()); + consentCoreServiceImpl.updateConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + @Test + public void testDeleteConsentAttributes() throws + Exception { + + doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(any(), + anyString(), any()); + consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testDeleteConsentAttributesDeleteError() throws + Exception { + + doThrow(ConsentDataDeletionException.class) + .when(mockedConsentCoreDAO).deleteConsentAttributes(any(), anyString(), + any()); + consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testDeleteConsentAttributesWithoutConsentID() throws + Exception { + + doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(any(), + anyString(), any()); + consentCoreServiceImpl.deleteConsentAttributes(null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_KEYS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testDeleteConsentAttributesWithoutAttributeKeysList() throws + Exception { + + doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(any(), + anyString(), any()); + consentCoreServiceImpl.deleteConsentAttributes(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + null); + } + + @Test + public void testSearchConsentStatusAuditRecords() throws + Exception { + + ArrayList consentStatusAuditRecords = new ArrayList<>(); + + doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) + .getConsentStatusAuditRecordsByConsentId(any(), any(ArrayList.class), + anyInt(), + anyInt()); + ArrayList statusAuditRecords = + consentCoreServiceImpl.searchConsentStatusAuditRecords(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_ACTION_BY, + 0L, 0L, "1234"); + Assert.assertNotNull(statusAuditRecords); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testSearchConsentStatusAuditRecordsWithDataRetrievalError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentStatusAuditRecords(any(), anyString(), anyString(), + anyString(), anyLong(), anyLong(), anyString()); + ArrayList statusAuditRecords = + consentCoreServiceImpl.searchConsentStatusAuditRecords(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_ACTION_BY, + 0L, 0L, "1234"); + Assert.assertNotNull(statusAuditRecords); + } + + @Test + public void testGetConsentStatusAuditRecords() throws + Exception { + + ArrayList consentStatusAuditRecords = new ArrayList<>(); + ArrayList consentIds = new ArrayList<>(); + + doReturn(consentStatusAuditRecords).when(mockedConsentCoreDAO) + .getConsentStatusAuditRecordsByConsentId(any(), any(ArrayList.class), + anyInt(), + anyInt()); + ArrayList statusAuditRecords = + consentCoreServiceImpl.getConsentStatusAuditRecords(consentIds, null, null); + Assert.assertNotNull(statusAuditRecords); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentStatusAuditRecordsWithDataRetrievalError() throws + Exception { + ArrayList consentIds = new ArrayList<>(); + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentStatusAuditRecordsByConsentId(any(), any(ArrayList.class), + any(), any()); + ArrayList statusAuditRecords = + consentCoreServiceImpl.getConsentStatusAuditRecords(consentIds, null, null); + Assert.assertNotNull(statusAuditRecords); + } + + @Test + public void testStoreConsentAmendmentHistory() throws + Exception { + + boolean result = consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, + ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + + Assert.assertTrue(result); + } + + @Test + public void testStoreConsentAmendmentHistoryWithoutPassingCurrentConsent() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setTimestamp(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP); + consentHistoryResource.setReason(ConsentMgtServiceTestData.SAMPLE_AMENDMENT_REASON); + consentHistoryResource.setDetailedConsentResource(ConsentMgtServiceTestData + .getSampleDetailedStoredTestCurrentConsentResource()); + + boolean result = consentCoreServiceImpl.storeConsentAmendmentHistory( + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + consentHistoryResource, null); + + Assert.assertTrue(result); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testStoreConsentAmendmentHistoryWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.storeConsentAmendmentHistory(null, + ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testStoreConsentAmendmentHistoryWithoutConsentHistoryResource() throws + Exception { + + consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, + null, + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testStoreConsentAmendmentHistoryWithZeroAsConsentAmendedTimestamp() throws + Exception { + + ConsentHistoryResource consentHistoryResource = ConsentMgtServiceTestData + .getSampleTestConsentHistoryResource(); + consentHistoryResource.setTimestamp(0); + consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, consentHistoryResource, + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testStoreConsentAmendmentHistoryWithoutConsentAmendedReason() throws + Exception { + + ConsentHistoryResource consentHistoryResource = ConsentMgtServiceTestData + .getSampleTestConsentHistoryResource(); + consentHistoryResource.setReason(null); + consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, + consentHistoryResource, + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testStoreConsentAmendmentHistoryDataInsertError() throws + Exception { + + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeConsentAmendmentHistory(any(), anyString(), + anyLong(), anyString(), anyString(), anyString(), + anyString()); + + consentCoreServiceImpl.storeConsentAmendmentHistory(sampleID, + ConsentMgtServiceTestData.getSampleTestConsentHistoryResource(), + ConsentMgtServiceTestData.getSampleDetailedStoredTestCurrentConsentResource()); + } + + + @Test + public void testAmendDetailedConsentData() throws + Exception { + + setInitialDataForAmendDetailedConsentSuccessFlow(); + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.amendDetailedConsent(sampleID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + + Assert.assertNotNull(detailedConsentResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(null, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + @Test + public void testAmendDetailedConsentDataWithoutValidityTimeOnly() throws + Exception { + + setInitialDataForAmendDetailedConsentSuccessFlow(); + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.amendDetailedConsent(sampleID, null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + + Assert.assertNotNull(detailedConsentResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutReceiptAndValidityTime() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, null, null, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutUserId() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, null, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutAuthId() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, null, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutNewConsentStatus() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutNewConsentAttributes() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + ConsentMgtServiceTestData.SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, null, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentDataWithoutAccountIdMapWithPermissions() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsent(sampleID, ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID, + null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, ConsentMgtServiceTestData.SAMPLE_USER_ID, + new HashMap<>()); + } + + private void setInitialDataForAmendDetailedConsentSuccessFlow() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentReceipt(any(), + anyString(), anyString()); + doNothing().when(mockedConsentCoreDAO).updateConsentValidityTime(any(), + anyString(), anyLong()); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(any(), + anyString(), any()); + doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(any(), + any(ConsentAttributes.class)); + } + + private void setInitialDataForAmendDetailedConsentWithBulkAuthResourceSuccessFlow() throws + Exception { + + // return authResource + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null)) + .when(mockedConsentCoreDAO).getAuthorizationResource(any(), + any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentReceipt(any(), + anyString(), anyString()); + doNothing().when(mockedConsentCoreDAO).updateConsentValidityTime(any(), + anyString(), anyLong()); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentStatusAuditRecord(sampleID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData.UNMATCHED_AUTHORIZATION_ID)) + .when(mockedConsentCoreDAO).storeConsentMappingResource(any(), + any(ConsentMappingResource.class)); + doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), + any(), anyString()); + + doReturn(true).when(mockedConsentCoreDAO).deleteConsentAttributes(any(), + anyString(), any()); + doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(any(), + any(ConsentAttributes.class)); + + //storeAuthorizationResource + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), + any(AuthorizationResource.class)); + // mocked DetailedConsentResource + DetailedConsentResource detailedConsentResource = Mockito.mock(DetailedConsentResource.class); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + // getOrgId + doReturn(ConsentMgtServiceTestData.ORG_INFO).when(detailedConsentResource).getOrgID(); + + } + + + // uint tests for amendDetailedConsentWithBulkAuthResource + @Test + public void testAmendDetailedConsentWithBulkAuthResource() throws + Exception { + + setInitialDataForAmendDetailedConsentWithBulkAuthResourceSuccessFlow(); + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.amendDetailedConsentWithBulkAuthResource( + ConsentMgtServiceTestData.ORG_INFO, + sampleID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourceListWithAuthIdAndConsentMappingId(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(sampleID, null) + ); + + Assert.assertNotNull(detailedConsentResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testAmendDetailedConsentWithBulkAuthResourceWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.amendDetailedConsentWithBulkAuthResource( + ConsentMgtServiceTestData.ORG_INFO, + null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourceListWithAuthIdAndConsentMappingId(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(sampleID, null) + ); + } + + @Test() + public void testAmendDetailedConsentWithBulkAuthResourceWithoutAuthorizationResource() throws + Exception { + + setInitialDataForAmendDetailedConsentWithBulkAuthResourceSuccessFlow(); + consentCoreServiceImpl.amendDetailedConsentWithBulkAuthResource( + ConsentMgtServiceTestData.ORG_INFO, + sampleID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + new ArrayList<>(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(sampleID, null) + ); + + } + + + @Test + public void testAmendDetailedConsentWithBulkAuthResourceWithoutUserId() throws + Exception { + setInitialDataForAmendDetailedConsentWithBulkAuthResourceSuccessFlow(); + + consentCoreServiceImpl.amendDetailedConsentWithBulkAuthResource( + ConsentMgtServiceTestData.ORG_INFO, + sampleID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourceListWithAuthIdAndConsentMappingId(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + null, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(sampleID, null) + ); + + } + + // unit tests for getConsentAmendmentHistoryData + @Test + public void testGetConsentAmendmentHistoryData() throws + Exception { + + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + + //retrieveConsentAmendmentHistory + doReturn(ConsentMgtServiceTestData.getSampleConsentHistoryDataMap()).when(mockedConsentCoreDAO). + retrieveConsentAmendmentHistory(any(), any(), any()); + + Map consentHistoryResource = + consentCoreServiceImpl.getConsentAmendmentHistoryData( + ConsentMgtServiceTestData.getSampleConsentStatusAuditRecordIds(), sampleID); + Assert.assertNotNull(consentHistoryResource); + } + + // empty consentStatusAuditRecordIds + @Test + public void testGetConsentAmendmentHistoryDataWithEmptyConsentStatusAuditRecordIds() throws + Exception { + + Map consentHistoryResource = + consentCoreServiceImpl.getConsentAmendmentHistoryData( + new ArrayList<>(), sampleID); + Assert.assertNotNull(consentHistoryResource); + } + + // empty consetId + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentAmendmentHistoryDataWithEmptyConsentId() throws + Exception { + + consentCoreServiceImpl.getConsentAmendmentHistoryData( + ConsentMgtServiceTestData.getSampleConsentStatusAuditRecordIds(), null); + } + + + @Test + public void testSearchConsents() throws + Exception { + + ArrayList detailedConsentResources = new ArrayList<>(); + detailedConsentResources.add(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()); + + doReturn(detailedConsentResources) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), anyLong(), anyLong(), anyInt(), + anyInt()); + + consentCoreServiceImpl.searchDetailedConsents(null, ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, + ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, + ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, + ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, + 12345L, 23456L, null, null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testSearchConsentsRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + + consentCoreServiceImpl.searchDetailedConsents(null, ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, + ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, + ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, + ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, + 12345L, 23456L, null, null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testSearchConsentsWithLimits() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), anyLong(), anyLong(), anyInt(), + anyInt()); + + consentCoreServiceImpl.searchDetailedConsents(null, ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, + ConsentMgtServiceTestData.SAMPLE_CLIENT_IDS_LIST, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPES_LIST, + ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST, + ConsentMgtServiceTestData.SAMPLE_USER_IDS_LIST, + 12345L, 23456L, 1, 0); + } + + +} + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentMgtCoreServiceTests.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentMgtCoreServiceTests.java new file mode 100644 index 000000000..68ad027d1 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/impl/ConsentMgtCoreServiceTests.java @@ -0,0 +1,1525 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.impl; + +import net.minidev.json.JSONObject; +import org.mockito.Mock; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.wso2.financial.services.accelerator.consent.mgt.dao.ConsentCoreDAO; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataInsertionException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataRetrievalException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentDataUpdationException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.persistence.ConsentStoreInitializer; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.DatabaseUtils; +import org.wso2.financial.services.accelerator.consent.mgt.service.util.ConsentCoreServiceUtil; +import org.wso2.financial.services.accelerator.consent.mgt.service.util.ConsentMgtServiceTestData; + +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mockStatic; + +/** + * Test for FS consent management core service. + */ +// CHECKSTYLE:OFF +public class ConsentMgtCoreServiceTests { + + private ConsentCoreServiceImpl consentCoreServiceImpl; + @Mock + private ConsentCoreDAO mockedConsentCoreDAO; + @Mock + private ConsentCoreServiceImpl consentServiceMock; + private String sampleID; + @Mock + Connection connectionMock; + @Mock + ConsentResource consentResourceMock; + MockedStatic databaseUtilMockedStatic; + MockedStatic consentStoreInitializerMockedStatic; + + + @BeforeClass + public void initTest() { + + connectionMock = Mockito.mock(Connection.class); + consentCoreServiceImpl = new ConsentCoreServiceImpl(); + mockedConsentCoreDAO = Mockito.mock(ConsentCoreDAO.class); + consentResourceMock = Mockito.mock(ConsentResource.class); + consentServiceMock = Mockito.mock(ConsentCoreServiceImpl.class); + } + + @BeforeMethod + public void mock() { + + sampleID = UUID.randomUUID().toString(); + } + + @BeforeMethod + private void mockStaticClasses() { + + databaseUtilMockedStatic = mockStatic(DatabaseUtils.class); + databaseUtilMockedStatic.when(DatabaseUtils::getDBConnection).thenReturn(connectionMock); + + consentStoreInitializerMockedStatic = mockStatic(ConsentStoreInitializer.class); + consentStoreInitializerMockedStatic.when(ConsentStoreInitializer::getInitializedConsentCoreDAOImpl) + .thenReturn(mockedConsentCoreDAO); + + } + + @AfterMethod + public void tearDown() { + // Closing the mockStatic after each test + Mockito.reset(mockedConsentCoreDAO); + + databaseUtilMockedStatic.close(); + consentStoreInitializerMockedStatic.close(); + + + } + + @Test(priority = 2) + public void testCreateAuthorizableConsent() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleTestConsentResource(), ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, true); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + } + + @Test(priority = 2) + public void testCreateAuthorizableConsentWithAttributes() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(any(), + any()); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, true); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + Assert.assertNotNull(detailedConsentResource.getConsentAttributes()); + } + + @Test(priority = 2) + public void testCreateAuthorizableConsentWithoutUserID() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), null, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, true); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithoutClientID() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setClientID(null); + + consentCoreServiceImpl.createAuthorizableConsent(consentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithoutReceipt() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setReceipt(null); + + consentCoreServiceImpl.createAuthorizableConsent(consentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithoutConsentType() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setConsentType(null); + + consentCoreServiceImpl.createAuthorizableConsent(consentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithoutCurrentStatus() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setCurrentStatus(null); + + consentCoreServiceImpl.createAuthorizableConsent(consentResource, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithImplicitAndNoAuthStatus() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), null, null, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithImplicitAndNoAuthType() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), null, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, null, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentRollback() throws + Exception { + + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + + consentCoreServiceImpl.createAuthorizableConsent(ConsentMgtServiceTestData + .getSampleTestConsentResource(), ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, true); + } + + + // unit tests for createAuthorizableConsentWithBulkAuth + + @Test + public void testCreateAuthorizableConsentWithBulkAuth() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentMappingResource(ConsentMgtServiceTestData. + SAMPLE_AUTHORIZATION_ID_1)).when(mockedConsentCoreDAO).storeConsentMappingResource(any(), any()); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleTestConsentResource(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), true); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + } + + @Test + public void testCreateAuthorizableConsentWithBulkAuthWithAttributes() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(any(), + any()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentMappingResource(ConsentMgtServiceTestData. + SAMPLE_AUTHORIZATION_ID_1)).when(mockedConsentCoreDAO).storeConsentMappingResource(any(), any()); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), true); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + Assert.assertNotNull(detailedConsentResource.getConsentAttributes()); + } + + @Test + public void testCreateAuthorizableConsentWithBulkAuthWithoutUserID() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + DetailedConsentResource detailedConsentResource = + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), false); + + Assert.assertNotNull(detailedConsentResource); + Assert.assertNotNull(detailedConsentResource.getConsentID()); + Assert.assertNotNull(detailedConsentResource.getClientID()); + Assert.assertNotNull(detailedConsentResource.getReceipt()); + Assert.assertNotNull(detailedConsentResource.getConsentType()); + Assert.assertNotNull(detailedConsentResource.getCurrentStatus()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthWithoutClientID() throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setClientID(null); + + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(consentResource, + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), true); + } + + // unit test for ImplicitAndNoAuthType + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthWithImplicitAndNoAuthType() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + ArrayList authorizationResources = new ArrayList<>(); + AuthorizationResource authorizationResource = new AuthorizationResource(); + authorizationResources.add(authorizationResource); + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleStoredTestConsentResourceWithAttributes(), + authorizationResources, + true); + } + + + // unit tests for createAuthorizableConsentWithBulkAuth with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthRollback() throws + Exception { + + + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleTestConsentResource(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), + true); + } + + + // unit tests for createAuthorizableConsentWithBulkAuth with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthRollbackWhenAuditRecord() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleTestConsentResource(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), + true); + } + + + // unit tests for createAuthorizableConsentWithBulkAuth with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthRollbackWhenStoringAuthResource() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeAuthorizationResource(any(), any()); + + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleTestConsentResource(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), + true); + } + + + // unit tests for createAuthorizableConsentWithBulkAuth with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateAuthorizableConsentWithBulkAuthRollbackWhenStoringAuthResourceWithAuditRecord() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeAuthorizationResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.createAuthorizableConsentWithBulkAuth(ConsentMgtServiceTestData + .getSampleTestConsentResource(), + ConsentMgtServiceTestData.getSampleTestAuthorizationResourcesList(null, null), + true); + } + + // unit tests for updateConsentStatusWithImplicitReasonAndUserId + @Test + public void testUpdateConsentStatusWithImplicitReasonAndUserId() throws + Exception { + + + + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + + // handle Status Audit Record + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.updateConsentStatusWithImplicitReasonAndUserId(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.ORG_INFO); + + + } + + // unit tests for updateConsentStatusWithImplicitReasonAndUserId with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusWithImplicitReasonAndUserIdRollback() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentStatus(any(), anyString(), anyString()); + + consentCoreServiceImpl.updateConsentStatusWithImplicitReasonAndUserId(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.ORG_INFO); + + } + + // unit tests for updateConsentStatusWithImplicitReasonAndUserId with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusWithImplicitReasonAndUserIdRollbackWhenAuditRecord() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.updateConsentStatusWithImplicitReasonAndUserId(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.ORG_INFO); + + } + + // unit tests for updateConsentStatusWithImplicitReasonAndUserId with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateConsentStatusWithImplicitReasonAndUserIdRollbackWhenAuditRecordWithConsentResource() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.updateConsentStatusWithImplicitReasonAndUserId(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.ORG_INFO); + } + + // unit tests for updateConsentStatusWithImplicitReasonAndUserId with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void + testUpdateConsentStatusWithImplicitReasonAndUserIdRollbackWhenAuditRecordWithConsentResourceWithConsentStatus() + throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.updateConsentStatusWithImplicitReasonAndUserId(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.ORG_INFO); + + } + + // unit test for bulkUpdateConsentStatus + @Test + public void testBulkUpdateConsentStatus() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any()); + consentCoreServiceImpl.bulkUpdateConsentStatus(ConsentMgtServiceTestData.ORG_INFO, + ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST); + } + + // unit test for bulkUpdateConsentStatus with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testBulkUpdateConsentStatusRollback() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any()); + consentCoreServiceImpl.bulkUpdateConsentStatus(ConsentMgtServiceTestData.ORG_INFO, + ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST); + } + + + // unit test for bulkUpdateConsentStatus with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testBulkUpdateConsentStatusRollbackWhenAuditRecord() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any()); + consentCoreServiceImpl.bulkUpdateConsentStatus(ConsentMgtServiceTestData.ORG_INFO, + ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST); + } + + // unit test for bulkUpdateConsentStatus with exceptions + @Test(expectedExceptions = ConsentMgtException.class) + public void testBulkUpdateConsentStatusRollbackWhenAuditRecordWithConsentResource() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), anyString()); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()).when(mockedConsentCoreDAO). + getDetailedConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentStatusAuditRecord(any(), any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), + any(), any(), any(), any(), any(), any(), any()); + consentCoreServiceImpl.bulkUpdateConsentStatus(ConsentMgtServiceTestData.ORG_INFO, + ConsentMgtServiceTestData.SAMPLE_CLIENT_ID, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_REASON, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CONSENT_STATUSES_LIST); + } + +// +// @Test +// public void testCreateExclusiveConsent() throws +// Exception { +// +// doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) +// .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), +// any(), any(), anyLong(), anyLong(), anyInt(), +// anyInt()); +// doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), +// anyString()); +// doReturn(ConsentMgtServiceTestData +// .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) +// .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), +// any(ConsentStatusAuditRecord.class)); +// doNothing().when(mockedConsentCoreDAO).updateConsentMappingStatus(any(), +// any(ArrayList.class), anyString()); +// doReturn(ConsentMgtServiceTestData.getSampleTestConsentResource()) +// .when(mockedConsentCoreDAO).storeConsentResource(any(), any(ConsentResource.class)); +// doReturn(true).when(mockedConsentCoreDAO).storeConsentAttributes(any(), +// any(ConsentAttributes.class)); +// doReturn(ConsentMgtServiceTestData +// .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, null)) +// .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), +// any(AuthorizationResource.class)); +// +// DetailedConsentResource exclusiveConsent = +// consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData +// .getSampleStoredConsentResource(), +// ConsentMgtServiceTestData.SAMPLE_USER_ID, +// ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, +// ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, +// ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); +// Assert.assertNotNull(exclusiveConsent); +// } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentDataUpdateError() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), any(), any(), any(), any()); + doThrow(ConsentDataUpdationException.class) + .when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentDataInsertError() throws + Exception { + + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourcesList()) + .when(mockedConsentCoreDAO).searchConsents(any(), any(), any(), any(), any(), + any(), any(), anyLong(), anyLong(), anyInt(), + anyInt()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .storeConsentResource(any(), any()); + doThrow(ConsentDataInsertionException.class) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutClientID() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + + ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + sampleConsentResource.setClientID(null); + + consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutReceipt() throws + Exception { + + ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + sampleConsentResource.setReceipt(null); + + consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutConsentType() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + sampleConsentResource.setConsentType(null); + + consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutConsentStatus() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + ConsentResource sampleConsentResource = ConsentMgtServiceTestData.getSampleStoredConsentResource(); + sampleConsentResource.setCurrentStatus(null); + + consentCoreServiceImpl.createExclusiveConsent(sampleConsentResource, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutUserID() throws + Exception { + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentStatusAuditRecord(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS)) + .when(mockedConsentCoreDAO).storeConsentStatusAuditRecord(any(), + any(ConsentStatusAuditRecord.class)); + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + null, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutAuthStatus() throws + Exception { + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, null, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutAuthType() throws + Exception { + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + null, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutApplicableExistingConsentStatus() throws + Exception { + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, null, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutNewExistingConsentStatus() throws + Exception { + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + null, true); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateExclusiveConsentWithoutNewCurrentConsentStatus() throws + Exception { + + consentCoreServiceImpl.createExclusiveConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource(), + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + null, true); + } + + @Test + public void testGetConsent() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredConsentResource()).when(mockedConsentCoreDAO) + .getConsentResource(any(), anyString()); + + // Get consent + ConsentResource retrievedConsentResource = consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), false); + + Assert.assertNotNull(retrievedConsentResource); + } + + @Test + public void testGetConsentWithAttributes() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredTestConsentResourceWithAttributes()) + .when(mockedConsentCoreDAO).getConsentResourceWithAttributes(any(), anyString()); + + // Get consent + ConsentResource retrievedConsentResource = consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), true); + + Assert.assertNotNull(retrievedConsentResource); + Assert.assertNotNull(retrievedConsentResource.getConsentAttributes()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentRollBackWhenRetrieve() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentResource(any(), anyString()); + + // Get consent + consentCoreServiceImpl.getConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID(), + false); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentWithoutConsentID() throws + Exception { + + consentCoreServiceImpl.getConsent(null, false); + } + + @Test + public void testGetDetailedConsent() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResource()) + .when(mockedConsentCoreDAO).getDetailedConsentResource(any(), anyString()); + + // Get consent + DetailedConsentResource retrievedConsentResource = consentCoreServiceImpl + .getDetailedConsent(ConsentMgtServiceTestData.getSampleStoredConsentResource().getConsentID()); + + Assert.assertNotNull(retrievedConsentResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetDetailedConsentWithoutConsentID() throws + Exception { + + // Get consent + consentCoreServiceImpl.getDetailedConsent(null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetDetailedConsentWithDataRetrievalException() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getDetailedConsentResource(any(), anyString()); + + // Get consent + consentCoreServiceImpl.getDetailedConsent(ConsentMgtServiceTestData + .getSampleStoredConsentResource().getConsentID()); + } + + @Test + public void testCreateConsentFile() throws + Exception { + + doReturn(ConsentMgtServiceTestData + .getSampleTestConsentResource(ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS)) + .when(mockedConsentCoreDAO).getConsentResource(any(), anyString()); + doReturn(true).when(mockedConsentCoreDAO).storeConsentFile(any(), any()); + doNothing().when(mockedConsentCoreDAO).updateConsentStatus(any(), anyString(), + anyString()); + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileErrorWhenRetrieval() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentResource(any(), anyString()); + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileRollBackWhenCreation() throws + Exception { + + ConsentResource storedConsentResource = ConsentMgtServiceTestData + .getSampleStoredConsentResource(ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + + doReturn(storedConsentResource).when(mockedConsentCoreDAO) + .getConsentResource(any(), anyString()); + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeConsentFile(any(), any()); + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileRollBackWhenUpdating() throws + Exception { + + ConsentResource storedConsentResource = ConsentMgtServiceTestData + .getSampleStoredConsentResource(ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + + doReturn(storedConsentResource).when(mockedConsentCoreDAO) + .getConsentResource(any(), anyString()); + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateConsentStatus(any(), anyString(), anyString()); + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + storedConsentResource.getCurrentStatus()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileWithInvalidStatus() + throws + Exception { + + ConsentResource consentResource = ConsentMgtServiceTestData.getSampleTestConsentResource(); + consentResource.setCurrentStatus(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + + doReturn(consentResource).when(mockedConsentCoreDAO).getConsentResource(any(), + anyString()); + + // Create consent file + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileWithoutFileContent() throws + Exception { + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(null), ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileWithoutConsentID() throws + Exception { + + ConsentFile sampleConsentFile = + ConsentMgtServiceTestData.getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE); + + sampleConsentFile.setConsentID(null); + consentCoreServiceImpl.createConsentFile(sampleConsentFile, ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileWithoutNewConsentStatus() + throws + Exception { + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + null, ConsentMgtServiceTestData.SAMPLE_USER_ID, + ConsentMgtServiceTestData.AWAITING_UPLOAD_STATUS); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentFileWithoutApplicableStatusForFileUpload() + throws + Exception { + + consentCoreServiceImpl.createConsentFile(ConsentMgtServiceTestData + .getSampleConsentFileObject(ConsentMgtServiceTestData.SAMPLE_CONSENT_FILE), + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_USER_ID, + null); + } + + @Test + public void testGetConsentFileConsentData() throws + Exception { + + doReturn(new ConsentFile()).when(mockedConsentCoreDAO) + .getConsentFile(any(), anyString()); + ConsentFile consentFile = consentCoreServiceImpl + .getConsentFile("3d22259e-942c-46b8-8f75-a608c677a6e6"); + Assert.assertNotNull(consentFile); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentFileWithoutConsentId() throws + Exception { + + consentCoreServiceImpl.getConsentFile(null); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetConsentFileWithDataRetrievalError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getConsentFile(any(), anyString()); + ConsentFile consentFile = consentCoreServiceImpl + .getConsentFile("3d22259e-942c-46b8-8f75-a608c677a6e6"); + Assert.assertNotNull(consentFile); + } + + @Test + public void testCreateConsentAuthorization() throws + Exception { + + AuthorizationResource sampleAuthorizationResource = + ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null); + + doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) + .when(mockedConsentCoreDAO).storeAuthorizationResource(any(), any()); + + //Create a consent authorization resource + AuthorizationResource storedAuthorizationResource = + consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); + + Assert.assertNotNull(storedAuthorizationResource); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationID()); + Assert.assertNotNull(storedAuthorizationResource.getConsentID()); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationType()); + Assert.assertNotNull(storedAuthorizationResource.getUserID()); + Assert.assertNotNull(storedAuthorizationResource.getAuthorizationStatus()); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAuthorizationRollbackWhenCreation() throws + Exception { + + AuthorizationResource sampleAuthorizationResource = + ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null); + + doThrow(ConsentDataInsertionException.class).when(mockedConsentCoreDAO) + .storeAuthorizationResource(any(), any()); + + // Get consent + consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAuthorizationWithoutConsentID() throws + Exception { + + AuthorizationResource sampleAuthorizationResource = + ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null); + sampleAuthorizationResource.setConsentID(null); + + //Create a consent authorization resource + consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAuthorizationWithoutAuthorizationStatus() throws + Exception { + + AuthorizationResource sampleAuthorizationResource = + ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null); + + // Explicitly setting authorization status to null + sampleAuthorizationResource.setAuthorizationStatus(null); + + //Create a consent authorization resource + consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testCreateConsentAuthorizationWithoutAuthorizationType() throws + Exception { + + AuthorizationResource sampleAuthorizationResource = + ConsentMgtServiceTestData.getSampleTestAuthorizationResource(sampleID, null); + sampleAuthorizationResource.setAuthorizationType(null); + + //Create a consent authorization resource + consentCoreServiceImpl.createConsentAuthorization(sampleAuthorizationResource); + } + + @Test + public void testGetAuthorizationResource() throws + Exception { + + doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) + .when(mockedConsentCoreDAO).getAuthorizationResource(any(), anyString(), any()); + AuthorizationResource authorizationResource = + consentCoreServiceImpl.getAuthorizationResource(ConsentMgtServiceTestData + .getSampleStoredTestAuthorizationResource().getAuthorizationID(), null); + Assert.assertNotNull(authorizationResource); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testGetAuthorizationResourceWithoutAuthID() throws + Exception { + + consentCoreServiceImpl.getAuthorizationResource(null, null); + } + +// @Test(expectedExceptions = ConsentMgtException.class) +// public void testGetAuthorizationResourceDataRetrieveError() throws +// Exception { +// +// doThrow(ConsentMgtException.class) +// .when(mockedConsentCoreDAO).getAuthorizationResource(any(), anyString(), any()); +// consentCoreServiceImpl.getAuthorizationResource(ConsentMgtServiceTestData +// .getSampleStoredTestAuthorizationResource().getAuthorizationID(), null); +// } + + @Test + public void testSearchAuthorizationsWithConsentID() throws + Exception { + + ArrayList consentIDs = new ArrayList<>(); + consentIDs.add(UUID.randomUUID().toString()); + + doReturn(ConsentMgtServiceTestData + .getSampleAuthorizationResourcesList(consentIDs)) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), anyString(), + anyString()); + ArrayList retrievedAuthorizations = + consentCoreServiceImpl.searchAuthorizations(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID); + Assert.assertNotNull(retrievedAuthorizations); + } + + @Test + public void testSearchAuthorizationsWithUserID() throws + Exception { + + ArrayList consentIDs = new ArrayList<>(); + consentIDs.add(UUID.randomUUID().toString()); + + doReturn(ConsentMgtServiceTestData + .getSampleAuthorizationResourcesList(consentIDs)) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), anyString(), + anyString()); + ArrayList retrievedAuthorizations = + consentCoreServiceImpl.searchAuthorizationsForUser(ConsentMgtServiceTestData.SAMPLE_USER_ID); + Assert.assertNotNull(retrievedAuthorizations); + } + + @Test + public void testSearchAuthorizations() throws + Exception { + + ArrayList consentIDs = new ArrayList<>(); + consentIDs.add(UUID.randomUUID().toString()); + + doReturn(ConsentMgtServiceTestData + .getSampleAuthorizationResourcesList(consentIDs)) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), anyString(), + anyString()); + ArrayList retrievedAuthorizations = + consentCoreServiceImpl.searchAuthorizations(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID); + Assert.assertNotNull(retrievedAuthorizations); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testSearchAuthorizationsDataRetrieveError() throws + Exception { + + doThrow(ConsentDataRetrievalException.class) + .when(mockedConsentCoreDAO).searchConsentAuthorizations(any(), anyString(), + anyString()); + + consentCoreServiceImpl.searchAuthorizations(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationStatusWithoutAuthId() throws + Exception { + + consentCoreServiceImpl.updateAuthorizationStatus(null, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationStatusWithoutNewAuthStatus() throws + Exception { + + consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, + null, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test + public void testUpdateAuthorizationStatus() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) + .when(mockedConsentCoreDAO).getAuthorizationResource(any(), anyString(), any()); + + consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationStatusWithDataUpdateError() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateAuthorizationStatus(any(), anyString(), anyString()); + + consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationStatusWithDataRetrievalError() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationStatus(any(), anyString(), + anyString()); + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getAuthorizationResource(any(), anyString(), any()); + + consentCoreServiceImpl.updateAuthorizationStatus(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_CONSUMED_STATUS, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationUserWithoutAuthorizationID() throws + Exception { + + consentCoreServiceImpl.updateAuthorizationUser(null, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationUserWithoutUserID() throws + Exception { + + consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + null, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationUserWithDataUpdateError() throws + Exception { + + doThrow(ConsentDataUpdationException.class).when(mockedConsentCoreDAO) + .updateAuthorizationUser(any(), anyString(), anyString()); + + consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test(expectedExceptions = ConsentMgtException.class) + public void testUpdateAuthorizationUserWithDataRetrieveError() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationUser(any(), + anyString(), anyString()); + doThrow(ConsentDataRetrievalException.class).when(mockedConsentCoreDAO) + .getAuthorizationResource(any(), anyString(), any()); + + consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.ORG_INFO); + } + + @Test + public void testUpdateAuthorizationUser() throws + Exception { + + doNothing().when(mockedConsentCoreDAO).updateAuthorizationUser(any(), anyString(), + anyString()); + doReturn(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()) + .when(mockedConsentCoreDAO).getAuthorizationResource(any(), anyString(), any()); + + + consentCoreServiceImpl.updateAuthorizationUser(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.ORG_INFO); + } + + // test for ConsentCoreServiceUtil + @Test + public void testGetConsentStatusAuditRecord() throws + Exception { + + + List consentStatusAuditRecord = ConsentCoreServiceUtil + .getRecordIdListForConsentHistoryRetrieval(ConsentMgtServiceTestData + .getSampleDetailedStoredTestConsentResource()); + Assert.assertNotNull(consentStatusAuditRecord); + + // assert + Assert.assertEquals(consentStatusAuditRecord.size(), 4); + + } + + @Test + public void testGetConsentStatusAuditRecordWithEmptyConsent() throws + Exception { + + List consentStatusAuditRecord = ConsentCoreServiceUtil + .getRecordIdListForConsentHistoryRetrieval(ConsentMgtServiceTestData + .getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs()); + Assert.assertNotNull(consentStatusAuditRecord); + + // assert + Assert.assertEquals(consentStatusAuditRecord.size(), 4); + + } + + // test getChangedBasicConsentDataJSON + @Test + public void testGetChangedBasicConsentDataJSON() throws + Exception { + + JSONObject changedBasicConsentDataJSON = ConsentCoreServiceUtil + .getChangedBasicConsentDataJSON( + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs(), + ConsentMgtServiceTestData.getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs()); + Assert.assertNotNull(changedBasicConsentDataJSON); + } + + + // test getChangedConsentAttributesDataJSON + @Test + public void testGetChangedConsentAttributesDataJSON() throws + Exception { + + JSONObject changedConsentAttributesDataJSON = ConsentCoreServiceUtil + .getChangedConsentAttributesDataJSON( + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, + ConsentMgtServiceTestData.SAMPLE_CHANGED_CONSENT_ATTRIBUTES_MAP); + Assert.assertNotNull(changedConsentAttributesDataJSON); + } + + // test getChangedConsentMappingDataJSONMap + @Test + public void testGetChangedConsentMappingDataJSONMap() throws + Exception { + + Map changedConsentMappingDataJSON = ConsentCoreServiceUtil + .getChangedConsentMappingDataJSONMap( + ConsentMgtServiceTestData.getSampleTestConsentMappingResourceListWithMappingId(), + ConsentMgtServiceTestData.getSampleTestConsentMappingResourceListWithMappingId()); + Assert.assertNotNull(changedConsentMappingDataJSON); + } + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceTestUtils.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceTestUtils.java new file mode 100644 index 000000000..3677fb22b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentCoreServiceTestUtils.java @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.util; + +import java.lang.reflect.Field; +import java.util.Map; + +public class ConsentCoreServiceTestUtils { + + public static void injectEnvironmentVariable(String key, String value) + throws + ReflectiveOperationException { + + Class processEnvironment = Class.forName("java.lang.ProcessEnvironment"); + + Field unmodifiableMapField = getAccessibleField(processEnvironment, "theUnmodifiableEnvironment"); + Object unmodifiableMap = unmodifiableMapField.get(null); + injectIntoUnmodifiableMap(key, value, unmodifiableMap); + + Field mapField = getAccessibleField(processEnvironment, "theEnvironment"); + Map map = (Map) mapField.get(null); + map.put(key, value); + } + + private static Field getAccessibleField(Class clazz, String fieldName) + throws + NoSuchFieldException { + + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return field; + } + + private static void injectIntoUnmodifiableMap(String key, String value, Object map) + throws + ReflectiveOperationException { + + Class unmodifiableMap = Class.forName("java.util.Collections$UnmodifiableMap"); + Field field = getAccessibleField(unmodifiableMap, "m"); + Object obj = field.get(map); + ((Map) obj).put(key, value); + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java new file mode 100644 index 000000000..908bdcb8d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/java/org/wso2/financial/services/accelerator/consent/mgt/service/util/ConsentMgtServiceTestData.java @@ -0,0 +1,669 @@ +/** + * Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com). + *

+ * WSO2 LLC. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.financial.services.accelerator.consent.mgt.service.util; + +import net.minidev.json.JSONObject; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentAttributes; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentFile; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; + +public class ConsentMgtServiceTestData { + + public static final String SAMPLE_CONSENT_RECEIPT = "{\"validUntil\": \"2020-10-20\", \"frequencyPerDay\": 1," + + " \"recurringIndicator\": false, \"combinedServiceIndicator\": true}"; + public static final String SAMPLE_CONSENT_TYPE = "accounts"; + public static final String SAMPLE_CLIENT_ID = "sampleClientID"; + public static final String ORG_INFO = "orgA"; + public static final String DEFAULT_ORG = "DEFAULT_ORG"; + public static final int SAMPLE_CONSENT_FREQUENCY = 1; + public static final Long SAMPLE_CONSENT_VALIDITY_PERIOD = 1638337852L; + public static final String SAMPLE_CURRENT_STATUS = "Authorised"; + public static final boolean SAMPLE_RECURRING_INDICATOR = true; + public static final String SAMPLE_AUTH_TYPE = "authorizationType"; + public static final String SAMPLE_USER_ID = "admin@wso2.com"; + public static final String SAMPLE_AUTHORIZATION_STATUS = "awaitingAuthorization"; + public static final String UNMATCHED_CONSENT_ID = "2222"; + public static final String SAMPLE_MAPPING_ID = "sampleMappingId"; + public static final String SAMPLE_ACCOUNT_ID = "123456789"; + public static final String SAMPLE_MAPPING_STATUS = "active"; + public static final String SAMPLE_NEW_MAPPING_STATUS = "inactive"; + public static final JSONObject SAMPLE_RESOURCE = new JSONObject(); + public static final String SAMPLE_PERMISSION = "samplePermission"; + public static final String SAMPLE_REASON = "sample reason"; + public static final String SAMPLE_ACTION_BY = "admin@wso2.com"; + public static final String SAMPLE_PREVIOUS_STATUS = "Received"; + public static final String SAMPLE_CONSENT_FILE = "sample file content"; + public static final String AWAITING_UPLOAD_STATUS = "awaitingUpload"; + public static final String SAMPLE_AUTHORIZATION_ID_1 = "88888"; + public static final String SAMPLE_MAPPING_ID_2 = "sampleMappingId2"; + public static final String CONSENT_ID = "464ef174-9877-4c71-940c-93d6e069eaf9"; + public static final String SAMPLE_CONSUMED_STATUS = "Consumed"; + public static final String UNMATCHED_AUTHORIZATION_ID = "3333"; + public static final long SAMPLE_CONSENT_AMENDMENT_TIMESTAMP = 1638337852; + public static final String SAMPLE_AMENDMENT_REASON = "sampleReason"; + public static final String SAMPLE_AUTHORIZATION_ID_2 = "99999"; + public static final String SAMPLE_HISTORY_ID = "sampleHistoryID"; + public static final String SAMPLE_NEW_USER_ID = "ann@gold.com"; + public static final Map SAMPLE_CONSENT_ATTRIBUTES_MAP = new HashMap() { + { + put("x-request-id", UUID.randomUUID().toString()); + put("idempotency-key", UUID.randomUUID().toString()); + put("sampleAttributeKey", "sampleAttributeValue"); + + } + }; + + public static final Map SAMPLE_CHANGED_CONSENT_ATTRIBUTES_MAP = new HashMap() { + { + put("x-request-id", UUID.randomUUID().toString()); + put("idempotency-key", UUID.randomUUID().toString()); + put("sampleAttributeKey", "sampleAttributeValue"); + + } + }; + + public static final ArrayList SAMPLE_ACCOUNT_ID_LIST = + new ArrayList(Arrays.asList(SAMPLE_ACCOUNT_ID)); + + public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP = + new HashMap>() {{ + put("accountID1", new ArrayList<>(Arrays.asList("permission1", "permission2"))); + put("accountID2", new ArrayList<>(Arrays.asList("permission3", "permission4"))); + }}; + + public static final ArrayList SAMPLE_CONSENT_ATTRIBUTES_KEYS = + new ArrayList(Arrays.asList("x-request-id", "idempotency-key")); + + public static final ArrayList SAMPLE_USER_IDS_LIST = + new ArrayList(Arrays.asList("userID1", "userID2", "userID3")); + + public static final ArrayList SAMPLE_CONSENT_IS_ARRAY = new ArrayList(Arrays.asList(CONSENT_ID)); + + public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP2 = + new HashMap>() {{ + put(SAMPLE_ACCOUNT_ID, new ArrayList<>(Arrays.asList("permission5", "permission6"))); + }}; + + public static final ArrayList SAMPLE_CONSENT_TYPES_LIST = + new ArrayList(Arrays.asList("accounts", "payments", "cof")); + + public static final ArrayList SAMPLE_CONSENT_STATUSES_LIST = + new ArrayList(Arrays.asList("created", "authorised", "awaitingAuthorization")); + + public static final Map> SAMPLE_ACCOUNT_IDS_AND_PERMISSIONS_MAP3 = + new HashMap>() {{ + put("mismatching account ID", new ArrayList<>(Arrays.asList("permission5", "permission6"))); + }}; + + public static final ArrayList SAMPLE_CLIENT_IDS_LIST = + new ArrayList(Arrays.asList("clientID1", "clientID2", "clientID3")); + public static final ArrayList MAPPING_IDS_LIST = + new ArrayList(Arrays.asList(SAMPLE_MAPPING_ID, SAMPLE_MAPPING_ID_2)); + public static final ArrayList UNMATCHED_MAPPING_IDS = new ArrayList(Arrays.asList("4444", "5555")); + + public static ConsentResource getSampleTestConsentResource() { + + return getSampleTestConsentResource(ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS); + } + + public static ConsentResource getSampleTestConsentResource(String status) { + + return new ConsentResource(ConsentMgtServiceTestData.ORG_INFO, null, UUID.randomUUID().toString(), + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, + ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR, status, + System.currentTimeMillis() / 1000, System.currentTimeMillis() / 1000); + } + + public static ConsentResource getSampleStoredConsentResource() { + ConsentResource consentResource = getSampleTestConsentResource(); + consentResource.setConsentID(UUID.randomUUID().toString()); + + return consentResource; + + } + + public static ConsentResource getSampleStoredConsentResource(String status) { + ConsentResource consentResource = getSampleTestConsentResource(status); + consentResource.setConsentID(UUID.randomUUID().toString()); + + return consentResource; + + } + + public static ConsentResource getSampleStoredTestConsentResourceWithAttributes() { + + ConsentResource consentResource = getSampleStoredConsentResource(); + consentResource.setConsentAttributes(ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + + return consentResource; + } + + public static DetailedConsentResource getSampleDetailedConsentResource( + ArrayList authResources, ArrayList mappingResources) { + + return new DetailedConsentResource( + ConsentMgtServiceTestData.ORG_INFO, + ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, UUID.randomUUID().toString(), + ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT, ConsentMgtServiceTestData.SAMPLE_CONSENT_TYPE, + ConsentMgtServiceTestData.SAMPLE_CURRENT_STATUS, ConsentMgtServiceTestData.SAMPLE_CONSENT_FREQUENCY, + ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD, System.currentTimeMillis() / 1000, + System.currentTimeMillis() / 1000, ConsentMgtServiceTestData.SAMPLE_RECURRING_INDICATOR, + ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP, authResources, mappingResources); + } + + public static ArrayList getSampleDetailedStoredTestConsentResourcesList() { + + ArrayList detailedConsentResourcesList = new ArrayList<>(); + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData.getSampleTestAuthorizationResource(null, null)); + + ArrayList consentMappingResources = new ArrayList<>(); + consentMappingResources.add(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(null, null).getAuthorizationID())); + + DetailedConsentResource detailedConsentResource = getSampleDetailedConsentResource(authorizationResources, + consentMappingResources); + + // Adding same resource twice to the list + detailedConsentResourcesList.add(detailedConsentResource); + detailedConsentResourcesList.add(detailedConsentResource); + + return detailedConsentResourcesList; + } + + public static DetailedConsentResource getSampleDetailedStoredTestConsentResource() { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.UNMATCHED_CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); + + ArrayList consentMappingResources = new ArrayList<>(); + consentMappingResources.add(ConsentMgtServiceTestData + .getSampleTestConsentMappingResource(ConsentMgtServiceTestData + .getSampleStoredTestAuthorizationResource().getAuthorizationID())); + consentMappingResources.add(ConsentMgtServiceTestData + .getSampleTestInactiveConsentMappingResource(ConsentMgtServiceTestData + .getSampleStoredTestAuthorizationResource().getAuthorizationID())); + + return getSampleDetailedConsentResource(authorizationResources, consentMappingResources); + } + + public static AuthorizationResource getSampleTestAuthorizationResource(String consentID, + String authorizationID) { + + AuthorizationResource authorizationResource = new AuthorizationResource(consentID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, System.currentTimeMillis() / 1000); + authorizationResource.setAuthorizationID(authorizationID); + + return authorizationResource; + } + + // list of authorization resources with consent mapping + + public static ArrayList getSampleTestAuthorizationResourcesList(String consentID, + String authorizationID) { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add( + ConsentMgtServiceTestData.getSampleTestAuthorizationResourceWithConsentMapping(consentID, + authorizationID)); + authorizationResources.add( + ConsentMgtServiceTestData.getSampleTestAuthorizationResourceWithConsentMapping(consentID, + authorizationID)); + + return authorizationResources; + } + + public static ArrayList + getSampleTestAuthorizationResourceListWithAuthIdAndConsentMappingId() { + ArrayList authorizationResources = new ArrayList<>(); + AuthorizationResource authorizationResource = new AuthorizationResource(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, System.currentTimeMillis() / 1000); + authorizationResource.setAuthorizationID(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1); + authorizationResource.setConsentMappingResource( + ConsentMgtServiceTestData.getSampleTestConsentMappingResourceList()); + authorizationResources.add(authorizationResource); + return authorizationResources; + } + + + public static AuthorizationResource getSampleTestAuthorizationResourceWithConsentMapping(String consentID, + String authorizationID) { + + + AuthorizationResource authorizationResource = new AuthorizationResource(consentID, + ConsentMgtServiceTestData.SAMPLE_USER_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_STATUS, + ConsentMgtServiceTestData.SAMPLE_AUTH_TYPE, System.currentTimeMillis() / 1000); + authorizationResource.setAuthorizationID(authorizationID); + authorizationResource.setConsentMappingResource( + ConsentMgtServiceTestData.getSampleTestConsentMappingResourceList()); + + return authorizationResource; + } + + public static AuthorizationResource getSampleStoredTestAuthorizationResource() { + + return getSampleTestAuthorizationResource(UUID.randomUUID().toString(), + UUID.randomUUID().toString()); + } + + public static ArrayList getSampleStoredTestAuthorizationResourcesList() { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()); + authorizationResources.add(ConsentMgtServiceTestData.getSampleStoredTestAuthorizationResource()); + + return authorizationResources; + } + + public static ConsentMappingResource getSampleTestConsentMappingResource(String authorizationID) { + + ConsentMappingResource consentMappingResource = new ConsentMappingResource(authorizationID, + ConsentMgtServiceTestData.SAMPLE_RESOURCE, + ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + consentMappingResource.setMappingID(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID); + + return consentMappingResource; + } + + // New method to get consent mapping resource without mapping and authorization id + public static ArrayList getSampleTestConsentMappingResourceListWithMappingId() { + + ArrayList consentMappingResources = new ArrayList<>(); + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setAccountID(ConsentMgtServiceTestData.SAMPLE_ACCOUNT_ID); + consentMappingResource.setResource(ConsentMgtServiceTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + consentMappingResource.setMappingID(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID); + + consentMappingResources.add(consentMappingResource); + consentMappingResources.add(consentMappingResource); + return consentMappingResources; + } + + // New method to get consent mapping resource without mapping and authorization id + public static ArrayList getSampleTestConsentMappingResourceList() { + + ArrayList consentMappingResources = new ArrayList<>(); + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setResource(ConsentMgtServiceTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + + consentMappingResources.add(consentMappingResource); + consentMappingResources.add(consentMappingResource); + return consentMappingResources; + } + + public static ConsentMappingResource getSampleTestInactiveConsentMappingResource(String authorizationID) { + + ConsentMappingResource consentMappingResource = getSampleTestConsentMappingResource(authorizationID); + consentMappingResource.setMappingID(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2); + consentMappingResource.setResource(ConsentMgtServiceTestData.SAMPLE_RESOURCE); + consentMappingResource.setMappingStatus(ConsentMgtServiceTestData.SAMPLE_NEW_MAPPING_STATUS); + + return consentMappingResource; + } + + public static ConsentStatusAuditRecord getSampleTestConsentStatusAuditRecord(String consentID, + String currentStatus) { + + return new ConsentStatusAuditRecord(String.valueOf(UUID.randomUUID()), consentID, currentStatus, + System.currentTimeMillis() / 1000, ConsentMgtServiceTestData.SAMPLE_REASON, + ConsentMgtServiceTestData.SAMPLE_ACTION_BY, ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); + } + + public static ConsentStatusAuditRecord getSampleStoredTestConsentStatusAuditRecord(String sampleID, + String currentStatus) { + + ConsentStatusAuditRecord consentStatusAuditRecord = getSampleTestConsentStatusAuditRecord(sampleID, + currentStatus); + consentStatusAuditRecord.setStatusAuditID(sampleID); + + return consentStatusAuditRecord; + } + + public static ConsentFile getSampleConsentFileObject(String fileContent) { + + return new ConsentFile(UUID.randomUUID().toString(), fileContent); + } + + public static ConsentAttributes getSampleTestConsentAttributesObject(String consentID) { + + return new ConsentAttributes(consentID, ConsentMgtServiceTestData.SAMPLE_CONSENT_ATTRIBUTES_MAP); + } + + public static ArrayList getSampleAuthorizationResourcesList(ArrayList consentIDs) { + + ArrayList authorizationResources = new ArrayList<>(); + + for (String consentID : consentIDs) { + for (int j = 0; j < 2; j++) { + AuthorizationResource authorizationResource = getSampleTestAuthorizationResource(consentID, + consentID); + authorizationResources.add(authorizationResource); + } + } + return authorizationResources; + } + + public static DetailedConsentResource getSampleDetailedStoredTestConsentResourceWithMultipleAccountIDs() { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData + .getSampleStoredTestAuthorizationResource()); + + ConsentMappingResource mappingResource1 = new ConsentMappingResource(); + mappingResource1.setAccountID(UUID.randomUUID().toString()); + + ConsentMappingResource mappingResource2 = new ConsentMappingResource(); + mappingResource2.setAccountID(UUID.randomUUID().toString()); + + ArrayList consentMappingResources = new ArrayList<>(); + consentMappingResources.add(mappingResource1); + consentMappingResources.add(mappingResource2); + + return getSampleDetailedConsentResource(authorizationResources, consentMappingResources); + } + + public static ArrayList getSampleConsentMappingResourcesList(ArrayList authIDs) { + + ArrayList consentMappingResources = new ArrayList<>(); + + for (String authID : authIDs) { + for (int j = 0; j < 2; j++) { + ConsentMappingResource consentMappingResource = getSampleTestConsentMappingResource(authID); + consentMappingResources.add(consentMappingResource); + } + } + return consentMappingResources; + } + + public static ConsentMappingResource getSampleStoredTestConsentMappingResource(String authorizationID) { + + ConsentMappingResource consentMappingResource = getSampleTestConsentMappingResource(authorizationID); + consentMappingResource.setMappingID(UUID.randomUUID().toString()); + + return consentMappingResource; + } + + public static ConsentHistoryResource getSampleTestConsentHistoryResource() { + + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setTimestamp(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP); + consentHistoryResource.setReason(ConsentMgtServiceTestData.SAMPLE_AMENDMENT_REASON); + consentHistoryResource.setDetailedConsentResource(getSampleDetailedConsentHistoryResource()); + + return consentHistoryResource; + } + + public static DetailedConsentResource getSampleDetailedConsentHistoryResource() { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData.getSampleTestAuthorizationResource( + ConsentMgtServiceTestData.CONSENT_ID, ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); + + ArrayList consentMappingResources = new ArrayList<>(); + consentMappingResources.add(ConsentMgtServiceTestData + .getSampleTestConsentHistoryMappingResource(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + ConsentMgtServiceTestData.SAMPLE_MAPPING_ID)); + + return getSampleDetailedConsentResource(authorizationResources, consentMappingResources); + } + + public static ConsentMappingResource getSampleTestConsentHistoryMappingResource(String authorizationID, + String mappingId) { + + ConsentMappingResource consentMappingResource = getSampleTestConsentMappingResource(authorizationID); + consentMappingResource.setMappingID(mappingId); + + return consentMappingResource; + } + + public static DetailedConsentResource getSampleDetailedStoredTestCurrentConsentResource() { + + ArrayList authorizationResources = new ArrayList<>(); + authorizationResources.add(ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1)); + authorizationResources.add(ConsentMgtServiceTestData + .getSampleTestAuthorizationResource(ConsentMgtServiceTestData.CONSENT_ID, + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_2)); + + ArrayList consentMappingResources = new ArrayList<>(); + consentMappingResources.add(ConsentMgtServiceTestData + .getSampleTestConsentHistoryMappingResource(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, + ConsentMgtServiceTestData.SAMPLE_MAPPING_ID)); + + // new mapping that is not included in the previous state of the consent + consentMappingResources.add(ConsentMgtServiceTestData.getSampleTestConsentHistoryMappingResource( + ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2)); + + return getSampleDetailedConsentResource(authorizationResources, consentMappingResources); + } + + public static Map getSampleDetailedStoredTestConsentHistoryDataMap() { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + + Map changedAttributesJson = new HashMap<>(); + changedAttributesJson.put("ConsentData", getBasicConsentDataChangedAttributesJson()); + changedAttributesJson.put("ConsentAttributesData", getConsentAttributesDataChangedAttributesJson()); + + Map consentAuthResources = new HashMap<>(); + consentAuthResources.put(ConsentMgtServiceTestData.SAMPLE_AUTHORIZATION_ID_1, "null"); + changedAttributesJson.put("ConsentAuthResourceData", consentAuthResources); + + Map consentMappingResources = new HashMap<>(); + JSONObject consentMappingDataJson1 = new JSONObject(); + consentMappingDataJson1.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID, consentMappingDataJson1); + + JSONObject consentMappingDataJson2 = new JSONObject(); + consentMappingDataJson2.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_NEW_MAPPING_STATUS); + consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2, consentMappingDataJson2); + + consentMappingResources.put(UUID.randomUUID().toString(), "null"); + changedAttributesJson.put("ConsentMappingData", consentMappingResources); + + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); + consentHistoryResource.setReason("SampleReason"); + consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); + return consentAmendmentHistoryDataMap; + } + + private static String getBasicConsentDataChangedAttributesJson() { + + JSONObject consentBasicDataJson = new JSONObject(); + consentBasicDataJson.put("RECEIPT", ConsentMgtServiceTestData.SAMPLE_CONSENT_RECEIPT); + consentBasicDataJson.put("UPDATED_TIME", + String.valueOf(ConsentMgtServiceTestData.SAMPLE_CONSENT_AMENDMENT_TIMESTAMP)); + consentBasicDataJson.put("VALIDITY_TIME", + String.valueOf(ConsentMgtServiceTestData.SAMPLE_CONSENT_VALIDITY_PERIOD)); + consentBasicDataJson.put("CURRENT_STATUS", ConsentMgtServiceTestData.SAMPLE_PREVIOUS_STATUS); + return consentBasicDataJson.toString(); + } + + private static String getConsentAttributesDataChangedAttributesJson() { + + JSONObject consentAttributesDataJson = new JSONObject(); + consentAttributesDataJson.put("sample_consent_attribute_name", "sample_consent_attribute_value"); + consentAttributesDataJson.put("sampleAttributeKey", null); + return consentAttributesDataJson.toString(); + } + + public static Map getSampleConsentHistoryBasicConsentDataMap() { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + Map changedAttributesJson = new HashMap<>(); + changedAttributesJson.put("ConsentData", getBasicConsentDataChangedAttributesJson()); + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); + consentHistoryResource.setReason("SampleReason"); + consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); + return consentAmendmentHistoryDataMap; + } + + public static Map getSampleConsentHistoryConsentAttributesDataMap() { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + Map changedAttributesJson = new HashMap<>(); + changedAttributesJson.put("ConsentAttributesData", getConsentAttributesDataChangedAttributesJson()); + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); + consentHistoryResource.setReason("SampleReason"); + consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); + return consentAmendmentHistoryDataMap; + } + + public static Map getSampleConsentHistoryConsentMappingsDataMap() { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + + Map changedAttributesJson = new HashMap<>(); + + Map consentMappingResources = new HashMap<>(); + JSONObject consentMappingDataJson1 = new JSONObject(); + consentMappingDataJson1.put("MAPPING_STATUS", ConsentMgtServiceTestData.SAMPLE_MAPPING_STATUS); + consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID, consentMappingDataJson1); + + JSONObject consentMappingDataJson2 = new JSONObject(); + consentMappingDataJson2.put("MAPPING_STATUS", "null"); + consentMappingResources.put(ConsentMgtServiceTestData.SAMPLE_MAPPING_ID_2, consentMappingDataJson2); + changedAttributesJson.put("ConsentMappingData", consentMappingResources); + + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); + consentHistoryResource.setReason("SampleReason"); + consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); + return consentAmendmentHistoryDataMap; + } + + public static Map getSampleAdditionalConsentAmendmentDataMap() { + + Map additionalAmendmentData = new HashMap<>(); + Map newUserAuthResources = new HashMap<>(); + Map> newUserAccountMappings = new HashMap<>(); + + AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); + newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); + + ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); + ArrayList consentMappingResourceList = new ArrayList<>(); + consentMappingResourceList.add(consentMappingResource); + newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); + + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); + return additionalAmendmentData; + } + + public static Map getSampleAdditionalConsentAmendmentDataMapWithoutConsentId() { + + Map additionalAmendmentData = new HashMap<>(); + Map newUserAuthResources = new HashMap<>(); + Map> newUserAccountMappings = new HashMap<>(); + + AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); + newAuthResource.setConsentID(null); + newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); + + ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); + ArrayList consentMappingResourceList = new ArrayList<>(); + consentMappingResourceList.add(consentMappingResource); + newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); + + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); + return additionalAmendmentData; + } + + public static Map getSampleAdditionalConsentAmendmentDataMapWithoutAccountId() { + + Map additionalAmendmentData = new HashMap<>(); + Map newUserAuthResources = new HashMap<>(); + Map> newUserAccountMappings = new HashMap<>(); + + AuthorizationResource newAuthResource = getSampleStoredTestAuthorizationResource(); + newUserAuthResources.put(SAMPLE_NEW_USER_ID, newAuthResource); + + ConsentMappingResource consentMappingResource = getSampleStoredTestConsentMappingResource(null); + consentMappingResource.setAccountID(null); + ArrayList consentMappingResourceList = new ArrayList<>(); + consentMappingResourceList.add(consentMappingResource); + newUserAccountMappings.put(SAMPLE_NEW_USER_ID, consentMappingResourceList); + + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_AUTHORIZATION_RESOURCES, newUserAuthResources); + additionalAmendmentData + .put(ConsentCoreServiceConstants.ADDITIONAL_MAPPING_RESOURCES, newUserAccountMappings); + return additionalAmendmentData; + } + + // sample statusAudit record Ids + public static ArrayList getSampleConsentStatusAuditRecordIds() { + + ArrayList consentStatusAuditRecordIds = new ArrayList<>(); + consentStatusAuditRecordIds.add(UUID.randomUUID().toString()); + consentStatusAuditRecordIds.add(UUID.randomUUID().toString()); + return consentStatusAuditRecordIds; + } + + // return Map with consent history resource + public static Map getSampleConsentHistoryDataMap() { + + Map consentAmendmentHistoryDataMap = new LinkedHashMap<>(); + Map changedAttributesJson = new HashMap<>(); + changedAttributesJson.put("ConsentData", getBasicConsentDataChangedAttributesJson()); + changedAttributesJson.put("ConsentAttributesData", getConsentAttributesDataChangedAttributesJson()); + changedAttributesJson.put("ConsentAuthResourceData", new HashMap<>()); + changedAttributesJson.put("ConsentMappingData", new HashMap<>()); + ConsentHistoryResource consentHistoryResource = new ConsentHistoryResource(); + consentHistoryResource.setChangedAttributesJsonDataMap(changedAttributesJson); + consentHistoryResource.setReason("SampleReason"); + consentAmendmentHistoryDataMap.put(ConsentMgtServiceTestData.SAMPLE_HISTORY_ID, consentHistoryResource); + return consentAmendmentHistoryDataMap; + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/resources/testng.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/resources/testng.xml new file mode 100644 index 000000000..629b58ff2 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/components/org.wso2.financial.services.accelerator.consent.mgt.service/src/test/resources/testng.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/config/checkstyle.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/config/checkstyle.xml new file mode 100644 index 000000000..36091f64c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/config/checkstyle.xml @@ -0,0 +1,3 @@ + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/Dockerfile b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/Dockerfile new file mode 100644 index 000000000..3eee3162c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/Dockerfile @@ -0,0 +1,28 @@ +# Use an official Maven image to build the WAR +FROM maven:3.9.9-eclipse-temurin-17 AS builder + +# Set working directory +WORKDIR /app + +# Copy project files +COPY . . + +COPY deployment/context.xml /app/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/context.xml +# Build the WAR file +RUN mvn clean package -DskipTests + +# Create a new user with UID 10014 +# RUN addgroup -g 10014 choreo && \ +# adduser --disabled-password --no-create-home --uid 10014 --ingroup choreo choreouser + +USER 10014 +FROM tomcat:9.0-jdk11 + +# RUN cp -r $CATALINA_HOME/webapps.dist/* $CATALINA_HOME/webapps +COPY --from=builder /app/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/target/consent.war /usr/local/tomcat/consent.war +# Copy the startup script +COPY deployment/entrypoint.sh /entrypoint.sh +RUN chmod +x /entrypoint.sh +EXPOSE 8080 +# USER 10014 +ENTRYPOINT ["/entrypoint.sh"] \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml new file mode 100644 index 000000000..62f0fe8e2 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml @@ -0,0 +1,9 @@ + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml.example b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml.example new file mode 100644 index 000000000..f0ea0b4b3 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/context.xml.example @@ -0,0 +1,9 @@ + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/entrypoint.sh b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/entrypoint.sh new file mode 100644 index 000000000..7f6889f99 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/deployment/entrypoint.sh @@ -0,0 +1,15 @@ +#!/bin/bash +set -e +export TRIVY_DISABLE_VEX_NOTICE=true + +# Ensure /usr/local/tomcat/webapps exists +mkdir -p /usr/local/tomcat/webapps + +# Copy the WAR file as ROOT.war if it doesn't already exist +if [ ! -f "/usr/local/tomcat/webapps/ROOT.war" ]; then + echo "Deploying ROOT.war..." + cp /usr/local/tomcat/consent.war /usr/local/tomcat/webapps/ROOT.war +fi + +# Start Tomcat +exec /usr/local/tomcat/bin/catalina.sh run diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/openapi.yaml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/openapi.yaml new file mode 100644 index 000000000..d9fc16f4e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/openapi.yaml @@ -0,0 +1,260 @@ +openapi: 3.0.1 +info: + title: Consent Management API + description: Consent Management application API + version: 1.0 +paths: + /consent/authorizationResource/{authorizationId}: + get: + operationId: consentAuthorizationIdGet + parameters: + - name: authorizationId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + responses: + default: + description: default response + content: + application/json: {} + /consent/{consentId}: + get: + operationId: consentConsentIdGet + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + - name: withAuthorizationResources + in: query + schema: + type: boolean + default: true + - name: UserId + in: query + schema: + type: string + - name: WithAttributes + in: query + schema: + type: boolean + responses: + default: + description: default response + content: + application/json: {} + put: + operationId: consentConsentIdPut + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/AmendmentResource" + required: true + responses: + default: + description: default response + content: + application/json: {} + delete: + operationId: consentConsentIdDelete + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + - name: userId + in: query + schema: + type: string + responses: + default: + description: default response + content: + "*/*": {} + /consent/{consentId}/history: + get: + operationId: consentConsentIdHistoryGet + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + - name: detailed + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + - name: actionBy + in: query + schema: + type: string + - name: fromTime + in: query + schema: + type: integer + format: int64 + - name: toTime + in: query + schema: + type: integer + format: int64 + - name: statusAuditId + in: query + schema: + type: string + responses: + default: + description: default response + content: + application/json: {} +components: + schemas: + AmendmentResource: + type: object + properties: + receipt: + type: string + validityPeriod: + type: integer + format: int32 + consentAttributes: + type: object + authorizationResources: + type: array + items: + $ref: "#/components/schemas/ReauthorizeResource" + currentStatus: + type: string + ReauthorizeResource: + type: object + properties: + authId: + type: string + authorizationStatus: + type: string + authorizationType: + type: string + resources: + type: array + items: + $ref: "#/components/schemas/Resource" + userID: + type: string + Resource: + type: object + properties: + resource: + type: string + consentMappingStatus: + type: string + resourceMappingId: + type: string + ConsentStatusUpdateResource: + type: object + properties: + status: + type: string + reason: + type: string + userID: + type: string + AuthorizationResourceDTO: + required: + - authorizationStatus + - authorizationType + - userID + type: object + properties: + authorizationStatus: + type: string + authorizationType: + type: string + userID: + type: string + resources: + type: array + items: + type: string + ConsentResourceDTO: + required: + - clientID + - consentType + - currentStatus + - receipt + - recurringIndicator + - validityPeriod + type: object + properties: + clientID: + type: string + consentType: + type: string + currentStatus: + type: string + receipt: + type: string + validityPeriod: + type: integer + format: int32 + recurringIndicator: + type: boolean + consentAttributes: + type: object + authorizationResources: + type: array + items: + $ref: "#/components/schemas/AuthorizationResourceDTO" + BulkConsentStatusUpdateResource: + type: object + properties: + clientID: + type: string + consentType: + type: string + applicableStatusesForStateChange: + type: array + items: + type: string + status: + type: string + reason: + type: string + userID: + type: string diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/pom.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/pom.xml new file mode 100644 index 000000000..82f2eedf7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/pom.xml @@ -0,0 +1,493 @@ + + + 4.0.0 + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.api + pom + 4.0.0-SNAPSHOT + + + org.wso2 + wso2 + 1.4 + + + + components/org.wso2.financial.services.accelerator.consent.mgt.dao + components/org.wso2.financial.services.accelerator.consent.mgt.service + + + webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint + + + + + + dev + + + true + + profile + dev + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + src/main/java + + + + attach-javadocs + + jar + + + + + + + + npm + + + + solution + + + profile + solution + + + + + + + npm + + + + + + WSO2 Open Banking - Parent + WSO2 Open Banking Solution + + + + + + + + wso2-nexus + WSO2 internal Repository + https://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + ignore + + + + wso2.releases + WSO2 internal Repository + https://maven.wso2.org/nexus/content/repositories/releases/ + + true + daily + ignore + + + + wso2.snapshots + Apache Snapshot Repository + https://maven.wso2.org/nexus/content/repositories/snapshots/ + + true + daily + + + false + + + + + + + wso2.releases + WSO2 internal Repository + https://maven.wso2.org/nexus/content/repositories/releases/ + + true + daily + ignore + + + + wso2.snapshots + WSO2 Snapshot Repository + https://maven.wso2.org/nexus/content/repositories/snapshots/ + + true + daily + + + false + + + + wso2-nexus + WSO2 internal Repository + https://maven.wso2.org/nexus/content/groups/wso2-public/ + + true + daily + ignore + + + + + + https://github.com/wso2/financial-open-banking.git + scm:git:https://github.com/wso2/financial-open-banking.git + scm:git:https://github.com/wso2/financial-open-banking.git + HEAD + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${maven.checkstyleplugin.version} + + + validate + validate + + + https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/checkstyle.xml + + + https://raw.githubusercontent.com/wso2/code-quality-tools/v1.3/checkstyle/suppressions.xml + + UTF-8 + true + true + true + + + check + + + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + ${maven.assembly.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.plugin.version} + true + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven.jar.plugin.version} + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.apache.felix + maven-bundle-plugin + ${maven.bundle.plugin.version} + true + + NONE + + ${buildNumber} + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven.surefire.plugin.version} + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + com.github.spotbugs + spotbugs-maven-plugin + ${maven.spotbugsplugin.version} + + Max + Low + true + ${project.build.directory}/spotbugs + + + + analyze-compile + compile + + check + + + + + + + + + + + + commons-logging + commons-logging + ${commons.logging.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + commons-beanutils + commons-beanutils + ${commons.bean.utils.version} + + + net.minidev + json-smart + ${json-smart.version} + + + + + org.wso2.eclipse.osgi + org.eclipse.osgi.services + ${org.osgi.eclipse.version} + + + org.eclipse.osgi + org.eclipse.osgi + ${org.osgi.bundle.version} + + + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.apache.commons + commons-collections4 + ${commons-collections.version} + + + com.github.spotbugs + spotbugs-annotations + ${spotbugs.annotations.version} + + + + org.json.wso2 + json + ${org.json.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + + org.apache.bcel + bcel + 6.6.0 + + + + + org.apache.commons + commons-text + 1.10.0 + + + + + org.apache.maven.shared + maven-shared-utils + 3.3.3 + + + + + org.apache.maven + maven-core + 3.8.1 + + + org.slf4j + slf4j-simple + ${org.slf4j.version} + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${org.apache.cxf.version} + + + org.apache.cxf + cxf-core + ${org.apache.cxf.version} + + + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs-api.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databinding.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.databinding.version} + + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.dao + ${project.version} + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.service + ${project.version} + + + + + org.testng + testng + ${org.testng.version} + test + + + org.mockito + mockito-core + ${mockito.version} + test + + + org.mockito + mockito-testng + ${mockito.testng.version} + test + + + commons-dbcp + commons-dbcp + ${commons-dbcp.version} + test + + + com.h2database.wso2 + h2-database-engine + ${orbit.version.h2.engine} + test + + + org.jacoco + org.jacoco.agent + runtime + ${jacoco.version} + + + + + + 1.8 + 2.4 + 3.8.0 + 3.0.2 + 3.3.2 + 3.2.0 + 4.2.3 + 3.1.0 + 1.12.0 + 1.2 + 3.4 + 1.9.4 + 2.4.11 + 3.5.100.v20160504-1419 + 3.9.1.v20130814-1242 + 6.0.20.Final + 4.4 + 4.7.3 + 3.0.0.wso2v4 + 2.16.1 + 2.1.1 + 2.17.1 + 3.5.9 + 2.15.1.wso2v1 + 2.0.1.Final + 0.8.6 + 5.3.1 + 7.10.1 + 0.5.2 + 1.4 + 1.2.140.wso2v3 + 1.7.21 + 2.0.0-alpha5 + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator-ignore b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator-ignore new file mode 100644 index 000000000..3bce5126e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator-ignore @@ -0,0 +1,26 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md +pom.xml +pom.xml +pom.xml diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator/openapi.yaml-default.sha256 b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator/openapi.yaml-default.sha256 new file mode 100644 index 000000000..7a0e2fa0e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/.openapi-generator/openapi.yaml-default.sha256 @@ -0,0 +1 @@ +2372219960531af3f5d3dcef8d52d148b22087e68b46fa7284aefa7bb673536d \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/README.md b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/README.md new file mode 100644 index 000000000..9b5c52b8f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/README.md @@ -0,0 +1,155 @@ +# openapi-java-client + +ConsentAPI +- API version: v1.0 + - Build date: 2025-05-02T11:51:05.356873+05:30[Asia/Colombo] + +This specifies a RESTful API for making interactions with the consent module + + For more information, please visit [https://wso2.com/solutions/financial-services/open-banking/](https://wso2.com/solutions/financial-services/open-banking/) + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.8+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + openapi-java-client + v1.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'openapi-java-client' jar has been published to maven central. + mavenLocal() // Needed if the 'openapi-java-client' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:openapi-java-client:v1.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/openapi-java-client-v1.0.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +// Import classes: +import impl.ApiClient; +import impl.ApiException; +import impl.Configuration; +import impl.models.*; +import org.wso2.bfsi.consent.management.endpoint.api.AdminApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://localhost:9446/api/bfsi/consent"); + + AdminApi apiInstance = new AdminApi(defaultClient); + String consentID = "consentID_example"; // String | + String userID = "userID_example"; // String | + try { + apiInstance.revokeConsents(consentID, userID); + } catch (ApiException e) { + System.err.println("Exception when calling AdminApi#revokeConsents"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://localhost:9446/api/bfsi/consent* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AdminApi* | [**revokeConsents**](docs/AdminApi.md#revokeConsents) | **DELETE** /admin/revoke | Revoke consents +*AdminApi* | [**searchConsents**](docs/AdminApi.md#searchConsents) | **GET** /admin/search | Search consent information +*AuthorizeApi* | [**authorizePersist**](docs/AuthorizeApi.md#authorizePersist) | **PATCH** /authorize/persist/{session-data-key} | Persist user consent +*AuthorizeApi* | [**authorizeRetrieve**](docs/AuthorizeApi.md#authorizeRetrieve) | **GET** /authorize/retrieve/{session-data-key} | Retrieve data for consent page +*ManageApi* | [**manageDelete**](docs/ManageApi.md#manageDelete) | **DELETE** /manage | Delete endpoint for manage +*ManageApi* | [**manageGet**](docs/ManageApi.md#manageGet) | **GET** /manage | Get endpoint for manage +*ManageApi* | [**managePatch**](docs/ManageApi.md#managePatch) | **PATCH** /manage | Patch endpoint for manage +*ManageApi* | [**managePost**](docs/ManageApi.md#managePost) | **POST** /manage | Post endpoint for manage +*ManageApi* | [**managePut**](docs/ManageApi.md#managePut) | **PUT** /manage | Put endpoint for manage +*ValidateApi* | [**consentValdiate**](docs/ValidateApi.md#consentValdiate) | **POST** /validate | Validation endpoint used for consent enforcement + + +## Documentation for Models + + - [OBConsentAuthorizationResourceDTO](docs/OBConsentAuthorizationResourceDTO.md) + - [OBConsentDetailDTO](docs/OBConsentDetailDTO.md) + - [OBConsentErrorCommonDTO](docs/OBConsentErrorCommonDTO.md) + - [OBConsentMappingResourceDTO](docs/OBConsentMappingResourceDTO.md) + - [OBConsentSearchMetadataDTO](docs/OBConsentSearchMetadataDTO.md) + - [OBConsentSearchOKResponseDTO](docs/OBConsentSearchOKResponseDTO.md) + - [OBConsentValidateDetailDTO](docs/OBConsentValidateDetailDTO.md) + - [OBConsentValidateOKResponseDTO](docs/OBConsentValidateOKResponseDTO.md) + + + +## Documentation for Authorization + +Endpoints do not require authorization. + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +architecture@wso2.com + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/Catalina/localhost/endpoint.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/Catalina/localhost/endpoint.xml new file mode 100644 index 000000000..e280b2c04 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/Catalina/localhost/endpoint.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.policy b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.policy new file mode 100644 index 000000000..7aab95dee --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.policy @@ -0,0 +1,264 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// ============================================================================ +// catalina.policy - Security Policy Permissions for Tomcat +// +// This file contains a default set of security policies to be enforced (by the +// JVM) when Catalina is executed with the "-security" option. In addition +// to the permissions granted here, the following additional permissions are +// granted to each web application: +// +// * Read access to the web application's document root directory +// * Read, write and delete access to the web application's working directory +// ============================================================================ + + +// ========== SYSTEM CODE PERMISSIONS ========================================= + + +// These permissions apply to javac +grant codeBase "file:${java.home}/lib/-" { + permission java.security.AllPermission; +}; + +// These permissions apply to all shared system extensions +grant codeBase "file:${java.home}/jre/lib/ext/-" { + permission java.security.AllPermission; +}; + +// These permissions apply to javac when ${java.home} points at $JAVA_HOME/jre +grant codeBase "file:${java.home}/../lib/-" { + permission java.security.AllPermission; +}; + +// These permissions apply to all shared system extensions when +// ${java.home} points at $JAVA_HOME/jre +grant codeBase "file:${java.home}/lib/ext/-" { + permission java.security.AllPermission; +}; + +// This permission is required when using javac to compile JSPs on Java 9 +// onwards +//grant codeBase "jrt:/jdk.compiler" { +// permission java.security.AllPermission; +//}; + + +// ========== CATALINA CODE PERMISSIONS ======================================= + +// These permissions apply to the daemon code +grant codeBase "file:${catalina.home}/bin/commons-daemon.jar" { + permission java.security.AllPermission; +}; + +// These permissions apply to the logging API +// Note: If tomcat-juli.jar is in ${catalina.base} and not in ${catalina.home}, +// update this section accordingly. +// grant codeBase "file:${catalina.base}/bin/tomcat-juli.jar" {..} +grant codeBase "file:${catalina.home}/bin/tomcat-juli.jar" { + permission java.io.FilePermission + "${java.home}${file.separator}lib${file.separator}logging.properties", "read"; + + permission java.io.FilePermission + "${catalina.base}${file.separator}conf${file.separator}logging.properties", "read"; + permission java.io.FilePermission + "${catalina.base}${file.separator}logs", "read, write"; + permission java.io.FilePermission + "${catalina.base}${file.separator}logs${file.separator}*", "read, write, delete"; + + permission java.lang.RuntimePermission "shutdownHooks"; + permission java.lang.RuntimePermission "getClassLoader"; + permission java.lang.RuntimePermission "setContextClassLoader"; + + permission java.lang.management.ManagementPermission "monitor"; + + permission java.util.logging.LoggingPermission "control"; + + permission java.util.PropertyPermission "java.util.logging.config.class", "read"; + permission java.util.PropertyPermission "java.util.logging.config.file", "read"; + permission java.util.PropertyPermission "org.apache.juli.AsyncMaxRecordCount", "read"; + permission java.util.PropertyPermission "org.apache.juli.AsyncOverflowDropType", "read"; + permission java.util.PropertyPermission "org.apache.juli.ClassLoaderLogManager.debug", "read"; + permission java.util.PropertyPermission "catalina.base", "read"; + + // Note: To enable per context logging configuration, permit read access to + // the appropriate file. Be sure that the logging configuration is + // secure before enabling such access. + // E.g. for the examples web application (uncomment and unwrap + // the following to be on a single line): + // permission java.io.FilePermission "${catalina.base}${file.separator} + // webapps${file.separator}examples${file.separator}WEB-INF + // ${file.separator}classes${file.separator}logging.properties", "read"; +}; + +// These permissions apply to the server startup code +grant codeBase "file:${catalina.home}/bin/bootstrap.jar" { + permission java.security.AllPermission; +}; + +// These permissions apply to the servlet API classes +// and those that are shared across all class loaders +// located in the "lib" directory +grant codeBase "file:${catalina.home}/lib/-" { + permission java.security.AllPermission; +}; + + +// If using a per instance lib directory, i.e. ${catalina.base}/lib, +// then the following permission will need to be uncommented +// grant codeBase "file:${catalina.base}/lib/-" { +// permission java.security.AllPermission; +// }; + + +// ========== WEB APPLICATION PERMISSIONS ===================================== + + +// These permissions are granted by default to all web applications +// In addition, a web application will be given a read FilePermission +// for all files and directories in its document root. +grant { + // Required for JNDI lookup of named JDBC DataSource's and + // javamail named MimePart DataSource used to send mail + permission java.util.PropertyPermission "java.home", "read"; + permission java.util.PropertyPermission "java.naming.*", "read"; + permission java.util.PropertyPermission "javax.sql.*", "read"; + + // OS Specific properties to allow read access + permission java.util.PropertyPermission "os.name", "read"; + permission java.util.PropertyPermission "os.version", "read"; + permission java.util.PropertyPermission "os.arch", "read"; + permission java.util.PropertyPermission "file.separator", "read"; + permission java.util.PropertyPermission "path.separator", "read"; + permission java.util.PropertyPermission "line.separator", "read"; + + // JVM properties to allow read access + permission java.util.PropertyPermission "java.version", "read"; + permission java.util.PropertyPermission "java.vendor", "read"; + permission java.util.PropertyPermission "java.vendor.url", "read"; + permission java.util.PropertyPermission "java.class.version", "read"; + permission java.util.PropertyPermission "java.specification.version", "read"; + permission java.util.PropertyPermission "java.specification.vendor", "read"; + permission java.util.PropertyPermission "java.specification.name", "read"; + + permission java.util.PropertyPermission "java.vm.specification.version", "read"; + permission java.util.PropertyPermission "java.vm.specification.vendor", "read"; + permission java.util.PropertyPermission "java.vm.specification.name", "read"; + permission java.util.PropertyPermission "java.vm.version", "read"; + permission java.util.PropertyPermission "java.vm.vendor", "read"; + permission java.util.PropertyPermission "java.vm.name", "read"; + + // Required for OpenJMX + permission java.lang.RuntimePermission "getAttribute"; + + // Allow read of JAXP compliant XML parser debug + permission java.util.PropertyPermission "jaxp.debug", "read"; + + // All JSPs need to be able to read this package + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat"; + + // Precompiled JSPs need access to these packages. + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper.el"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.jasper.runtime"; + permission java.lang.RuntimePermission + "accessClassInPackage.org.apache.jasper.runtime.*"; + + // Applications using WebSocket need to be able to access these packages + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat.websocket"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.tomcat.websocket.server"; +}; + + +// The Manager application needs access to the following packages to support the +// session display functionality. It also requires the custom Tomcat +// DeployXmlPermission to enable the use of META-INF/context.xml +// These settings support the following configurations: +// - default CATALINA_HOME == CATALINA_BASE +// - CATALINA_HOME != CATALINA_BASE, per instance Manager in CATALINA_BASE +// - CATALINA_HOME != CATALINA_BASE, shared Manager in CATALINA_HOME +grant codeBase "file:${catalina.base}/webapps/manager/-" { + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.ha.session"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager.util"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.util"; + permission org.apache.catalina.security.DeployXmlPermission "manager"; +}; +grant codeBase "file:${catalina.home}/webapps/manager/-" { + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.ha.session"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.manager.util"; + permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.util"; + permission org.apache.catalina.security.DeployXmlPermission "manager"; +}; + +// The Host Manager application needs the custom Tomcat DeployXmlPermission to +// enable the use of META-INF/context.xml +// These settings support the following configurations: +// - default CATALINA_HOME == CATALINA_BASE +// - CATALINA_HOME != CATALINA_BASE, per instance Host Manager in CATALINA_BASE +// - CATALINA_HOME != CATALINA_BASE, shared Host Manager in CATALINA_HOME +grant codeBase "file:${catalina.base}/webapps/host-manager/-" { + permission org.apache.catalina.security.DeployXmlPermission "host-manager"; +}; +grant codeBase "file:${catalina.home}/webapps/host-manager/-" { + permission org.apache.catalina.security.DeployXmlPermission "host-manager"; +}; + + +// You can assign additional permissions to particular web applications by +// adding additional "grant" entries here, based on the code base for that +// application, /WEB-INF/classes/, or /WEB-INF/lib/ jar files. +// +// Different permissions can be granted to JSP pages, classes loaded from +// the /WEB-INF/classes/ directory, all jar files in the /WEB-INF/lib/ +// directory, or even to individual jar files in the /WEB-INF/lib/ directory. +// +// For instance, assume that the standard "examples" application +// included a JDBC driver that needed to establish a network connection to the +// corresponding database and used the scrape taglib to get the weather from +// the NOAA web server. You might create a "grant" entries like this: +// +// The permissions granted to the context root directory apply to JSP pages. +// grant codeBase "file:${catalina.base}/webapps/examples/-" { +// permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect"; +// permission java.net.SocketPermission "*.noaa.gov:80", "connect"; +// }; +// +// The permissions granted to the context WEB-INF/classes directory +// grant codeBase "file:${catalina.base}/webapps/examples/WEB-INF/classes/-" { +// }; +// +// The permission granted to your JDBC driver +// grant codeBase "jar:file:${catalina.base}/webapps/examples/WEB-INF/lib/driver.jar!/-" { +// permission java.net.SocketPermission "dbhost.mycompany.com:5432", "connect"; +// }; +// The permission granted to the scrape taglib +// grant codeBase "jar:file:${catalina.base}/webapps/examples/WEB-INF/lib/scrape.jar!/-" { +// permission java.net.SocketPermission "*.noaa.gov:80", "connect"; +// }; + +// To grant permissions for web applications using packed WAR files, use the +// Tomcat specific WAR url scheme. +// +// The permissions granted to the entire web application +// grant codeBase "war:file:${catalina.base}/webapps/examples.war*/-" { +// }; +// +// The permissions granted to a specific JAR +// grant codeBase "war:file:${catalina.base}/webapps/examples.war*/WEB-INF/lib/foo.jar" { +// }; \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.properties b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.properties new file mode 100644 index 000000000..c094c3249 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/catalina.properties @@ -0,0 +1,220 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# +# List of comma-separated packages that start with or equal this string +# will cause a security exception to be thrown when +# passed to checkPackageAccess unless the +# corresponding RuntimePermission ("accessClassInPackage."+package) has +# been granted. +package.access=sun.,org.apache.catalina.,org.apache.coyote.,org.apache.jasper.,org.apache.tomcat. +# +# List of comma-separated packages that start with or equal this string +# will cause a security exception to be thrown when +# passed to checkPackageDefinition unless the +# corresponding RuntimePermission ("defineClassInPackage."+package) has +# been granted. +# +# by default, no packages are restricted for definition, and none of +# the class loaders supplied with the JDK call checkPackageDefinition. +# +package.definition=sun.,java.,org.apache.catalina.,org.apache.coyote.,\ +org.apache.jasper.,org.apache.naming.,org.apache.tomcat. + +# +# +# List of comma-separated paths defining the contents of the "common" +# classloader. Prefixes should be used to define what is the repository type. +# Path may be relative to the CATALINA_HOME or CATALINA_BASE path or absolute. +# If left as blank,the JVM system loader will be used as Catalina's "common" +# loader. +# Examples: +# "foo": Add this folder as a class repository +# "foo/*.jar": Add all the JARs of the specified folder as class +# repositories +# "foo/bar.jar": Add bar.jar as a class repository +# +# Note: Values are enclosed in double quotes ("...") in case either the +# ${catalina.base} path or the ${catalina.home} path contains a comma. +# Because double quotes are used for quoting, the double quote character +# may not appear in a path. +common.loader="${catalina.base}/lib","${catalina.base}/lib/*.jar","${catalina.home}/lib","${catalina.home}/lib/*.jar" + +# +# List of comma-separated paths defining the contents of the "server" +# classloader. Prefixes should be used to define what is the repository type. +# Path may be relative to the CATALINA_HOME or CATALINA_BASE path or absolute. +# If left as blank, the "common" loader will be used as Catalina's "server" +# loader. +# Examples: +# "foo": Add this folder as a class repository +# "foo/*.jar": Add all the JARs of the specified folder as class +# repositories +# "foo/bar.jar": Add bar.jar as a class repository +# +# Note: Values may be enclosed in double quotes ("...") in case either the +# ${catalina.base} path or the ${catalina.home} path contains a comma. +# Because double quotes are used for quoting, the double quote character +# may not appear in a path. +server.loader= + +# +# List of comma-separated paths defining the contents of the "shared" +# classloader. Prefixes should be used to define what is the repository type. +# Path may be relative to the CATALINA_BASE path or absolute. If left as blank, +# the "common" loader will be used as Catalina's "shared" loader. +# Examples: +# "foo": Add this folder as a class repository +# "foo/*.jar": Add all the JARs of the specified folder as class +# repositories +# "foo/bar.jar": Add bar.jar as a class repository +# Please note that for single jars, e.g. bar.jar, you need the URL form +# starting with file:. +# +# Note: Values may be enclosed in double quotes ("...") in case either the +# ${catalina.base} path or the ${catalina.home} path contains a comma. +# Because double quotes are used for quoting, the double quote character +# may not appear in a path. +shared.loader= + +# Default list of JAR files that should not be scanned using the JarScanner +# functionality. This is typically used to scan JARs for configuration +# information. JARs that do not contain such information may be excluded from +# the scan to speed up the scanning process. This is the default list. JARs on +# this list are excluded from all scans. The list must be a comma separated list +# of JAR file names. +# The list of JARs to skip may be over-ridden at a Context level for individual +# scan types by configuring a JarScanner with a nested JarScanFilter. +# The JARs listed below include: +# - Tomcat Bootstrap JARs +# - Tomcat API JARs +# - Catalina JARs +# - Jasper JARs +# - Tomcat JARs +# - Common non-Tomcat JARs +# - Test JARs (JUnit, Cobertura and dependencies) +tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\ +annotations-api.jar,\ +ant-junit*.jar,\ +ant-launcher*.jar,\ +ant*.jar,\ +asm-*.jar,\ +aspectj*.jar,\ +bcel*.jar,\ +biz.aQute.bnd*.jar,\ +bootstrap.jar,\ +catalina-ant.jar,\ +catalina-ha.jar,\ +catalina-ssi.jar,\ +catalina-storeconfig.jar,\ +catalina-tribes.jar,\ +catalina.jar,\ +cglib-*.jar,\ +cobertura-*.jar,\ +commons-beanutils*.jar,\ +commons-codec*.jar,\ +commons-collections*.jar,\ +commons-compress*.jar,\ +commons-daemon.jar,\ +commons-dbcp*.jar,\ +commons-digester*.jar,\ +commons-fileupload*.jar,\ +commons-httpclient*.jar,\ +commons-io*.jar,\ +commons-lang*.jar,\ +commons-logging*.jar,\ +commons-math*.jar,\ +commons-pool*.jar,\ +derby-*.jar,\ +dom4j-*.jar,\ +easymock-*.jar,\ +ecj-*.jar,\ +el-api.jar,\ +geronimo-spec-jaxrpc*.jar,\ +h2*.jar,\ +ha-api-*.jar,\ +hamcrest-*.jar,\ +hibernate*.jar,\ +httpclient*.jar,\ +icu4j-*.jar,\ +jasper-el.jar,\ +jasper.jar,\ +jaspic-api.jar,\ +jaxb-*.jar,\ +jaxen-*.jar,\ +jaxws-rt-*.jar,\ +jdom-*.jar,\ +jetty-*.jar,\ +jmx-tools.jar,\ +jmx.jar,\ +jsp-api.jar,\ +jstl.jar,\ +jta*.jar,\ +junit-*.jar,\ +junit.jar,\ +log4j*.jar,\ +mail*.jar,\ +objenesis-*.jar,\ +oraclepki.jar,\ +org.hamcrest.core_*.jar,\ +org.junit_*.jar,\ +oro-*.jar,\ +servlet-api-*.jar,\ +servlet-api.jar,\ +slf4j*.jar,\ +taglibs-standard-spec-*.jar,\ +tagsoup-*.jar,\ +tomcat-api.jar,\ +tomcat-coyote.jar,\ +tomcat-coyote-ffm.jar,\ +tomcat-dbcp.jar,\ +tomcat-i18n-*.jar,\ +tomcat-jdbc.jar,\ +tomcat-jni.jar,\ +tomcat-juli-adapters.jar,\ +tomcat-juli.jar,\ +tomcat-util-scan.jar,\ +tomcat-util.jar,\ +tomcat-websocket.jar,\ +tools.jar,\ +unboundid-ldapsdk-*.jar,\ +websocket-api.jar,\ +wsdl4j*.jar,\ +xercesImpl.jar,\ +xml-apis.jar,\ +xmlParserAPIs-*.jar,\ +xmlParserAPIs.jar,\ +xom-*.jar + +# Default list of JAR files that should be scanned that overrides the default +# jarsToSkip list above. This is typically used to include a specific JAR that +# has been excluded by a broad file name pattern in the jarsToSkip list. +# The list of JARs to scan may be over-ridden at a Context level for individual +# scan types by configuring a JarScanner with a nested JarScanFilter. +tomcat.util.scan.StandardJarScanFilter.jarsToScan=\ +log4j-taglib*.jar,\ +log4j-web*.jar,\ +log4javascript*.jar,\ +slf4j-taglib*.jar + +# String cache configuration. +tomcat.util.buf.StringCache.byte.enabled=true +#tomcat.util.buf.StringCache.char.enabled=true +#tomcat.util.buf.StringCache.trainThreshold=500000 +#tomcat.util.buf.StringCache.cacheSize=5000 + +# Disable use of some privilege blocks Tomcat doesn't need since calls to the +# code in question are always already inside a privilege block +org.apache.el.GET_CLASSLOADER_USE_PRIVILEGED=false diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/context.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/context.xml new file mode 100644 index 000000000..4f6fc0cd9 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/context.xml @@ -0,0 +1,31 @@ + + + + + + + + WEB-INF/web.xml + WEB-INF/tomcat-web.xml + ${catalina.base}/conf/web.xml + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xml new file mode 100644 index 000000000..cdebf8725 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xml @@ -0,0 +1,23 @@ + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xsd b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xsd new file mode 100644 index 000000000..1004a1191 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/jaspic-providers.xsd @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/logging.properties b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/logging.properties new file mode 100644 index 000000000..ee5644e32 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/logging.properties @@ -0,0 +1,76 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +handlers = 1catalina.org.apache.juli.AsyncFileHandler, 2localhost.org.apache.juli.AsyncFileHandler, 3manager.org.apache.juli.AsyncFileHandler, 4host-manager.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler + +.handlers = 1catalina.org.apache.juli.AsyncFileHandler, java.util.logging.ConsoleHandler + +############################################################ +# Handler specific properties. +# Describes specific configuration info for Handlers. +############################################################ + +1catalina.org.apache.juli.AsyncFileHandler.level = ALL +1catalina.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs +1catalina.org.apache.juli.AsyncFileHandler.prefix = catalina. +1catalina.org.apache.juli.AsyncFileHandler.maxDays = 90 +1catalina.org.apache.juli.AsyncFileHandler.encoding = UTF-8 + +2localhost.org.apache.juli.AsyncFileHandler.level = ALL +2localhost.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs +2localhost.org.apache.juli.AsyncFileHandler.prefix = localhost. +2localhost.org.apache.juli.AsyncFileHandler.maxDays = 90 +2localhost.org.apache.juli.AsyncFileHandler.encoding = UTF-8 + +3manager.org.apache.juli.AsyncFileHandler.level = ALL +3manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs +3manager.org.apache.juli.AsyncFileHandler.prefix = manager. +3manager.org.apache.juli.AsyncFileHandler.maxDays = 90 +3manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8 + +4host-manager.org.apache.juli.AsyncFileHandler.level = ALL +4host-manager.org.apache.juli.AsyncFileHandler.directory = ${catalina.base}/logs +4host-manager.org.apache.juli.AsyncFileHandler.prefix = host-manager. +4host-manager.org.apache.juli.AsyncFileHandler.maxDays = 90 +4host-manager.org.apache.juli.AsyncFileHandler.encoding = UTF-8 + +java.util.logging.ConsoleHandler.level = ALL +java.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter +java.util.logging.ConsoleHandler.encoding = UTF-8 + + +############################################################ +# Facility specific properties. +# Provides extra control for each logger. +############################################################ + +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = 2localhost.org.apache.juli.AsyncFileHandler + +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = 3manager.org.apache.juli.AsyncFileHandler + +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].level = INFO +org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/host-manager].handlers = 4host-manager.org.apache.juli.AsyncFileHandler + +# For example, set the org.apache.catalina.util.LifecycleBase logger to log +# each component that extends LifecycleBase changing state: +#org.apache.catalina.util.LifecycleBase.level = FINE + +# To see debug messages for HTTP/2 handling, uncomment the following line: +#org.apache.coyote.http2.level = FINE + +# To see debug messages for WebSocket handling, uncomment the following line: +#org.apache.tomcat.websocket.level = FINE diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/server.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/server.xml new file mode 100644 index 000000000..7dd4fca19 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/server.xml @@ -0,0 +1,250 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xml new file mode 100644 index 000000000..86b2a4afe --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xml @@ -0,0 +1,56 @@ + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xsd b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xsd new file mode 100644 index 000000000..6a3446c0e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/tomcat-users.xsd @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/web.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/web.xml new file mode 100644 index 000000000..2d8b4cb82 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/conf/web.xml @@ -0,0 +1,4755 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + default + org.apache.catalina.servlets.DefaultServlet + + debug + 0 + + + listings + false + + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + jsp + org.apache.jasper.servlet.JspServlet + + fork + false + + + xpoweredBy + false + + 3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + default + / + + + + + jsp + *.jsp + *.jspx + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 30 + + + + + + + + + + + + + 123 + application/vnd.lotus-1-2-3 + + + 3dml + text/vnd.in3d.3dml + + + 3ds + image/x-3ds + + + 3g2 + video/3gpp2 + + + 3gp + video/3gpp + + + 7z + application/x-7z-compressed + + + aab + application/x-authorware-bin + + + aac + audio/x-aac + + + aam + application/x-authorware-map + + + aas + application/x-authorware-seg + + + abs + audio/x-mpeg + + + abw + application/x-abiword + + + ac + application/pkix-attr-cert + + + acc + application/vnd.americandynamics.acc + + + ace + application/x-ace-compressed + + + acu + application/vnd.acucobol + + + acutc + application/vnd.acucorp + + + adp + audio/adpcm + + + aep + application/vnd.audiograph + + + afm + application/x-font-type1 + + + afp + application/vnd.ibm.modcap + + + ahead + application/vnd.ahead.space + + + ai + application/postscript + + + aif + audio/x-aiff + + + aifc + audio/x-aiff + + + aiff + audio/x-aiff + + + aim + application/x-aim + + + air + application/vnd.adobe.air-application-installer-package+zip + + + ait + application/vnd.dvb.ait + + + ami + application/vnd.amiga.ami + + + anx + application/annodex + + + apk + application/vnd.android.package-archive + + + appcache + text/cache-manifest + + + application + application/x-ms-application + + + apr + application/vnd.lotus-approach + + + arc + application/x-freearc + + + art + image/x-jg + + + asc + application/pgp-signature + + + asf + video/x-ms-asf + + + asm + text/x-asm + + + aso + application/vnd.accpac.simply.aso + + + asx + video/x-ms-asf + + + atc + application/vnd.acucorp + + + atom + application/atom+xml + + + atomcat + application/atomcat+xml + + + atomsvc + application/atomsvc+xml + + + atx + application/vnd.antix.game-component + + + au + audio/basic + + + avi + video/x-msvideo + + + avx + video/x-rad-screenplay + + + aw + application/applixware + + + axa + audio/annodex + + + axv + video/annodex + + + azf + application/vnd.airzip.filesecure.azf + + + azs + application/vnd.airzip.filesecure.azs + + + azw + application/vnd.amazon.ebook + + + bat + application/x-msdownload + + + bcpio + application/x-bcpio + + + bdf + application/x-font-bdf + + + bdm + application/vnd.syncml.dm+wbxml + + + bed + application/vnd.realvnc.bed + + + bh2 + application/vnd.fujitsu.oasysprs + + + bin + application/octet-stream + + + blb + application/x-blorb + + + blorb + application/x-blorb + + + bmi + application/vnd.bmi + + + bmp + image/bmp + + + body + text/html + + + book + application/vnd.framemaker + + + box + application/vnd.previewsystems.box + + + boz + application/x-bzip2 + + + bpk + application/octet-stream + + + btif + image/prs.btif + + + bz + application/x-bzip + + + bz2 + application/x-bzip2 + + + c + text/x-c + + + c11amc + application/vnd.cluetrust.cartomobile-config + + + c11amz + application/vnd.cluetrust.cartomobile-config-pkg + + + c4d + application/vnd.clonk.c4group + + + c4f + application/vnd.clonk.c4group + + + c4g + application/vnd.clonk.c4group + + + c4p + application/vnd.clonk.c4group + + + c4u + application/vnd.clonk.c4group + + + cab + application/vnd.ms-cab-compressed + + + caf + audio/x-caf + + + cap + application/vnd.tcpdump.pcap + + + car + application/vnd.curl.car + + + cat + application/vnd.ms-pki.seccat + + + cb7 + application/x-cbr + + + cba + application/x-cbr + + + cbr + application/x-cbr + + + cbt + application/x-cbr + + + cbz + application/x-cbr + + + cc + text/x-c + + + cct + application/x-director + + + ccxml + application/ccxml+xml + + + cdbcmsg + application/vnd.contact.cmsg + + + cdf + application/x-cdf + + + cdkey + application/vnd.mediastation.cdkey + + + cdmia + application/cdmi-capability + + + cdmic + application/cdmi-container + + + cdmid + application/cdmi-domain + + + cdmio + application/cdmi-object + + + cdmiq + application/cdmi-queue + + + cdx + chemical/x-cdx + + + cdxml + application/vnd.chemdraw+xml + + + cdy + application/vnd.cinderella + + + cer + application/pkix-cert + + + cfs + application/x-cfs-compressed + + + cgm + image/cgm + + + chat + application/x-chat + + + chm + application/vnd.ms-htmlhelp + + + chrt + application/vnd.kde.kchart + + + cif + chemical/x-cif + + + cii + application/vnd.anser-web-certificate-issue-initiation + + + cil + application/vnd.ms-artgalry + + + cla + application/vnd.claymore + + + class + application/java + + + clkk + application/vnd.crick.clicker.keyboard + + + clkp + application/vnd.crick.clicker.palette + + + clkt + application/vnd.crick.clicker.template + + + clkw + application/vnd.crick.clicker.wordbank + + + clkx + application/vnd.crick.clicker + + + clp + application/x-msclip + + + cmc + application/vnd.cosmocaller + + + cmdf + chemical/x-cmdf + + + cml + chemical/x-cml + + + cmp + application/vnd.yellowriver-custom-menu + + + cmx + image/x-cmx + + + cod + application/vnd.rim.cod + + + com + application/x-msdownload + + + conf + text/plain + + + cpio + application/x-cpio + + + cpp + text/x-c + + + cpt + application/mac-compactpro + + + crd + application/x-mscardfile + + + crl + application/pkix-crl + + + crt + application/x-x509-ca-cert + + + cryptonote + application/vnd.rig.cryptonote + + + csh + application/x-csh + + + csml + chemical/x-csml + + + csp + application/vnd.commonspace + + + css + text/css + + + cst + application/x-director + + + csv + text/csv + + + cu + application/cu-seeme + + + curl + text/vnd.curl + + + cww + application/prs.cww + + + cxt + application/x-director + + + cxx + text/x-c + + + dae + model/vnd.collada+xml + + + daf + application/vnd.mobius.daf + + + dart + application/vnd.dart + + + dataless + application/vnd.fdsn.seed + + + davmount + application/davmount+xml + + + dbk + application/docbook+xml + + + dcr + application/x-director + + + dcurl + text/vnd.curl.dcurl + + + dd2 + application/vnd.oma.dd2+xml + + + ddd + application/vnd.fujixerox.ddd + + + deb + application/x-debian-package + + + def + text/plain + + + deploy + application/octet-stream + + + der + application/x-x509-ca-cert + + + dfac + application/vnd.dreamfactory + + + dgc + application/x-dgc-compressed + + + dib + image/bmp + + + dic + text/x-c + + + dir + application/x-director + + + dis + application/vnd.mobius.dis + + + dist + application/octet-stream + + + distz + application/octet-stream + + + djv + image/vnd.djvu + + + djvu + image/vnd.djvu + + + dll + application/x-msdownload + + + dmg + application/x-apple-diskimage + + + dmp + application/vnd.tcpdump.pcap + + + dms + application/octet-stream + + + dna + application/vnd.dna + + + doc + application/msword + + + docm + application/vnd.ms-word.document.macroenabled.12 + + + docx + application/vnd.openxmlformats-officedocument.wordprocessingml.document + + + dot + application/msword + + + dotm + application/vnd.ms-word.template.macroenabled.12 + + + dotx + application/vnd.openxmlformats-officedocument.wordprocessingml.template + + + dp + application/vnd.osgi.dp + + + dpg + application/vnd.dpgraph + + + dra + audio/vnd.dra + + + dsc + text/prs.lines.tag + + + dssc + application/dssc+der + + + dtb + application/x-dtbook+xml + + + dtd + application/xml-dtd + + + dts + audio/vnd.dts + + + dtshd + audio/vnd.dts.hd + + + dump + application/octet-stream + + + dv + video/x-dv + + + dvb + video/vnd.dvb.file + + + dvi + application/x-dvi + + + dwf + model/vnd.dwf + + + dwg + image/vnd.dwg + + + dxf + image/vnd.dxf + + + dxp + application/vnd.spotfire.dxp + + + dxr + application/x-director + + + ecelp4800 + audio/vnd.nuera.ecelp4800 + + + ecelp7470 + audio/vnd.nuera.ecelp7470 + + + ecelp9600 + audio/vnd.nuera.ecelp9600 + + + ecma + application/ecmascript + + + edm + application/vnd.novadigm.edm + + + edx + application/vnd.novadigm.edx + + + efif + application/vnd.picsel + + + ei6 + application/vnd.pg.osasli + + + elc + application/octet-stream + + + emf + application/x-msmetafile + + + eml + message/rfc822 + + + emma + application/emma+xml + + + emz + application/x-msmetafile + + + eol + audio/vnd.digital-winds + + + eot + application/vnd.ms-fontobject + + + eps + application/postscript + + + epub + application/epub+zip + + + es3 + application/vnd.eszigno3+xml + + + esa + application/vnd.osgi.subsystem + + + esf + application/vnd.epson.esf + + + et3 + application/vnd.eszigno3+xml + + + etx + text/x-setext + + + eva + application/x-eva + + + evy + application/x-envoy + + + exe + application/octet-stream + + + exi + application/exi + + + ext + application/vnd.novadigm.ext + + + ez + application/andrew-inset + + + ez2 + application/vnd.ezpix-album + + + ez3 + application/vnd.ezpix-package + + + f + text/x-fortran + + + f4v + video/x-f4v + + + f77 + text/x-fortran + + + f90 + text/x-fortran + + + fbs + image/vnd.fastbidsheet + + + fcdt + application/vnd.adobe.formscentral.fcdt + + + fcs + application/vnd.isac.fcs + + + fdf + application/vnd.fdf + + + fe_launch + application/vnd.denovo.fcselayout-link + + + fg5 + application/vnd.fujitsu.oasysgp + + + fgd + application/x-director + + + fh + image/x-freehand + + + fh4 + image/x-freehand + + + fh5 + image/x-freehand + + + fh7 + image/x-freehand + + + fhc + image/x-freehand + + + fig + application/x-xfig + + + flac + audio/flac + + + fli + video/x-fli + + + flo + application/vnd.micrografx.flo + + + flv + video/x-flv + + + flw + application/vnd.kde.kivio + + + flx + text/vnd.fmi.flexstor + + + fly + text/vnd.fly + + + fm + application/vnd.framemaker + + + fnc + application/vnd.frogans.fnc + + + for + text/x-fortran + + + fpx + image/vnd.fpx + + + frame + application/vnd.framemaker + + + fsc + application/vnd.fsc.weblaunch + + + fst + image/vnd.fst + + + ftc + application/vnd.fluxtime.clip + + + fti + application/vnd.anser-web-funds-transfer-initiation + + + fvt + video/vnd.fvt + + + fxp + application/vnd.adobe.fxp + + + fxpl + application/vnd.adobe.fxp + + + fzs + application/vnd.fuzzysheet + + + g2w + application/vnd.geoplan + + + g3 + image/g3fax + + + g3w + application/vnd.geospace + + + gac + application/vnd.groove-account + + + gam + application/x-tads + + + gbr + application/rpki-ghostbusters + + + gca + application/x-gca-compressed + + + gdl + model/vnd.gdl + + + geo + application/vnd.dynageo + + + gex + application/vnd.geometry-explorer + + + ggb + application/vnd.geogebra.file + + + ggs + application/vnd.geogebra.slides + + + ggt + application/vnd.geogebra.tool + + + ghf + application/vnd.groove-help + + + gif + image/gif + + + gim + application/vnd.groove-identity-message + + + gml + application/gml+xml + + + gmx + application/vnd.gmx + + + gnumeric + application/x-gnumeric + + + gph + application/vnd.flographit + + + gpx + application/gpx+xml + + + gqf + application/vnd.grafeq + + + gqs + application/vnd.grafeq + + + gram + application/srgs + + + gramps + application/x-gramps-xml + + + gre + application/vnd.geometry-explorer + + + grv + application/vnd.groove-injector + + + grxml + application/srgs+xml + + + gsf + application/x-font-ghostscript + + + gtar + application/x-gtar + + + gtm + application/vnd.groove-tool-message + + + gtw + model/vnd.gtw + + + gv + text/vnd.graphviz + + + gxf + application/gxf + + + gxt + application/vnd.geonext + + + gz + application/x-gzip + + + h + text/x-c + + + h261 + video/h261 + + + h263 + video/h263 + + + h264 + video/h264 + + + hal + application/vnd.hal+xml + + + hbci + application/vnd.hbci + + + hdf + application/x-hdf + + + hh + text/x-c + + + hlp + application/winhlp + + + hpgl + application/vnd.hp-hpgl + + + hpid + application/vnd.hp-hpid + + + hps + application/vnd.hp-hps + + + hqx + application/mac-binhex40 + + + htc + text/x-component + + + htke + application/vnd.kenameaapp + + + htm + text/html + + + html + text/html + + + hvd + application/vnd.yamaha.hv-dic + + + hvp + application/vnd.yamaha.hv-voice + + + hvs + application/vnd.yamaha.hv-script + + + i2g + application/vnd.intergeo + + + icc + application/vnd.iccprofile + + + ice + x-conference/x-cooltalk + + + icm + application/vnd.iccprofile + + + ico + image/x-icon + + + ics + text/calendar + + + ief + image/ief + + + ifb + text/calendar + + + ifm + application/vnd.shana.informed.formdata + + + iges + model/iges + + + igl + application/vnd.igloader + + + igm + application/vnd.insors.igm + + + igs + model/iges + + + igx + application/vnd.micrografx.igx + + + iif + application/vnd.shana.informed.interchange + + + imp + application/vnd.accpac.simply.imp + + + ims + application/vnd.ms-ims + + + in + text/plain + + + ink + application/inkml+xml + + + inkml + application/inkml+xml + + + install + application/x-install-instructions + + + iota + application/vnd.astraea-software.iota + + + ipfix + application/ipfix + + + ipk + application/vnd.shana.informed.package + + + irm + application/vnd.ibm.rights-management + + + irp + application/vnd.irepository.package+xml + + + iso + application/x-iso9660-image + + + itp + application/vnd.shana.informed.formtemplate + + + ivp + application/vnd.immervision-ivp + + + ivu + application/vnd.immervision-ivu + + + jad + text/vnd.sun.j2me.app-descriptor + + + jam + application/vnd.jam + + + jar + application/java-archive + + + java + text/x-java-source + + + jisp + application/vnd.jisp + + + jlt + application/vnd.hp-jlyt + + + jnlp + application/x-java-jnlp-file + + + joda + application/vnd.joost.joda-archive + + + jpe + image/jpeg + + + jpeg + image/jpeg + + + jpg + image/jpeg + + + jpgm + video/jpm + + + jpgv + video/jpeg + + + jpm + video/jpm + + + js + text/javascript + + + jsf + text/plain + + + json + application/json + + + jsonml + application/jsonml+json + + + jspf + text/plain + + + kar + audio/midi + + + karbon + application/vnd.kde.karbon + + + kfo + application/vnd.kde.kformula + + + kia + application/vnd.kidspiration + + + kml + application/vnd.google-earth.kml+xml + + + kmz + application/vnd.google-earth.kmz + + + kne + application/vnd.kinar + + + knp + application/vnd.kinar + + + kon + application/vnd.kde.kontour + + + kpr + application/vnd.kde.kpresenter + + + kpt + application/vnd.kde.kpresenter + + + kpxx + application/vnd.ds-keypoint + + + ksp + application/vnd.kde.kspread + + + ktr + application/vnd.kahootz + + + ktx + image/ktx + + + ktz + application/vnd.kahootz + + + kwd + application/vnd.kde.kword + + + kwt + application/vnd.kde.kword + + + lasxml + application/vnd.las.las+xml + + + latex + application/x-latex + + + lbd + application/vnd.llamagraphics.life-balance.desktop + + + lbe + application/vnd.llamagraphics.life-balance.exchange+xml + + + les + application/vnd.hhe.lesson-player + + + lha + application/x-lzh-compressed + + + link66 + application/vnd.route66.link66+xml + + + list + text/plain + + + list3820 + application/vnd.ibm.modcap + + + listafp + application/vnd.ibm.modcap + + + lnk + application/x-ms-shortcut + + + log + text/plain + + + lostxml + application/lost+xml + + + lrf + application/octet-stream + + + lrm + application/vnd.ms-lrm + + + ltf + application/vnd.frogans.ltf + + + lvp + audio/vnd.lucent.voice + + + lwp + application/vnd.lotus-wordpro + + + lzh + application/x-lzh-compressed + + + m13 + application/x-msmediaview + + + m14 + application/x-msmediaview + + + m1v + video/mpeg + + + m21 + application/mp21 + + + m2a + audio/mpeg + + + m2v + video/mpeg + + + m3a + audio/mpeg + + + m3u + audio/x-mpegurl + + + m3u8 + application/vnd.apple.mpegurl + + + m4a + audio/mp4 + + + m4b + audio/mp4 + + + m4r + audio/mp4 + + + m4u + video/vnd.mpegurl + + + m4v + video/mp4 + + + ma + application/mathematica + + + mac + image/x-macpaint + + + mads + application/mads+xml + + + mag + application/vnd.ecowin.chart + + + maker + application/vnd.framemaker + + + man + text/troff + + + mar + application/octet-stream + + + mathml + application/mathml+xml + + + mb + application/mathematica + + + mbk + application/vnd.mobius.mbk + + + mbox + application/mbox + + + mc1 + application/vnd.medcalcdata + + + mcd + application/vnd.mcd + + + mcurl + text/vnd.curl.mcurl + + + mdb + application/x-msaccess + + + mdi + image/vnd.ms-modi + + + me + text/troff + + + mesh + model/mesh + + + meta4 + application/metalink4+xml + + + metalink + application/metalink+xml + + + mets + application/mets+xml + + + mfm + application/vnd.mfmp + + + mft + application/rpki-manifest + + + mgp + application/vnd.osgeo.mapguide.package + + + mgz + application/vnd.proteus.magazine + + + mid + audio/midi + + + midi + audio/midi + + + mie + application/x-mie + + + mif + application/x-mif + + + mime + message/rfc822 + + + mj2 + video/mj2 + + + mjp2 + video/mj2 + + + mjs + text/javascript + + + mk3d + video/x-matroska + + + mka + audio/x-matroska + + + mks + video/x-matroska + + + mkv + video/x-matroska + + + mlp + application/vnd.dolby.mlp + + + mmd + application/vnd.chipnuts.karaoke-mmd + + + mmf + application/vnd.smaf + + + mmr + image/vnd.fujixerox.edmics-mmr + + + mng + video/x-mng + + + mny + application/x-msmoney + + + mobi + application/x-mobipocket-ebook + + + mods + application/mods+xml + + + mov + video/quicktime + + + movie + video/x-sgi-movie + + + mp1 + audio/mpeg + + + mp2 + audio/mpeg + + + mp21 + application/mp21 + + + mp2a + audio/mpeg + + + mp3 + audio/mpeg + + + mp4 + video/mp4 + + + mp4a + audio/mp4 + + + mp4s + application/mp4 + + + mp4v + video/mp4 + + + mpa + audio/mpeg + + + mpc + application/vnd.mophun.certificate + + + mpe + video/mpeg + + + mpeg + video/mpeg + + + mpega + audio/x-mpeg + + + mpg + video/mpeg + + + mpg4 + video/mp4 + + + mpga + audio/mpeg + + + mpkg + application/vnd.apple.installer+xml + + + mpm + application/vnd.blueice.multipass + + + mpn + application/vnd.mophun.application + + + mpp + application/vnd.ms-project + + + mpt + application/vnd.ms-project + + + mpv2 + video/mpeg2 + + + mpy + application/vnd.ibm.minipay + + + mqy + application/vnd.mobius.mqy + + + mrc + application/marc + + + mrcx + application/marcxml+xml + + + ms + text/troff + + + mscml + application/mediaservercontrol+xml + + + mseed + application/vnd.fdsn.mseed + + + mseq + application/vnd.mseq + + + msf + application/vnd.epson.msf + + + msh + model/mesh + + + msi + application/x-msdownload + + + msl + application/vnd.mobius.msl + + + msty + application/vnd.muvee.style + + + mts + model/vnd.mts + + + mus + application/vnd.musician + + + musicxml + application/vnd.recordare.musicxml+xml + + + mvb + application/x-msmediaview + + + mwf + application/vnd.mfer + + + mxf + application/mxf + + + mxl + application/vnd.recordare.musicxml + + + mxml + application/xv+xml + + + mxs + application/vnd.triscape.mxs + + + mxu + video/vnd.mpegurl + + + n-gage + application/vnd.nokia.n-gage.symbian.install + + + n3 + text/n3 + + + nb + application/mathematica + + + nbp + application/vnd.wolfram.player + + + nc + application/x-netcdf + + + ncx + application/x-dtbncx+xml + + + nfo + text/x-nfo + + + ngdat + application/vnd.nokia.n-gage.data + + + nitf + application/vnd.nitf + + + nlu + application/vnd.neurolanguage.nlu + + + nml + application/vnd.enliven + + + nnd + application/vnd.noblenet-directory + + + nns + application/vnd.noblenet-sealer + + + nnw + application/vnd.noblenet-web + + + npx + image/vnd.net-fpx + + + nsc + application/x-conference + + + nsf + application/vnd.lotus-notes + + + ntf + application/vnd.nitf + + + nzb + application/x-nzb + + + oa2 + application/vnd.fujitsu.oasys2 + + + oa3 + application/vnd.fujitsu.oasys3 + + + oas + application/vnd.fujitsu.oasys + + + obd + application/x-msbinder + + + obj + application/x-tgif + + + oda + application/oda + + + + odb + application/vnd.oasis.opendocument.database + + + + odc + application/vnd.oasis.opendocument.chart + + + + odf + application/vnd.oasis.opendocument.formula + + + odft + application/vnd.oasis.opendocument.formula-template + + + + odg + application/vnd.oasis.opendocument.graphics + + + + odi + application/vnd.oasis.opendocument.image + + + + odm + application/vnd.oasis.opendocument.text-master + + + + odp + application/vnd.oasis.opendocument.presentation + + + + ods + application/vnd.oasis.opendocument.spreadsheet + + + + odt + application/vnd.oasis.opendocument.text + + + oga + audio/ogg + + + ogg + audio/ogg + + + ogv + video/ogg + + + + ogx + application/ogg + + + omdoc + application/omdoc+xml + + + onepkg + application/onenote + + + onetmp + application/onenote + + + onetoc + application/onenote + + + onetoc2 + application/onenote + + + opf + application/oebps-package+xml + + + opml + text/x-opml + + + oprc + application/vnd.palm + + + opus + audio/ogg + + + org + application/vnd.lotus-organizer + + + osf + application/vnd.yamaha.openscoreformat + + + osfpvg + application/vnd.yamaha.openscoreformat.osfpvg+xml + + + otc + application/vnd.oasis.opendocument.chart-template + + + otf + font/otf + + + + otg + application/vnd.oasis.opendocument.graphics-template + + + + oth + application/vnd.oasis.opendocument.text-web + + + oti + application/vnd.oasis.opendocument.image-template + + + + otp + application/vnd.oasis.opendocument.presentation-template + + + + ots + application/vnd.oasis.opendocument.spreadsheet-template + + + + ott + application/vnd.oasis.opendocument.text-template + + + oxps + application/oxps + + + oxt + application/vnd.openofficeorg.extension + + + p + text/x-pascal + + + p10 + application/pkcs10 + + + p12 + application/x-pkcs12 + + + p7b + application/x-pkcs7-certificates + + + p7c + application/pkcs7-mime + + + p7m + application/pkcs7-mime + + + p7r + application/x-pkcs7-certreqresp + + + p7s + application/pkcs7-signature + + + p8 + application/pkcs8 + + + pas + text/x-pascal + + + paw + application/vnd.pawaafile + + + pbd + application/vnd.powerbuilder6 + + + pbm + image/x-portable-bitmap + + + pcap + application/vnd.tcpdump.pcap + + + pcf + application/x-font-pcf + + + pcl + application/vnd.hp-pcl + + + pclxl + application/vnd.hp-pclxl + + + pct + image/pict + + + pcurl + application/vnd.curl.pcurl + + + pcx + image/x-pcx + + + pdb + application/vnd.palm + + + pdf + application/pdf + + + pfa + application/x-font-type1 + + + pfb + application/x-font-type1 + + + pfm + application/x-font-type1 + + + pfr + application/font-tdpfr + + + pfx + application/x-pkcs12 + + + pgm + image/x-portable-graymap + + + pgn + application/x-chess-pgn + + + pgp + application/pgp-encrypted + + + pic + image/pict + + + pict + image/pict + + + pkg + application/octet-stream + + + pki + application/pkixcmp + + + pkipath + application/pkix-pkipath + + + plb + application/vnd.3gpp.pic-bw-large + + + plc + application/vnd.mobius.plc + + + plf + application/vnd.pocketlearn + + + pls + audio/x-scpls + + + pml + application/vnd.ctc-posml + + + png + image/png + + + pnm + image/x-portable-anymap + + + pnt + image/x-macpaint + + + portpkg + application/vnd.macports.portpkg + + + pot + application/vnd.ms-powerpoint + + + potm + application/vnd.ms-powerpoint.template.macroenabled.12 + + + potx + application/vnd.openxmlformats-officedocument.presentationml.template + + + ppam + application/vnd.ms-powerpoint.addin.macroenabled.12 + + + ppd + application/vnd.cups-ppd + + + ppm + image/x-portable-pixmap + + + pps + application/vnd.ms-powerpoint + + + ppsm + application/vnd.ms-powerpoint.slideshow.macroenabled.12 + + + ppsx + application/vnd.openxmlformats-officedocument.presentationml.slideshow + + + ppt + application/vnd.ms-powerpoint + + + pptm + application/vnd.ms-powerpoint.presentation.macroenabled.12 + + + pptx + application/vnd.openxmlformats-officedocument.presentationml.presentation + + + pqa + application/vnd.palm + + + prc + application/x-mobipocket-ebook + + + pre + application/vnd.lotus-freelance + + + prf + application/pics-rules + + + ps + application/postscript + + + psb + application/vnd.3gpp.pic-bw-small + + + psd + image/vnd.adobe.photoshop + + + psf + application/x-font-linux-psf + + + pskcxml + application/pskc+xml + + + ptid + application/vnd.pvi.ptid1 + + + pub + application/x-mspublisher + + + pvb + application/vnd.3gpp.pic-bw-var + + + pwn + application/vnd.3m.post-it-notes + + + pya + audio/vnd.ms-playready.media.pya + + + pyv + video/vnd.ms-playready.media.pyv + + + qam + application/vnd.epson.quickanime + + + qbo + application/vnd.intu.qbo + + + qfx + application/vnd.intu.qfx + + + qps + application/vnd.publishare-delta-tree + + + qt + video/quicktime + + + qti + image/x-quicktime + + + qtif + image/x-quicktime + + + qwd + application/vnd.quark.quarkxpress + + + qwt + application/vnd.quark.quarkxpress + + + qxb + application/vnd.quark.quarkxpress + + + qxd + application/vnd.quark.quarkxpress + + + qxl + application/vnd.quark.quarkxpress + + + qxt + application/vnd.quark.quarkxpress + + + ra + audio/x-pn-realaudio + + + ram + audio/x-pn-realaudio + + + rar + application/x-rar-compressed + + + ras + image/x-cmu-raster + + + rcprofile + application/vnd.ipunplugged.rcprofile + + + rdf + application/rdf+xml + + + rdz + application/vnd.data-vision.rdz + + + rep + application/vnd.businessobjects + + + res + application/x-dtbresource+xml + + + rgb + image/x-rgb + + + rif + application/reginfo+xml + + + rip + audio/vnd.rip + + + ris + application/x-research-info-systems + + + rl + application/resource-lists+xml + + + rlc + image/vnd.fujixerox.edmics-rlc + + + rld + application/resource-lists-diff+xml + + + rm + application/vnd.rn-realmedia + + + rmi + audio/midi + + + rmp + audio/x-pn-realaudio-plugin + + + rms + application/vnd.jcp.javame.midlet-rms + + + rmvb + application/vnd.rn-realmedia-vbr + + + rnc + application/relax-ng-compact-syntax + + + roa + application/rpki-roa + + + roff + text/troff + + + rp9 + application/vnd.cloanto.rp9 + + + rpss + application/vnd.nokia.radio-presets + + + rpst + application/vnd.nokia.radio-preset + + + rq + application/sparql-query + + + rs + application/rls-services+xml + + + rsd + application/rsd+xml + + + rss + application/rss+xml + + + rtf + application/rtf + + + rtx + text/richtext + + + s + text/x-asm + + + s3m + audio/s3m + + + saf + application/vnd.yamaha.smaf-audio + + + sbml + application/sbml+xml + + + sc + application/vnd.ibm.secure-container + + + scd + application/x-msschedule + + + scm + application/vnd.lotus-screencam + + + scq + application/scvp-cv-request + + + scs + application/scvp-cv-response + + + scurl + text/vnd.curl.scurl + + + sda + application/vnd.stardivision.draw + + + sdc + application/vnd.stardivision.calc + + + sdd + application/vnd.stardivision.impress + + + sdkd + application/vnd.solent.sdkm+xml + + + sdkm + application/vnd.solent.sdkm+xml + + + sdp + application/sdp + + + sdw + application/vnd.stardivision.writer + + + see + application/vnd.seemail + + + seed + application/vnd.fdsn.seed + + + sema + application/vnd.sema + + + semd + application/vnd.semd + + + semf + application/vnd.semf + + + ser + application/java-serialized-object + + + setpay + application/set-payment-initiation + + + setreg + application/set-registration-initiation + + + sfd-hdstx + application/vnd.hydrostatix.sof-data + + + sfs + application/vnd.spotfire.sfs + + + sfv + text/x-sfv + + + sgi + image/sgi + + + sgl + application/vnd.stardivision.writer-global + + + sgm + text/sgml + + + sgml + text/sgml + + + sh + application/x-sh + + + shar + application/x-shar + + + shf + application/shf+xml + + + + sid + image/x-mrsid-image + + + sig + application/pgp-signature + + + sil + audio/silk + + + silo + model/mesh + + + sis + application/vnd.symbian.install + + + sisx + application/vnd.symbian.install + + + sit + application/x-stuffit + + + sitx + application/x-stuffitx + + + skd + application/vnd.koan + + + skm + application/vnd.koan + + + skp + application/vnd.koan + + + skt + application/vnd.koan + + + sldm + application/vnd.ms-powerpoint.slide.macroenabled.12 + + + sldx + application/vnd.openxmlformats-officedocument.presentationml.slide + + + slt + application/vnd.epson.salt + + + sm + application/vnd.stepmania.stepchart + + + smf + application/vnd.stardivision.math + + + smi + application/smil+xml + + + smil + application/smil+xml + + + smv + video/x-smv + + + smzip + application/vnd.stepmania.package + + + snd + audio/basic + + + snf + application/x-font-snf + + + so + application/octet-stream + + + spc + application/x-pkcs7-certificates + + + spf + application/vnd.yamaha.smaf-phrase + + + spl + application/x-futuresplash + + + spot + text/vnd.in3d.spot + + + spp + application/scvp-vp-response + + + spq + application/scvp-vp-request + + + spx + audio/ogg + + + sql + application/x-sql + + + src + application/x-wais-source + + + srt + application/x-subrip + + + sru + application/sru+xml + + + srx + application/sparql-results+xml + + + ssdl + application/ssdl+xml + + + sse + application/vnd.kodak-descriptor + + + ssf + application/vnd.epson.ssf + + + ssml + application/ssml+xml + + + st + application/vnd.sailingtracker.track + + + stc + application/vnd.sun.xml.calc.template + + + std + application/vnd.sun.xml.draw.template + + + stf + application/vnd.wt.stf + + + sti + application/vnd.sun.xml.impress.template + + + stk + application/hyperstudio + + + stl + application/vnd.ms-pki.stl + + + str + application/vnd.pg.format + + + stw + application/vnd.sun.xml.writer.template + + + sub + text/vnd.dvb.subtitle + + + sus + application/vnd.sus-calendar + + + susp + application/vnd.sus-calendar + + + sv4cpio + application/x-sv4cpio + + + sv4crc + application/x-sv4crc + + + svc + application/vnd.dvb.service + + + svd + application/vnd.svd + + + svg + image/svg+xml + + + svgz + image/svg+xml + + + swa + application/x-director + + + swf + application/x-shockwave-flash + + + swi + application/vnd.aristanetworks.swi + + + sxc + application/vnd.sun.xml.calc + + + sxd + application/vnd.sun.xml.draw + + + sxg + application/vnd.sun.xml.writer.global + + + sxi + application/vnd.sun.xml.impress + + + sxm + application/vnd.sun.xml.math + + + sxw + application/vnd.sun.xml.writer + + + t + text/troff + + + t3 + application/x-t3vm-image + + + taglet + application/vnd.mynfc + + + tao + application/vnd.tao.intent-module-archive + + + tar + application/x-tar + + + tcap + application/vnd.3gpp2.tcap + + + tcl + application/x-tcl + + + teacher + application/vnd.smart.teacher + + + tei + application/tei+xml + + + teicorpus + application/tei+xml + + + tex + application/x-tex + + + texi + application/x-texinfo + + + texinfo + application/x-texinfo + + + text + text/plain + + + tfi + application/thraud+xml + + + tfm + application/x-tex-tfm + + + tga + image/x-tga + + + thmx + application/vnd.ms-officetheme + + + tif + image/tiff + + + tiff + image/tiff + + + tmo + application/vnd.tmobile-livetv + + + torrent + application/x-bittorrent + + + tpl + application/vnd.groove-tool-template + + + tpt + application/vnd.trid.tpt + + + tr + text/troff + + + tra + application/vnd.trueapp + + + trm + application/x-msterminal + + + tsd + application/timestamped-data + + + tsv + text/tab-separated-values + + + ttc + font/collection + + + ttf + font/ttf + + + ttl + text/turtle + + + twd + application/vnd.simtech-mindmapper + + + twds + application/vnd.simtech-mindmapper + + + txd + application/vnd.genomatix.tuxedo + + + txf + application/vnd.mobius.txf + + + txt + text/plain + + + u32 + application/x-authorware-bin + + + udeb + application/x-debian-package + + + ufd + application/vnd.ufdl + + + ufdl + application/vnd.ufdl + + + ulw + audio/basic + + + ulx + application/x-glulx + + + umj + application/vnd.umajin + + + unityweb + application/vnd.unity + + + uoml + application/vnd.uoml+xml + + + uri + text/uri-list + + + uris + text/uri-list + + + urls + text/uri-list + + + ustar + application/x-ustar + + + utz + application/vnd.uiq.theme + + + uu + text/x-uuencode + + + uva + audio/vnd.dece.audio + + + uvd + application/vnd.dece.data + + + uvf + application/vnd.dece.data + + + uvg + image/vnd.dece.graphic + + + uvh + video/vnd.dece.hd + + + uvi + image/vnd.dece.graphic + + + uvm + video/vnd.dece.mobile + + + uvp + video/vnd.dece.pd + + + uvs + video/vnd.dece.sd + + + uvt + application/vnd.dece.ttml+xml + + + uvu + video/vnd.uvvu.mp4 + + + uvv + video/vnd.dece.video + + + uvva + audio/vnd.dece.audio + + + uvvd + application/vnd.dece.data + + + uvvf + application/vnd.dece.data + + + uvvg + image/vnd.dece.graphic + + + uvvh + video/vnd.dece.hd + + + uvvi + image/vnd.dece.graphic + + + uvvm + video/vnd.dece.mobile + + + uvvp + video/vnd.dece.pd + + + uvvs + video/vnd.dece.sd + + + uvvt + application/vnd.dece.ttml+xml + + + uvvu + video/vnd.uvvu.mp4 + + + uvvv + video/vnd.dece.video + + + uvvx + application/vnd.dece.unspecified + + + uvvz + application/vnd.dece.zip + + + uvx + application/vnd.dece.unspecified + + + uvz + application/vnd.dece.zip + + + vcard + text/vcard + + + vcd + application/x-cdlink + + + vcf + text/x-vcard + + + vcg + application/vnd.groove-vcard + + + vcs + text/x-vcalendar + + + vcx + application/vnd.vcx + + + vis + application/vnd.visionary + + + viv + video/vnd.vivo + + + vob + video/x-ms-vob + + + vor + application/vnd.stardivision.writer + + + vox + application/x-authorware-bin + + + vrml + model/vrml + + + vsd + application/vnd.visio + + + vsf + application/vnd.vsf + + + vss + application/vnd.visio + + + vst + application/vnd.visio + + + vsw + application/vnd.visio + + + vtu + model/vnd.vtu + + + vxml + application/voicexml+xml + + + w3d + application/x-director + + + wad + application/x-doom + + + wasm + application/wasm + + + wav + audio/x-wav + + + wax + audio/x-ms-wax + + + + wbmp + image/vnd.wap.wbmp + + + wbs + application/vnd.criticaltools.wbs+xml + + + wbxml + application/vnd.wap.wbxml + + + wcm + application/vnd.ms-works + + + wdb + application/vnd.ms-works + + + wdp + image/vnd.ms-photo + + + weba + audio/webm + + + webm + video/webm + + + webp + image/webp + + + wg + application/vnd.pmi.widget + + + wgt + application/widget + + + wks + application/vnd.ms-works + + + wm + video/x-ms-wm + + + wma + audio/x-ms-wma + + + wmd + application/x-ms-wmd + + + wmf + application/x-msmetafile + + + + wml + text/vnd.wap.wml + + + + wmlc + application/vnd.wap.wmlc + + + + wmls + text/vnd.wap.wmlscript + + + + wmlsc + application/vnd.wap.wmlscriptc + + + wmv + video/x-ms-wmv + + + wmx + video/x-ms-wmx + + + wmz + application/x-msmetafile + + + woff + font/woff + + + woff2 + font/woff2 + + + wpd + application/vnd.wordperfect + + + wpl + application/vnd.ms-wpl + + + wps + application/vnd.ms-works + + + wqd + application/vnd.wqd + + + wri + application/x-mswrite + + + wrl + model/vrml + + + wsdl + application/wsdl+xml + + + wspolicy + application/wspolicy+xml + + + wtb + application/vnd.webturbo + + + wvx + video/x-ms-wvx + + + x32 + application/x-authorware-bin + + + x3d + model/x3d+xml + + + x3db + model/x3d+binary + + + x3dbz + model/x3d+binary + + + x3dv + model/x3d+vrml + + + x3dvz + model/x3d+vrml + + + x3dz + model/x3d+xml + + + xaml + application/xaml+xml + + + xap + application/x-silverlight-app + + + xar + application/vnd.xara + + + xbap + application/x-ms-xbap + + + xbd + application/vnd.fujixerox.docuworks.binder + + + xbm + image/x-xbitmap + + + xdf + application/xcap-diff+xml + + + xdm + application/vnd.syncml.dm+xml + + + xdp + application/vnd.adobe.xdp+xml + + + xdssc + application/dssc+xml + + + xdw + application/vnd.fujixerox.docuworks + + + xenc + application/xenc+xml + + + xer + application/patch-ops-error+xml + + + xfdf + application/vnd.adobe.xfdf + + + xfdl + application/vnd.xfdl + + + xht + application/xhtml+xml + + + xhtml + application/xhtml+xml + + + xhvml + application/xv+xml + + + xif + image/vnd.xiff + + + xla + application/vnd.ms-excel + + + xlam + application/vnd.ms-excel.addin.macroenabled.12 + + + xlc + application/vnd.ms-excel + + + xlf + application/x-xliff+xml + + + xlm + application/vnd.ms-excel + + + xls + application/vnd.ms-excel + + + xlsb + application/vnd.ms-excel.sheet.binary.macroenabled.12 + + + xlsm + application/vnd.ms-excel.sheet.macroenabled.12 + + + xlsx + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + + + xlt + application/vnd.ms-excel + + + xltm + application/vnd.ms-excel.template.macroenabled.12 + + + xltx + application/vnd.openxmlformats-officedocument.spreadsheetml.template + + + xlw + application/vnd.ms-excel + + + xm + audio/xm + + + xml + application/xml + + + xo + application/vnd.olpc-sugar + + + xop + application/xop+xml + + + xpi + application/x-xpinstall + + + xpl + application/xproc+xml + + + xpm + image/x-xpixmap + + + xpr + application/vnd.is-xpr + + + xps + application/vnd.ms-xpsdocument + + + xpw + application/vnd.intercon.formnet + + + xpx + application/vnd.intercon.formnet + + + xsl + application/xml + + + xslt + application/xslt+xml + + + xsm + application/vnd.syncml+xml + + + xspf + application/xspf+xml + + + xul + application/vnd.mozilla.xul+xml + + + xvm + application/xv+xml + + + xvml + application/xv+xml + + + xwd + image/x-xwindowdump + + + xyz + chemical/x-xyz + + + xz + application/x-xz + + + yang + application/yang + + + yin + application/yin+xml + + + z + application/x-compress + + + z1 + application/x-zmachine + + + z2 + application/x-zmachine + + + z3 + application/x-zmachine + + + z4 + application/x-zmachine + + + z5 + application/x-zmachine + + + z6 + application/x-zmachine + + + z7 + application/x-zmachine + + + z8 + application/x-zmachine + + + zaz + application/vnd.zzazz.deck+xml + + + zip + application/zip + + + zir + application/vnd.zul + + + zirz + application/vnd.zul + + + zmm + application/vnd.handheld-entertainment+xml + + + + + + + + + + + + + + + + + + index.html + index.htm + index.jsp + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-15.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-15.txt new file mode 100644 index 000000000..e7621485a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-15.txt @@ -0,0 +1,45 @@ +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:13:31 +0530] "GET /endpoint HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:13:31 +0530] "GET /endpoint HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:13:31 +0530] "GET /favicon.ico HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:13:32 +0530] "GET /endpoint HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:22:14 +0530] "GET /endpoint HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:22:14 +0530] "GET /favicon.ico HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:28:00 +0530] "GET /api/fs/consent/admin/create HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:28:08 +0530] "GET /api/fs/consent/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:28:29 +0530] "GET /endpoint/api/fs/consent/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:29:14 +0530] "GET /api/fs/consent/admin/create HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:29:27 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:31:15 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:31:20 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:31:22 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:31:32 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:31:45 +0530] "GET /endpoint HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:35:25 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:35:26 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:35:31 +0530] "GET /endpoint/api/fs/consent/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:35:37 +0530] "GET /endpoint HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:38:01 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:38:01 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:47:13 +0530] "GET /endpoint/api/fs/consent/admin/create HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:47:52 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 168 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:59:21 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:18:59:55 +0530] "GET /endpoint/admin/create HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:00:23 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:12:14 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:12:18 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 168 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:15:38 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 168 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:18:04 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 168 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:18:30 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:44:21 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:44:44 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:45:56 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:46:38 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:46:38 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:47:57 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:48:39 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:48:58 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:49:15 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:50:59 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 4303 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:19:58:12 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 6518 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:20:15:27 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 6518 +0:0:0:0:0:0:0:1 - - [15/Feb/2025:20:18:41 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 6518 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-16.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-16.txt new file mode 100644 index 000000000..a49b27ace --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-16.txt @@ -0,0 +1,38 @@ +0:0:0:0:0:0:0:1 - - [16/Feb/2025:16:50:17 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 6518 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:16:58:29 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:16:59:40 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:01:38 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:01:53 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:02:49 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:19:01 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:36:56 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 14504 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:37:23 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 15459 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:42:34 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 10551 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:17:44:44 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 10563 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:01:52 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:03:08 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:03:37 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:06:22 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:09:39 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 13 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:24:03 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:28:26 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:36:09 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 201 - +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:38:47 +0530] "GET /endpoint/admin/search?consentIds=00cea448-beee-4f06-94a9-8bc7e6dbee11 HTTP/1.1" 200 44 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:18:39:08 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 200 854 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:32:58 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:38:48 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:38:48 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:46:44 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:50:45 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:50:45 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:52:33 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:53:46 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:58:32 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:19:58:35 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:00:48 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:01:09 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:02:09 +0530] "GET /endpoint/admin/9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:02:10 +0530] "GET /endpoint/admin/f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:02:18 +0530] "GET /endpoint/admin/f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 123 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:03:17 +0530] "GET /endpoint/admin/f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [16/Feb/2025:20:05:04 +0530] "GET /endpoint/admin/f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 200 409 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-17.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-17.txt new file mode 100644 index 000000000..bbe5052f7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-17.txt @@ -0,0 +1,15 @@ +0:0:0:0:0:0:0:1 - - [17/Feb/2025:12:07:25 +0530] "GET /endpoint/admin/create HTTP/1.1" 500 8787 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:12:08:25 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:12:08:49 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 200 854 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:13:31:29 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:13:31:29 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:13:32:18 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 13 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:04:36 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:05:45 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:17:39 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:50:24 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:53:00 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:14:58:16 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:15:26:03 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:15:31:13 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 179 +0:0:0:0:0:0:0:1 - - [17/Feb/2025:15:47:54 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 200 854 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-18.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-18.txt new file mode 100644 index 000000000..ffee31060 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-18.txt @@ -0,0 +1,4 @@ +0:0:0:0:0:0:0:1 - - [18/Feb/2025:14:10:26 +0530] "GET /consent/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [18/Feb/2025:14:10:41 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 +0:0:0:0:0:0:0:1 - - [18/Feb/2025:14:11:16 +0530] "GET / HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [18/Feb/2025:14:11:16 +0530] "GET /favicon.ico HTTP/1.1" 404 682 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-19.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-19.txt new file mode 100644 index 000000000..695a93001 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-19.txt @@ -0,0 +1,3 @@ +0:0:0:0:0:0:0:1 - - [19/Feb/2025:14:42:41 +0530] "GET /endpoint HTTP/1.1" 500 2693 +0:0:0:0:0:0:0:1 - - [19/Feb/2025:14:42:41 +0530] "GET /favicon.ico HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [19/Feb/2025:14:43:10 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 500 183 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-20.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-20.txt new file mode 100644 index 000000000..2ecf5b000 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-20.txt @@ -0,0 +1,22 @@ +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:51:09 +0530] "GET /endpoint/admin/get HTTP/1.1" 500 7827 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:51:29 +0530] "GET /endpoint/admin/get HTTP/1.1" 500 7827 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:52:09 +0530] "GET /endpoint/admin/get HTTP/1.1" 500 2779 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:53:33 +0530] "GET /endpoint/admin/get HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:53:37 +0530] "GET /endpoint/admin/get HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:53:51 +0530] "GET /consent/admin/get HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:54:03 +0530] "GET /endpoint HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:54:03 +0530] "GET /endpoint HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:54:05 +0530] "GET / HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:54:11 +0530] "GET /consent/admin/get HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:11:54:38 +0530] "GET /endpoint//admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:12:21:53 +0530] "GET /endpoint//admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:13:25:33 +0530] "GET /endpoint//admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:13:46:58 +0530] "GET /endpoint/admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:19:44:16 +0530] "GET /endpoint/admin/search?consentIds=f9b8d67e-8cac-45cd-b4f3-d5aab2bbd64f HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:25:04 +0530] "GET /consent-docker/admin/create HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:25:23 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 175 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:29:54 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:30:08 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:33:19 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:33:26 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 +0:0:0:0:0:0:0:1 - - [20/Feb/2025:21:36:31 +0530] "GET /endpoint/admin/create HTTP/1.1" 200 150 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-25.txt b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-25.txt new file mode 100644 index 000000000..4f183b878 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/logs/localhost_access_log.2025-02-25.txt @@ -0,0 +1,12 @@ +0:0:0:0:0:0:0:1 - - [25/Feb/2025:15:26:04 +0530] "GET /endpoint/test HTTP/1.1" 404 - +0:0:0:0:0:0:0:1 - - [25/Feb/2025:15:26:12 +0530] "GET /endpoint/admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:16:05:31 +0530] "GET /endpoint/admin/test HTTP/1.1" 500 7827 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:16:05:40 +0530] "GET /endpoint/admin/test HTTP/1.1" 500 7827 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:16:07:33 +0530] "GET /endpoint/admin/test HTTP/1.1" 200 4 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:02 +0530] "GET /endpoint/09ef2886-59e2-4126-a00a-406e248c9012?detailedConsent=false&withAttributes=true HTTP/1.1" 404 682 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:12 +0530] "GET /consent/09ef2886-59e2-4126-a00a-406e248c9012?detailedConsent=false&withAttributes=true HTTP/1.1" 404 799 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:48 +0530] "GET /endpoint/09ef2886-59e2-4126-a00a-406e248c9012?detailedConsent=false&withAttributes=true HTTP/1.1" 404 800 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:59 +0530] "GET /endpoint HTTP/1.1" 302 - +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:59 +0530] "GET /endpoint/ HTTP/1.1" 404 764 +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:59 +0530] "GET /endpoint HTTP/1.1" 302 - +0:0:0:0:0:0:0:1 - - [25/Feb/2025:21:53:59 +0530] "GET /endpoint/ HTTP/1.1" 404 764 diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/pom.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/pom.xml new file mode 100644 index 000000000..16d986d8b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/pom.xml @@ -0,0 +1,403 @@ + + + + + 4.0.0 + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.api + 4.0.0-SNAPSHOT + ../../pom.xml + + + org.wso2.financial.services.accelerator.consent.mgt.endpoint + war + WSO2 Financial Services - Consent Endpoint + + + + commons-logging + commons-logging + + + + org.apache.commons + commons-dbcp2 + 2.9.0 + + + + org.apache.commons + commons-lang3 + + + commons-beanutils + commons-beanutils + + + org.apache.commons + commons-collections4 + ${commons-collections.version} + + + javax.servlet + servlet-api + 2.5 + provided + + + org.json.wso2 + json + ${org.json.version} + + + + + + com.mysql + mysql-connector-j + 9.2.0 + + + org.apache.cxf + cxf-core + + + org.apache.cxf + cxf-rt-frontend-jaxrs + + + io.swagger + swagger-annotations + 1.5.3 + + + org.webjars + swagger-ui + 5.12.0 + + + io.swagger.core.v3 + swagger-jaxrs2 + 2.2.20 + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + org.apache.cxf + cxf-rt-rs-extension-providers + 4.0.3 + + + net.minidev + json-smart + ${json-smart.version} + + + com.github.spotbugs + spotbugs-maven-plugin + ${maven.spotbugsplugin.version} + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.service + 4.0.0-SNAPSHOT + + + + + + + org.wso2.financial.services.accelerator + org.wso2.financial.services.accelerator.consent.mgt.dao + 4.0.0-SNAPSHOT + + + + + + + + javax.validation + validation-api + 2.0.1.Final + compile + + + + io.swagger.core.v3 + swagger-jaxrs2 + 2.2.20 + + + + + org.webjars + swagger-ui + 4.15.5 + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + + org.slf4j + slf4j-simple + ${org.slf4j.version} + + + + org.testng + testng + test + + + org.mockito + mockito-core + test + + + org.mockito + mockito-testng + test + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.3.0 + + + copy-dependencies + package + + copy-dependencies + + + ${project.build.directory}/WEB-INF/lib + runtime + + + + + + + org.apache.maven.plugins + maven-war-plugin + + + + + src/main/webapp + + + consent + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + Max + Low + true + true + ${project.build.directory}/spotbugs + ${project.basedir}/src/main/resources/findbugs-exclude.xml + ${project.basedir}/src/main/resources/findbugs-include.xml + + + com.h3xstream.findsecbugs + findsecbugs-plugin + ${com.h3xstream.findsecbugs.version} + + + + + + analyze-compile + compile + + check + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + src/test/resources/testng.xml + + + target/jacoco.exec + + true + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + + **/*Constant.class + **/*Component.class + **/*DataHolder.class + **/*Exception.class + + + + org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/** + **/*SwaggerApplication.class + **/*DatabaseInitializer.class + **/*ConsentApi.class + **/*ConsentUtils.class + + + + + + + + + + + + + + default-prepare-agent + + prepare-agent + + + + default-prepare-agent-integration + + prepare-agent-integration + + + + default-report + + report + + + + default-report-integration + + report-integration + + + + default-check + + check + + + + + BUNDLE + + + INSTRUCTION + COVEREDRATIO + 0.7 + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/AndroidManifest.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/AndroidManifest.xml new file mode 100644 index 000000000..a9534e369 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/SwaggerApplication.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/SwaggerApplication.java new file mode 100644 index 000000000..20c722752 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/SwaggerApplication.java @@ -0,0 +1,26 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint; +import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; + +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +/** + * JAX-RS application class. + */ +@ApplicationPath("/api") // Base path for JAX-RS +@OpenAPIDefinition(info = @Info(title = "Consent Management API", version = "1.0", description = "Consent Management " + + "application" + + " API")) +public class SwaggerApplication extends Application { + @Override + public Set> getClasses() { + Set> classes = new HashSet<>(); + classes.add(OpenApiResource.class); // Registers Swagger OpenAPI Resource + return classes; + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/api/ConsentApi.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/api/ConsentApi.java new file mode 100644 index 000000000..b09df4de7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/api/ConsentApi.java @@ -0,0 +1,265 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.api; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.impl.ConsentAPIImpl; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AmendmentResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AmendmentResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.BulkConsentStatusUpdateResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentHistory; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResourceDTO; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentStatusUpdateResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.DetailedConsentResource; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +/** + * Represents a collection of functions to interact with the API endpoints. + */ +@SuppressFBWarnings("JAXRS_ENDPOINT") +// Suppressed content - Endpoints +// Suppression reason - False Positive : These endpoints are secured with access +// control +@Path("/consent") +@Api(description = "the consent API") +@javax.annotation.Generated + (value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentApi { + ConsentAPIImpl consentAPIImpl = new ConsentAPIImpl(); + + + @DELETE + @Path("/{consentId}") + @ApiOperation(value = "Consent purging", notes = "", response = Void.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 204, message = "Successful operation", response = Void.class), + @ApiResponse(code = 404, message = "Invalid consent id", response = Void.class) + }) + public Response consentConsentIdDelete( + + @PathParam("consentId") @ApiParam("consent id") String consentId, + + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo, + @QueryParam("userId") String userId + + ) { + try { + return Response.ok().entity(consentAPIImpl.consentConsentIdDelete(consentId, orgInfo, userId)) + .build(); + } catch (Exception e) { + // Handle other errors + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("An unexpected error occurred: " + e.getMessage()) + .build(); + } + } + + @GET + @Path("/{consentId}") + @Produces({"application/json"}) + @ApiOperation(value = "Consent retrieval", notes = "", response = DetailedConsentResource.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = DetailedConsentResource.class), + @ApiResponse(code = 404, message = "Invalid consent id", response = Void.class) + }) + public Response consentConsentIdGet( + + @PathParam("consentId") @ApiParam("consent id") String consentId, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo, + @QueryParam("isDetailedConsentResource") boolean isDetailedConsentResource, + @QueryParam("withAttributes") @DefaultValue("true") boolean withAttributes + + ) { + try { + return consentAPIImpl.consentConsentIdGet(consentId, orgInfo, isDetailedConsentResource, + withAttributes); + } catch (Exception e) { + // Handle other errors + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("An unexpected error occurred: " + e.getMessage()) + .build(); + } + } + + @GET + @Path("/{consentId}/authorizationResource/{authorizationId}") + @Produces({"application/json"}) + @ApiOperation(value = "Consent retrieval", notes = "", response = DetailedConsentResource.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = DetailedConsentResource.class), + @ApiResponse(code = 404, message = "Invalid consent id", response = Void.class) + }) + public Response consentAuthorizationIdGet( + + @PathParam("authorizationId") @ApiParam("authorization Id") String authorizationId, + @PathParam("consentId") @ApiParam("consent Id") String consentId, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo + + + ) { + return consentAPIImpl.consentAuthorizationAuthorizationIdGet(authorizationId, orgInfo, consentId); + + } + + @GET + @Path("/{consentId}/history") + @Produces({"application/json"}) + @ApiOperation(value = "get consent history", notes = "", response = ConsentHistory.class, + responseContainer = "List", tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = ConsentHistory.class, + responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid consent id", response = Void.class) + }) + public Response consentConsentIdHistoryGet( + + @PathParam("consentId") @ApiParam("consent id") String consentId, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo, + @QueryParam("detailed") boolean detailed, + @QueryParam("status") @ApiParam("status") String status, + @QueryParam("actionBy") @ApiParam("actionBy") String actionBy, + @QueryParam("fromTime") @ApiParam("fromTime") long fromTime, + @QueryParam("toTime") @ApiParam("toTime") long toTime, + @QueryParam("statusAuditId") @ApiParam("statusAuditId") String statusAuditId + + ) { + return consentAPIImpl.consentConsentIdHistoryGet(consentId, orgInfo, detailed, status, + actionBy, fromTime, toTime, statusAuditId); + + } + + @PUT + @Path("/{consentId}") + @Consumes({"application/json"}) + @Produces({"application/json"}) + @ApiOperation(value = "Consent amendment", notes = "", response = AmendmentResponse.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = AmendmentResponse.class), + @ApiResponse(code = 400, message = "Invalid request body", response = Void.class) + }) + public Response consentConsentIdPut( + + @PathParam("consentId") @ApiParam("consent id") String consentId, + @Valid @NotNull AmendmentResource amendmentResource, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo) { + + return consentAPIImpl.consentConsentIdPut(consentId, amendmentResource, orgInfo); + + } + + @PUT + @Path("/{consentId}/status") + @Consumes({"application/json"}) + @Produces({"application/json"}) + @ApiOperation(value = "Consent status update", notes = "", response = String.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid consent id", response = Void.class) + }) + public Response consentConsentIdStatusPut( + + @PathParam("consentId") @ApiParam("consent id") String consentId, + @Valid @NotNull ConsentStatusUpdateResource consentStatusUpdateResource, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo) { + + return consentAPIImpl.consentConsentIdStatusPut(consentId, consentStatusUpdateResource, + orgInfo); + + } + + @GET + @Produces({"application/json"}) + @ApiOperation(value = "consent search", notes = "", response = DetailedConsentResource.class, + responseContainer = "List", tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = DetailedConsentResource.class, + responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid consent id", response = Void.class) + }) + public Response consentGet( + + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo, + @QueryParam("consentTypes") String consentTypes, + @QueryParam("consentStatuses") String consentStatuses, + @QueryParam("clientIds") String clientIds, + @QueryParam("userIds") String userIds, + @QueryParam("fromTime") int fromTime, + @QueryParam("toTime") int toTime, + @QueryParam("limit") int limit, + @QueryParam("offset") int offset + + ) { + return consentAPIImpl.consentGet(orgInfo, consentTypes, consentStatuses, userIds, + fromTime, + toTime, limit, offset); + } + + @POST + @Consumes({"application/json"}) + @Produces({"application/json"}) + @ApiOperation(value = "Consent initiation", notes = "", response = ConsentResponse.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = ConsentResponse.class), + @ApiResponse(code = 400, message = "Invalid request body", response = Void.class) + }) + public Response consentPost( + + @Valid @NotNull ConsentResourceDTO consentResource, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo, + @HeaderParam("isImplicitAuth") @ApiParam("Flag to determine whether authorization is implicit or not") + boolean isImplicitAuth, + @HeaderParam("isExclusiveConsent") @ApiParam("Flag to determine whether this is an exclusive consent") + boolean exclusiveConsent) { + + return consentAPIImpl.consentPost(consentResource, orgInfo, isImplicitAuth, + exclusiveConsent); + + } + + @PUT + @Path("/status") + @Consumes({"application/json"}) + @Produces({"application/json"}) + @ApiOperation(value = "Bulk consent status change", notes = "", response = String.class, tags = {"consent"}) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "Successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid consent id", response = Void.class) + }) + public Response consentStatusPut( + + @Valid @NotNull BulkConsentStatusUpdateResource bulkConsentStatusUpdateResource, + @HeaderParam("OrgInfo") @ApiParam("jwt header containing tenant related information") + @DefaultValue("DEFAULT_ORG") String orgInfo) { + + return consentAPIImpl.consentStatusPut(bulkConsentStatusUpdateResource, orgInfo); + + + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/constants/ConsentConstant.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/constants/ConsentConstant.java new file mode 100644 index 000000000..3f5f45804 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/constants/ConsentConstant.java @@ -0,0 +1,180 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.constants; + + +/** + * Constant class for consent extension module. + */ +public class ConsentConstant { + + //Common Constants + public static final String DETAILED_CONSENT = "detailedConsent"; + public static final String WITH_ATTRIBUTES = "withAttributes"; + + //Common Constants + public static final String + UUID_REGEX = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"; + + public static final String ACCOUNTS = "accounts"; + public static final String PAYMENTS = "payments"; + public static final String FUNDS_CONFIRMATIONS = "fundsconfirmations"; + public static final String ACCOUNT_CONSENT_PATH = "account-access-consents"; + public static final String COF_CONSENT_PATH = "funds-confirmation-consents"; + public static final String PAYMENT_CONSENT_PATH = "payment-consents"; + public static final String CONSENT_DATA = "consentData"; + public static final String TITLE = "title"; + public static final String CONSENT_ID = "ConsentId"; + public static final String ACCOUNT_ID = "account_id"; + public static final String DATA = "Data"; + public static final String CONSENT_TYPE = "consent_type"; + public static final String AWAIT_AUTHORISE_STATUS = "AwaitingAuthorisation"; + public static final String AUTHORIZED_STATUS = "Authorised"; + public static final String REVOKED_STATUS = "Revoked"; + public static final String REJECTED_STATUS = "Rejected"; + public static final String CREATED_STATUS = "created"; + public static final String DEFAULT_AUTH_TYPE = "authorisation"; + public static final String PERMISSIONS = "Permissions"; + public static final String EXPIRATION_DATE = "ExpirationDateTime"; + public static final String EXPIRATION_DATE_TITLE = "Expiration Date Time"; + public static final String TRANSACTION_FROM_DATE = "TransactionFromDateTime"; + public static final String TRANSACTION_FROM_DATE_TITLE = "Transaction From Date Time"; + public static final String TRANSACTION_TO_DATE = "TransactionToDateTime"; + public static final String TRANSACTION_TO_DATE_TITLE = "Transaction To Date Time"; + public static final String INITIATION = "Initiation"; + public static final String PAYMENT_TYPE_TITLE = "Payment Type"; + public static final String CURRENCY_OF_TRANSFER = "CurrencyOfTransfer"; + public static final String CURRENCY_OF_TRANSFER_TITLE = "Currency of Transfer"; + public static final String INTERNATIONAL_PAYMENTS = "International Payments"; + public static final String DOMESTIC_PAYMENTS = "Domestic Payments"; + public static final String END_TO_END_IDENTIFICATION = "EndToEndIdentification"; + public static final String END_TO_END_IDENTIFICATION_TITLE = "End to End Identification"; + public static final String INSTRUCTION_IDENTIFICATION = "InstructionIdentification"; + public static final String INSTRUCTION_IDENTIFICATION_TITLE = "Instruction Identification"; + public static final String DEBTOR_ACC = "DebtorAccount"; + public static final String DEBTOR_ACC_TITLE = "Debtor Account"; + public static final String CREDITOR_ACC = "CreditorAccount"; + public static final String CREDITOR_ACC_TITLE = "Creditor Account"; + public static final String SCHEME_NAME = "SchemeName"; + public static final String SCHEME_NAME_TITLE = "Scheme Name"; + public static final String IDENTIFICATION = "Identification"; + public static final String IDENTIFICATION_TITLE = "Identification"; + public static final String NAME = "Name"; + public static final String NAME_TITLE = "Name"; + public static final String SECONDARY_IDENTIFICATION = "SecondaryIdentification"; + public static final String SECONDARY_IDENTIFICATION_TITLE = "Secondary Identification"; + public static final String OPEN_ENDED_AUTHORIZATION = "Open Ended Authorisation Requested"; + public static final String INSTRUCTED_AMOUNT = "InstructedAmount"; + public static final String INSTRUCTED_AMOUNT_TITLE = "Instructed Amount"; + public static final String CURRENCY = "Currency"; + public static final String CURRENCY_TITLE = "Currency"; + public static final String AMOUNT = "Amount"; + public static final String AMOUNT_TITLE = "Amount"; + + //Consent Auth Servlet Constants + public static final String DEBTOR_ACCOUNT_ID = "AccountId"; + public static final String AUTH_ACCOUNT_ID = "account_id"; + public static final String DATA_REQUESTED = "data_requested"; + public static final String ACCOUNT_DATA = "account_data"; + public static final String SELECTED_ACCOUNT = "selectedAccount"; + public static final String DISPLAY_NAME = "display_name"; + public static final String PAYMENT_ACCOUNT = "paymentAccount"; + public static final String COF_ACCOUNT = "cofAccount"; + public static final String PRIMARY = "primary"; + public static final String ACCOUNT_IDS = "accountIds"; + public static final String ERRORS = "errors"; + public static final String ERROR_CODE = "code"; + public static final String ERROR_MSG = "message"; + public static final String ERROR_DESCRIPTION = "description"; + public static final String STATE = "state"; + public static final String REDIRECT_URI = "redirect_uri"; + //Consent Admin Handler Constants + public static final String CONSENT_IDS = "consentIds"; + public static final String CLIENT_IDS = "clientIds"; + public static final String CONSENT_TYPES = "consentTypes"; + public static final String CONSENT_STATUSES = "consentStatuses"; + public static final String USER_IDS = "userIds"; + public static final String FROM_TIME = "fromTime"; + public static final String TO_TIME = "toTime"; + public static final String LIMIT = "limit"; + public static final String OFFSET = "offset"; + public static final String COUNT = "count"; + public static final String TOTAL = "total"; + public static final String METADATA = "metadata"; + public static final String HISTORY_ID = "historyId"; + public static final String AMENDED_REASON = "amendedReason"; + public static final String AMENDED_TIME = "amendedTime"; + public static final String CURRENT_CONSENT = "currentConsent"; + public static final String AMENDMENT_HISTORY = "consentAmendmentHistory"; + public static final String AMENDMENT_COUNT = "amendmentCount"; + public static final String STATUS_AUDIT_ID = "statusAuditId"; + public static final String ACTION_TIME = "actionTime"; + public static final String REASON = "reason"; + public static final String ACTION_BY = "actionBy"; + public static final String PREVIOUS_STATUS = "previousStatus"; + public static final String CONSENT_FILE = "consentFile"; + public static final String CONSENT_REVOKE_FROM_DASHBOARD_REASON = "Revoke the consent from dashboard"; + public static final String CLAIMS = "claims"; + public static final String USER_INFO = "userinfo"; + public static final String ID_TOKEN = "id_token"; + public static final String OB_INTENT_ID = "openbanking_intent_id"; + public static final String VALUE = "value"; + public static final String CREATION_DATE_TIME = "CreationDateTime"; + public static final String STATUS_UPDATE_DATE_TIME = "StatusUpdateDateTime"; + public static final String STATUS = "Status"; + public static final String RECEIPT = "receipt"; + public static final String CLIENT_ID = "clientId"; + public static final String CURRENT_STATUS = "currentStatus"; + public static final String CONSENT_FREQUENCY = "consentFrequency"; + public static final String VALIDITY_PERIOD = "validityPeriod"; + public static final String CREATED_TIME = "createTime"; + public static final String UPDATED_TIMESTAMP = "updatedTimestamp"; + public static final String RECURRING_INDICATOR = "recurringIndicator"; + public static final String CONSENT_ATTRIBUTES = "consentAttributes"; + public static final String RESOURCE = "resource"; + public static final String AUTH_ID = "authorizationId"; + public static final String CC_CONSENT_ID = "consentId"; + public static final String USER_ID = "userId"; + public static final String AUTH_STATUS = "authorizationStatus"; + public static final String AUTH_TYPE = "authorizationType"; + public static final String UPDATE_TIME = "updatedTime"; + public static final String AUTH_RESOURCES = "authorizationResources"; + public static final String MAPPING_ID = "mappingId"; + public static final String PERMISSION = "permission"; + public static final String MAPPING_STATUS = "mappingStatus"; + public static final String MAPPING_RESOURCES = "consentMappingResources"; + + //Consent Authorize Constants + public static final String IS_ERROR = "isError"; + public static final String TYPE = "type"; + public static final String APPLICATION = "application"; + public static final String SENSITIVE_DATA_MAP = "sensitiveDataMap"; + public static final String LOGGED_IN_USER = "loggedInUser"; + public static final String SP_QUERY_PARAMS = "spQueryParams"; + public static final String SCOPES = "scopeString"; + public static final String REQUEST_HEADERS = "requestHeaders"; + public static final String REQUEST_URI = "redirectURI"; + public static final String META_DATA = "metaDataMap"; + public static final String RESOURCE_PATH = "ResourcePath"; + public static final String CONSENT_RESOURCE = "consentResource"; + public static final String AUTH_RESOURCE = "authResource"; + public static final String REGULATORY = "regulatory"; + public static final String HAS_APPROVED_ALWAYS = "hasApprovedAlways"; + public static final String USER = "user"; + public static final String SESSION_DATA_KEY = "sessionDataKey"; + public static final String SESSION_DATA_KEY_CONSENT = "sessionDataKeyConsent"; + public static final String CONSENT = "consent"; + public static final String LOCATION = "Location"; + public static final int STATUS_FOUND = 302; + public static final String APPROVAL = "approval"; + public static final String COOKIES = "cookies"; + + // Consent Validate Constants + public static final String HEADERS = "headers"; + public static final String BODY = "body"; + public static final String ELECTED_RESOURCE = "electedResource"; + public static final String RESOURCE_PARAMS = "resourceParams"; + public static final String ADDITIONAL_CONSENT_INFO = "additionalConsentInfo"; + public static final String CONSENT_INFO = "consentInformation"; + public static final String CREATED_TIMESTAMP = "createdTimestamp"; + + public static final String ORG_MISMATCH = "OrgInfo does not match, please provide the correct OrgInfo"; +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/exception/ConstraintViolationException.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/exception/ConstraintViolationException.java new file mode 100644 index 000000000..0282c8e62 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/exception/ConstraintViolationException.java @@ -0,0 +1,31 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.exception; + +import com.fasterxml.jackson.databind.exc.MismatchedInputException; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Exception mapper for ConstraintViolationException. + */ +@Provider +public class ConstraintViolationException implements ExceptionMapper { + + @Override + public Response toResponse(MismatchedInputException exception) { + Map response = new HashMap<>(); + response.put("error", + exception.getMessage()); + return Response.status(Response.Status.BAD_REQUEST) + .entity(response) + .type(MediaType.APPLICATION_JSON) + .build(); + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/impl/ConsentAPIImpl.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/impl/ConsentAPIImpl.java new file mode 100644 index 000000000..55ba5f71b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/impl/ConsentAPIImpl.java @@ -0,0 +1,602 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.impl; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import net.minidev.json.JSONObject; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentHistoryResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentStatusAuditRecord; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AmendmentResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AuthResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AuthorizationResourceDTO; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.BulkConsentStatusUpdateResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResourceDTO; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentStatusUpdateResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ReauthorizeResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.utils.ConsentUtils; +import org.wso2.financial.services.accelerator.consent.mgt.service.constants.ConsentCoreServiceConstants; +import org.wso2.financial.services.accelerator.consent.mgt.service.impl.ConsentCoreServiceImpl; +import org.wso2.financial.services.accelerator.consent.mgt.service.util.ConsentCoreServiceUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import javax.ws.rs.core.Response; + +/** + * ConsentAPIImpl. + */ +@SuppressFBWarnings("CRLF_INJECTION_LOGS") +public class ConsentAPIImpl { + private static final Log log = LogFactory.getLog(ConsentAPIImpl.class); + private ConsentCoreServiceImpl consentCoreService; + + public ConsentAPIImpl() { + consentCoreService = new ConsentCoreServiceImpl(); + } + + public void setConsentCoreService(ConsentCoreServiceImpl consentCoreService) { + this.consentCoreService = consentCoreService; + } + + + public Response consentGet( + String orgInfo, + String consentType, String consentStatus + , String userID, long fromTimeValue, long toTimeValue, int limitValue, int offsetValue) { + + + try { + + + ////////////// initialize the search query ////////////// + ArrayList consentIDs = new ArrayList<>(); + ArrayList clientIDs = new ArrayList<>(); + ArrayList consentTypes = new ArrayList<>(); + ArrayList consentStatuses = new ArrayList<>(); + ArrayList userIDs = new ArrayList<>(); + if (consentType != null) { + Collections.addAll(consentTypes, consentType.split(",")); + } + if (consentStatus != null) { + Collections.addAll(consentStatuses, consentStatus.split(",")); + } + if (userID != null) { + userIDs.add(userID); + } + + + Long fromTime = null; + Long toTime = null; + Integer limit = null; + Integer offset = null; + fromTime = fromTimeValue == 0L ? null : fromTimeValue; + toTime = toTimeValue == 0L ? null : toTimeValue; + limit = limitValue == 0 ? null : limitValue; + offset = offsetValue == 0 ? null : offsetValue; + + ////////////// service call ////////////// + ArrayList results; + results = consentCoreService.searchDetailedConsents( + orgInfo, + consentIDs, + clientIDs, + consentTypes, + consentStatuses, + userIDs, + fromTime, + toTime, + limit, + offset); + + + if (limit != null || offset != null) { + results = consentCoreService.searchDetailedConsents(orgInfo, consentIDs, + clientIDs, + consentTypes, + consentStatuses, + userIDs, + fromTime, + toTime, + null, + null); + } + + ////////////// build response ////////////// + ArrayList consentResponses = new ArrayList<>(); + + for (DetailedConsentResource detailedConsentResource : results) { + + ConsentResponse consentResponse = new ConsentResponse(); + ConsentUtils.buildConsentResourceResponse(consentResponse, detailedConsentResource, + detailedConsentResource.getAuthorizationResources(), + detailedConsentResource.getConsentMappingResources(), true); + consentResponses.add(consentResponse); + } + + return Response.ok().entity(consentResponses).build(); + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + + public Response consentPost( + ConsentResourceDTO consentResourceDTO, + String orgInfo, boolean isImplicitAuth, boolean exclusiveConsent) { + + try { + ////////////// handle request ////////////// + ConsentResource consentResource = new ConsentResource(); + ConsentUtils.copyPropertiesToConsentResource(consentResource, consentResourceDTO); + consentResource.setOrgID(orgInfo); + + // if consentFrequency is an attribute in consentAttributes, then set it to the consentResource + Map consentAttributes = + ConsentUtils.convertToMap(consentResourceDTO.getConsentAttributes()); + if (!consentAttributes.isEmpty()) { + if (consentAttributes.containsKey("consentFrequency")) { + try { + consentResource.setConsentFrequency( + Integer.parseInt(consentAttributes.get("consentFrequency"))); + + } catch (NumberFormatException e) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, "Invalid Number Format"); + } + } else { + consentResource.setConsentFrequency(0); + } + } + + // build AuthorizationResource objects + ArrayList authorizations = new ArrayList<>(); + + if (isImplicitAuth) { + if (consentResourceDTO.getAuthorizationResources() == null) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + ConsentCoreServiceConstants.CANNOT_PROCEED_WITH_IMPLICIT_AUTH); + } + for (AuthorizationResourceDTO authorizationResourceDTO : + consentResourceDTO.getAuthorizationResources()) { + AuthorizationResource authorizationResource = new AuthorizationResource(); + ConsentUtils.copyPropertiesToAuthorizationResource(authorizationResource, authorizationResourceDTO); + ArrayList consentMappingResources = new ArrayList<>(); + for (Object resource : authorizationResourceDTO.getResources()) { + ConsentMappingResource res = new ConsentMappingResource(); + + // convert resource to JSON string + ObjectMapper objectMapper = new ObjectMapper(); + String jsonString = objectMapper.writeValueAsString(resource); + JSONObject jsonObject = + new JSONObject(objectMapper.convertValue(resource, java.util.Map.class)); + + res.setResource(jsonObject); + res.setMappingStatus("active"); + consentMappingResources.add(res); + } + authorizationResource.setConsentMappingResource(consentMappingResources); + authorizations.add(authorizationResource); + + } + } + + ////////////// Service call ////////////// + DetailedConsentResource result = null; + + if (!exclusiveConsent) { + result = consentCoreService.createAuthorizableConsentWithBulkAuth(consentResource, + authorizations, + isImplicitAuth); + + } else { + //TODO : Implement exclusive consent + throw new ConsentMgtException(Response.Status.NOT_IMPLEMENTED, "Exclusive Consent Not yet " + + "implemented"); + } + + ////////////// build response ////////////// + ConsentResponse consentResponse = new ConsentResponse(); + ConsentUtils.buildConsentResourceResponse(consentResponse, result, result.getAuthorizationResources(), + result.getConsentMappingResources(), + true); + + return Response.status(Response.Status.CREATED).entity(consentResponse).build(); + } catch (JsonProcessingException e) { + + return handleConsentMgtException(new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, + e.getMessage())); + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + public Response consentConsentIdStatusPut( + String consentID, ConsentStatusUpdateResource consentStatusUpdateResource + , String orgInfo) { + try { + consentCoreService.updateConsentStatusWithImplicitReasonAndUserId(consentID, + consentStatusUpdateResource.getStatus(), + consentStatusUpdateResource.getReason(), + consentStatusUpdateResource.getUserId(), + orgInfo); + return Response.ok().entity("Status Updated").build(); + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + public Response consentStatusPut(BulkConsentStatusUpdateResource bulkConsentStatusUpdateResource, String orgInfo) { + try { + consentCoreService.bulkUpdateConsentStatus( + orgInfo, + bulkConsentStatusUpdateResource.getClientID(), + bulkConsentStatusUpdateResource.getStatus(), + bulkConsentStatusUpdateResource.getReason(), + bulkConsentStatusUpdateResource.getUserId(), + bulkConsentStatusUpdateResource.getConsentType(), + bulkConsentStatusUpdateResource.getApplicableStatusesForStateChange()); + + return Response.ok().entity("Status Updated").build(); + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + public Response consentConsentIdPut( + String consentID, AmendmentResource amendmentResource, + String orgInfo) { + + try { + ////////////// handle request ////////////// + // get authorization resources without authId + ArrayList newAuthorization = new ArrayList<>(); + + // get authorization resources with authId + ArrayList reAuthorization = new ArrayList<>(); + + // get resources without authId + Map> newResources = new HashMap<>(); + + // get resources with authId + ArrayList reResources = new ArrayList<>(); + + // iterate through authorization resources and build new and existing auth and resource objects + for (ReauthorizeResource authResourceDTO : amendmentResource.getAuthorizationResources()) { + //existing auth + if (authResourceDTO.getAuthorizationId() != null) { + AuthorizationResource auth = new AuthorizationResource(); + ConsentUtils.copyPropertiesToAuthorizationResource(auth, authResourceDTO); + auth.setConsentID(consentID); + reAuthorization.add(auth); + + } else { + // new auth + AuthorizationResource auth = new AuthorizationResource(); + ConsentUtils.copyPropertiesToAuthorizationResource(auth, authResourceDTO); + auth.setConsentID(consentID); + newAuthorization.add(auth); + } + } + + // TODO : // action by ?? + String userID; + if (amendmentResource.getAuthorizationResources().isEmpty()) { + userID = null; + } else { + userID = amendmentResource.getAuthorizationResources().get(0).getUserId(); + } + + ////////////// service call ////////////// + DetailedConsentResource amendmentResponse = consentCoreService.amendDetailedConsentWithBulkAuthResource( + orgInfo, + consentID, + amendmentResource.getReceipt(), + Long.valueOf(amendmentResource.getValidityPeriod()), + reAuthorization, + amendmentResource.getCurrentStatus(), + ConsentUtils.convertToMap(amendmentResource.getConsentAttributes()), + userID, + newAuthorization); + + + ////////////// build response ////////////// + ConsentResponse consentResponse = new ConsentResponse(); + ConsentUtils.buildConsentResourceResponse(consentResponse, amendmentResponse, + amendmentResponse.getAuthorizationResources(), amendmentResponse.getConsentMappingResources(), + true); + + return Response.ok().entity(consentResponse).build(); + + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + + } + + + // +// + public Response consentConsentIdGet( + String consentID, String orgInfo, boolean isDetailedConsentResource, + boolean isWithAttributes) { + + try { + + + if (ConsentUtils.isConsentIdValid(consentID)) { + + try { + if (isDetailedConsentResource) { + ////////////// Service call ////////////// + DetailedConsentResource detailedConsentResource = + consentCoreService.getDetailedConsent(consentID); + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgInfo, + detailedConsentResource.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + + ////////////// build Response ////////////// + ConsentResponse consentResponse = new ConsentResponse(); + ConsentUtils.buildConsentResourceResponse(consentResponse, + detailedConsentResource, + detailedConsentResource.getAuthorizationResources(), + detailedConsentResource.getConsentMappingResources(), true); +// if( isWithAttributes == null){ + if (!isWithAttributes) { + consentResponse.setConsentAttributes(null); + // remove null values from the consent + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + +// } + + return Response.ok().entity(consentResponse).build(); + + } else { + + ConsentResource consent; + ////////////// Service Call ////////////// + if (Objects.equals(isWithAttributes, + true)) { + consent = consentCoreService.getConsent(consentID, + true); + } else { + consent = consentCoreService.getConsent(consentID, + false); + } + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgInfo, + consent.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + ////////////// build Response ////////////// + // remove null values from the consent + consent.setOrgID(null); + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + + return Response.ok().entity(objectMapper.writeValueAsString(consent)).build(); + + + } + } catch (JSONException e) { + log.error("Error Occurred while handling the request", e); + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), e); + } catch (JsonProcessingException e) { + throw new ConsentMgtException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage(), e); + } + } else { + log.error("Invalid Consent ID"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "Invalid Consent ID"); + } + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + public Response consentAuthorizationAuthorizationIdGet(String authorizationId, String orgInfo, String consentId) { + AuthResponse authResponse = new AuthResponse(); + + try { + + ConsentResource consentResource = consentCoreService.getConsent(consentId, false); + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgInfo, + consentResource.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + + AuthorizationResource authorizationResource = consentCoreService.getAuthorizationResource(authorizationId, + orgInfo); + + ConsentUtils.buildAuthorizationResourceResponse(authResponse, authorizationResource, + authorizationResource.getConsentMappingResource()); + + return Response.ok().entity(authResponse).build(); + + } catch (ConsentMgtException e) { + + return handleConsentMgtException(e); + } + + + } + + public Response consentConsentIdDelete(String consentID, String orgInfo, String userID) throws + ConsentMgtException { + try { + ConsentResource consentResource = consentCoreService.getConsent(consentID, + false); + + if (!ConsentCoreServiceUtil.validateOrgInfo(orgInfo, + consentResource.getOrgID())) { + log.error("OrgInfo does not match"); + throw new ConsentMgtException(Response.Status.BAD_REQUEST, + "OrgInfo does not match, please provide the correct OrgInfo"); + } + + boolean result = consentCoreService.revokeConsent(consentID, + "revoked", + userID, + false); + if (result) { + JSONObject message = new JSONObject(); + message.put("errorMessage", "Consent Revoked"); + + return Response.ok().entity(message).build(); + } else { + return Response.serverError().build(); + + } + + + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + + } + + + public Response consentConsentIdHistoryGet( + String consentID, String orgInfo, Boolean detailed, String status, String actionBy, long fromTimeValue, + long toTimeValue, String statusAuditId) { + + try { + + Long fromTime = null; + Long toTime = null; + Integer limit = null; + Integer offset = null; + fromTime = fromTimeValue == 0L ? null : fromTimeValue; + toTime = toTimeValue == 0L ? null : toTimeValue; + + ArrayList consentStatusAuditRecords = + consentCoreService.searchConsentStatusAuditRecords(consentID, status, + actionBy, fromTime, + toTime, + statusAuditId); + + // get the consent status audit record Ids + ArrayList consentStatusAuditRecordIds = new ArrayList<>(); + for (ConsentStatusAuditRecord consentStatusAuditRecord : consentStatusAuditRecords) { + consentStatusAuditRecordIds.add(consentStatusAuditRecord.getStatusAuditID()); + } + + ArrayList results = + new ArrayList<>(consentCoreService.getConsentAmendmentHistoryData(consentStatusAuditRecordIds, + consentID).values()); + ArrayList newResults = new ArrayList<>(); + + if (!detailed) { + for (ConsentHistoryResource result : results) { + result.getDetailedConsentResource().setAuthorizationResources(null); + result.getDetailedConsentResource().setConsentAttributes(null); + result.getDetailedConsentResource().setConsentMappingResources(null); + newResults.add(result); + } + // remove null values from the consent + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try { + return Response.ok().entity(objectMapper.writeValueAsString(newResults)).build(); + + } catch (JsonProcessingException e) { + log.error("Error Occurred while handling the request", e); + JSONObject error = new JSONObject(); + error.put("errorMessage", e.getMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + + } else { + + + for (ConsentHistoryResource result : results) { + DetailedConsentResource detailedConsentResource = + result.getDetailedConsentResource(); + + // get consent mapping resources for each AuthorizationResource + Map> consentMappingResourcesMap = new HashMap<>(); + for (ConsentMappingResource consentMappingResource : + detailedConsentResource.getConsentMappingResources()) { + if (!consentMappingResourcesMap.containsKey(consentMappingResource.getAuthorizationID())) { + consentMappingResourcesMap.put(consentMappingResource.getAuthorizationID(), + new ArrayList<>()); + } + consentMappingResourcesMap.get(consentMappingResource.getAuthorizationID()) + .add(consentMappingResource); + } + + ArrayList authorizationResourcesWithResources = new ArrayList<>(); + for (AuthorizationResource authorizationResource : + detailedConsentResource.getAuthorizationResources()) { + AuthorizationResource auth = new AuthorizationResource(); + ConsentUtils.buildAuthorizationResourceResponse(auth, + authorizationResource, + consentMappingResourcesMap.get(authorizationResource.getAuthorizationID())); + authorizationResourcesWithResources.add(auth); + } + detailedConsentResource.setAuthorizationResources(authorizationResourcesWithResources); + newResults.add(result); + } + + // remove null values from the consent + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + try { + return Response.ok().entity(objectMapper.writeValueAsString(newResults)).build(); + } catch (JsonProcessingException e) { + log.error("Error Occurred while handling the request", e); + JSONObject error = new JSONObject(); + error.put("errorMessage", e.getMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + + } + + } catch (ConsentMgtException e) { + return handleConsentMgtException(e); + } + } + + private Response handleConsentMgtException(ConsentMgtException e) { + log.error("Error Occurred while handling the request", e); + JSONObject error = new JSONObject(); + error.put("errorMessage", e.getMessage()); + return Response.status(e.getErrorCode()).entity(error).build(); + } + + private void validateOrgInfo(String expectedOrg, String providedOrg) throws + ConsentMgtException { + if (!expectedOrg.equals(providedOrg)) { + log.error(String.format("OrgInfo mismatch: Expected=%s, Provided=%s", expectedOrg, providedOrg)); + throw new ConsentMgtException(Response.Status.NOT_FOUND, + "OrgInfo mismatch, please provide the correct OrgInfo"); + } + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResource.java new file mode 100644 index 000000000..49932ecfc --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResource.java @@ -0,0 +1,195 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("AmendmentResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class AmendmentResource implements Serializable { + private String receipt; + private Integer validityPeriod; + private Object consentAttributes; + private @Valid List<@Valid ReauthorizeResource> authorizationResources = new ArrayList<>(); + private String currentStatus; + + public AmendmentResource() { + } + + /** + * + **/ + public AmendmentResource receipt(String receipt) { + this.receipt = receipt; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("receipt") + public String getReceipt() { + return receipt; + } + + @JsonProperty("receipt") + public void setReceipt(String receipt) { + this.receipt = receipt; + } + + /** + * + **/ + public AmendmentResource validityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + return this; + } + + + @ApiModelProperty(example = "3600", value = "") + @JsonProperty("validityPeriod") + public Integer getValidityPeriod() { + return validityPeriod; + } + + @JsonProperty("validityPeriod") + public void setValidityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + } + + /** + * + **/ + public AmendmentResource consentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + return this; + } + + + @ApiModelProperty(example = "{\"key1\":\"value1\"}", value = "") + @JsonProperty("consentAttributes") + public Object getConsentAttributes() { + return consentAttributes; + } + + @JsonProperty("consentAttributes") + public void setConsentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + } + + /** + * + **/ + public AmendmentResource authorizationResources(List<@Valid ReauthorizeResource> authorizationResources) { + this.authorizationResources = authorizationResources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authorizationResources") + @Valid public List<@Valid ReauthorizeResource> getAuthorizationResources() { + return authorizationResources; + } + + @JsonProperty("authorizationResources") + public void setAuthorizationResources(List<@Valid ReauthorizeResource> authorizationResources) { + this.authorizationResources = authorizationResources; + } + + public AmendmentResource addAuthorizationResourcesItem(ReauthorizeResource authorizationResourcesItem) { + if (this.authorizationResources == null) { + this.authorizationResources = new ArrayList<>(); + } + + this.authorizationResources.add(authorizationResourcesItem); + return this; + } + + public AmendmentResource removeAuthorizationResourcesItem(ReauthorizeResource authorizationResourcesItem) { + if (authorizationResourcesItem != null && this.authorizationResources != null) { + this.authorizationResources.remove(authorizationResourcesItem); + } + + return this; + } + + /** + * + **/ + public AmendmentResource currentStatus(String currentStatus) { + this.currentStatus = currentStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorization", value = "") + @JsonProperty("currentStatus") + public String getCurrentStatus() { + return currentStatus; + } + + @JsonProperty("currentStatus") + public void setCurrentStatus(String currentStatus) { + this.currentStatus = currentStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AmendmentResource amendmentResource = (AmendmentResource) o; + return Objects.equals(this.receipt, amendmentResource.receipt) && + Objects.equals(this.validityPeriod, amendmentResource.validityPeriod) && + Objects.equals(this.consentAttributes, amendmentResource.consentAttributes) && + Objects.equals(this.authorizationResources, amendmentResource.authorizationResources) && + Objects.equals(this.currentStatus, amendmentResource.currentStatus); + } + + @Override + public int hashCode() { + return Objects.hash(receipt, validityPeriod, consentAttributes, authorizationResources, currentStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AmendmentResource {\n"); + + sb.append(" receipt: ").append(toIndentedString(receipt)).append("\n"); + sb.append(" validityPeriod: ").append(toIndentedString(validityPeriod)).append("\n"); + sb.append(" consentAttributes: ").append(toIndentedString(consentAttributes)).append("\n"); + sb.append(" authorizationResources: ").append(toIndentedString(authorizationResources)).append("\n"); + sb.append(" currentStatus: ").append(toIndentedString(currentStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResponse.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResponse.java new file mode 100644 index 000000000..133bfce9c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AmendmentResponse.java @@ -0,0 +1,280 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("AmendmentResponse") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class AmendmentResponse implements Serializable { + private String clientID; + private String consentType; + private String currentStatus; + private Object receipt; + private Integer validityPeriod; + private Boolean recurringIndicator; + private Object consentAttributes; + private @Valid List<@Valid ReauthorizeResource> authorizationResources = new ArrayList<>(); + + public AmendmentResponse() { + } + + @JsonCreator + public AmendmentResponse( + @JsonProperty(required = true, value = "clientID") String clientID, + @JsonProperty(required = true, value = "consentType") String consentType, + @JsonProperty(required = true, value = "receipt") Object receipt, + @JsonProperty(required = true, value = "validityPeriod") Integer validityPeriod, + @JsonProperty(required = true, value = "recurringIndicator") Boolean recurringIndicator + ) { + this.clientID = clientID; + this.consentType = consentType; + this.receipt = receipt; + this.validityPeriod = validityPeriod; + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public AmendmentResponse clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", required = true, value = "") + @JsonProperty(required = true, value = "clientID") + @NotNull public String getClientID() { + return clientID; + } + + @JsonProperty(required = true, value = "clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public AmendmentResponse consentType(String consentType) { + this.consentType = consentType; + return this; + } + + + @ApiModelProperty(example = "Accounts", required = true, value = "") + @JsonProperty(required = true, value = "consentType") + @NotNull public String getConsentType() { + return consentType; + } + + @JsonProperty(required = true, value = "consentType") + public void setConsentType(String consentType) { + this.consentType = consentType; + } + + /** + * + **/ + public AmendmentResponse currentStatus(String currentStatus) { + this.currentStatus = currentStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorization", value = "") + @JsonProperty("currentStatus") + public String getCurrentStatus() { + return currentStatus; + } + + @JsonProperty("currentStatus") + public void setCurrentStatus(String currentStatus) { + this.currentStatus = currentStatus; + } + + /** + * + **/ + public AmendmentResponse receipt(Object receipt) { + this.receipt = receipt; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "receipt") + @NotNull public Object getReceipt() { + return receipt; + } + + @JsonProperty(required = true, value = "receipt") + public void setReceipt(Object receipt) { + this.receipt = receipt; + } + + /** + * + **/ + public AmendmentResponse validityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + return this; + } + + + @ApiModelProperty(example = "3600", required = true, value = "") + @JsonProperty(required = true, value = "validityPeriod") + @NotNull public Integer getValidityPeriod() { + return validityPeriod; + } + + @JsonProperty(required = true, value = "validityPeriod") + public void setValidityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + } + + /** + * + **/ + public AmendmentResponse recurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "recurringIndicator") + @NotNull public Boolean getRecurringIndicator() { + return recurringIndicator; + } + + @JsonProperty(required = true, value = "recurringIndicator") + public void setRecurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public AmendmentResponse consentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("consentAttributes") + public Object getConsentAttributes() { + return consentAttributes; + } + + @JsonProperty("consentAttributes") + public void setConsentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + } + + /** + * + **/ + public AmendmentResponse authorizationResources(List<@Valid ReauthorizeResource> authorizationResources) { + this.authorizationResources = authorizationResources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authorizationResources") + @Valid public List<@Valid ReauthorizeResource> getAuthorizationResources() { + return authorizationResources; + } + + @JsonProperty("authorizationResources") + public void setAuthorizationResources(List<@Valid ReauthorizeResource> authorizationResources) { + this.authorizationResources = authorizationResources; + } + + public AmendmentResponse addAuthorizationResourcesItem(ReauthorizeResource authorizationResourcesItem) { + if (this.authorizationResources == null) { + this.authorizationResources = new ArrayList<>(); + } + + this.authorizationResources.add(authorizationResourcesItem); + return this; + } + + public AmendmentResponse removeAuthorizationResourcesItem(ReauthorizeResource authorizationResourcesItem) { + if (authorizationResourcesItem != null && this.authorizationResources != null) { + this.authorizationResources.remove(authorizationResourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AmendmentResponse amendmentResponse = (AmendmentResponse) o; + return Objects.equals(this.clientID, amendmentResponse.clientID) && + Objects.equals(this.consentType, amendmentResponse.consentType) && + Objects.equals(this.currentStatus, amendmentResponse.currentStatus) && + Objects.equals(this.receipt, amendmentResponse.receipt) && + Objects.equals(this.validityPeriod, amendmentResponse.validityPeriod) && + Objects.equals(this.recurringIndicator, amendmentResponse.recurringIndicator) && + Objects.equals(this.consentAttributes, amendmentResponse.consentAttributes) && + Objects.equals(this.authorizationResources, amendmentResponse.authorizationResources); + } + + @Override + public int hashCode() { + return Objects.hash(clientID, consentType, currentStatus, receipt, validityPeriod, recurringIndicator, + consentAttributes, authorizationResources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AmendmentResponse {\n"); + + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" consentType: ").append(toIndentedString(consentType)).append("\n"); + sb.append(" currentStatus: ").append(toIndentedString(currentStatus)).append("\n"); + sb.append(" receipt: ").append(toIndentedString(receipt)).append("\n"); + sb.append(" validityPeriod: ").append(toIndentedString(validityPeriod)).append("\n"); + sb.append(" recurringIndicator: ").append(toIndentedString(recurringIndicator)).append("\n"); + sb.append(" consentAttributes: ").append(toIndentedString(consentAttributes)).append("\n"); + sb.append(" authorizationResources: ").append(toIndentedString(authorizationResources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthResponse.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthResponse.java new file mode 100644 index 000000000..cbba7e8fa --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthResponse.java @@ -0,0 +1,208 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("AuthResponse") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class AuthResponse implements Serializable { + private String authorizationId; + private String authorizationStatus; + private String authorizationType; + private String userID; + private @Valid List<@Valid Resource> resources = new ArrayList<>(); + + public AuthResponse() { + } + + @JsonCreator + public AuthResponse( + @JsonProperty(required = true, value = "authId") String authorizationId, + @JsonProperty(required = true, value = "authorizationStatus") String authorizationStatus, + @JsonProperty(required = true, value = "authorizationType") String authorizationType, + @JsonProperty(required = true, value = "userID") String userID + ) { + this.authorizationId = authorizationId; + this.authorizationStatus = authorizationStatus; + this.authorizationType = authorizationType; + this.userID = userID; + } + + /** + * + **/ + public AuthResponse authId(String authId) { + this.authorizationId = authId; + return this; + } + + + @ApiModelProperty(example = "5162ab67-b4e1-4e88-b429-f0bf34fae343", required = true, value = "") + @JsonProperty(required = true, value = "authId") + @NotNull public String getAuthId() { + return authorizationId; + } + + @JsonProperty(required = true, value = "authId") + public void setAuthId(String authId) { + this.authorizationId = authId; + } + + /** + * + **/ + public AuthResponse authorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + return this; + } + + + @ApiModelProperty(example = "created", required = true, value = "") + @JsonProperty(required = true, value = "authorizationStatus") + @NotNull public String getAuthorizationStatus() { + return authorizationStatus; + } + + @JsonProperty(required = true, value = "authorizationStatus") + public void setAuthorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + } + + /** + * + **/ + public AuthResponse authorizationType(String authorizationType) { + this.authorizationType = authorizationType; + return this; + } + + + @ApiModelProperty(example = "authorization", required = true, value = "") + @JsonProperty(required = true, value = "authorizationType") + @NotNull public String getAuthorizationType() { + return authorizationType; + } + + @JsonProperty(required = true, value = "authorizationType") + public void setAuthorizationType(String authorizationType) { + this.authorizationType = authorizationType; + } + + /** + * + **/ + public AuthResponse userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", required = true, value = "") + @JsonProperty(required = true, value = "userID") + @NotNull public String getUserId() { + return userID; + } + + @JsonProperty(required = true, value = "userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public AuthResponse resources(List<@Valid Resource> resources) { + this.resources = resources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("resources") + @Valid public List<@Valid Resource> getResources() { + return resources; + } + + @JsonProperty("resources") + public void setResources(List<@Valid Resource> resources) { + this.resources = resources; + } + + public AuthResponse addResourcesItem(Resource resourcesItem) { + if (this.resources == null) { + this.resources = new ArrayList<>(); + } + + this.resources.add(resourcesItem); + return this; + } + + public AuthResponse removeResourcesItem(Resource resourcesItem) { + if (resourcesItem != null && this.resources != null) { + this.resources.remove(resourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuthResponse authResponse = (AuthResponse) o; + return Objects.equals(this.authorizationId, authResponse.authorizationId) && + Objects.equals(this.authorizationStatus, authResponse.authorizationStatus) && + Objects.equals(this.authorizationType, authResponse.authorizationType) && + Objects.equals(this.userID, authResponse.userID) && + Objects.equals(this.resources, authResponse.resources); + } + + @Override + public int hashCode() { + return Objects.hash(authorizationId, authorizationStatus, authorizationType, userID, resources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuthResponse {\n"); + + sb.append(" authId: ").append(toIndentedString(authorizationId)).append("\n"); + sb.append(" authorizationStatus: ").append(toIndentedString(authorizationStatus)).append("\n"); + sb.append(" authorizationType: ").append(toIndentedString(authorizationType)).append("\n"); + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" resources: ").append(toIndentedString(resources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthorizationResourceDTO.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthorizationResourceDTO.java new file mode 100644 index 000000000..b6ed60e8d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/AuthorizationResourceDTO.java @@ -0,0 +1,183 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("AuthResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class AuthorizationResourceDTO implements Serializable { + private String authorizationStatus; + private String authorizationType; + private String userID; + private @Valid List resources = new ArrayList<>(); + + public AuthorizationResourceDTO() { + } + + @JsonCreator + public AuthorizationResourceDTO( + @JsonProperty(required = true, value = "authorizationStatus") String authorizationStatus, + @JsonProperty(required = true, value = "authorizationType") String authorizationType, + @JsonProperty(required = true, value = "userID") String userID + ) { + this.authorizationStatus = authorizationStatus; + this.authorizationType = authorizationType; + this.userID = userID; + } + + /** + * + **/ + public AuthorizationResourceDTO authorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + return this; + } + + + @ApiModelProperty(example = "created", required = true, value = "") + @JsonProperty(required = true, value = "authorizationStatus") + @NotNull public String getAuthorizationStatus() { + return authorizationStatus; + } + + @JsonProperty(required = true, value = "authorizationStatus") + public void setAuthorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + } + + /** + * + **/ + public AuthorizationResourceDTO authorizationType(String authorizationType) { + this.authorizationType = authorizationType; + return this; + } + + + @ApiModelProperty(example = "authorization", required = true, value = "") + @JsonProperty(required = true, value = "authorizationType") + @NotNull public String getAuthorizationType() { + return authorizationType; + } + + @JsonProperty(required = true, value = "authorizationType") + public void setAuthorizationType(String authorizationType) { + this.authorizationType = authorizationType; + } + + /** + * + **/ + public AuthorizationResourceDTO userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", required = true, value = "") + @JsonProperty(required = true, value = "userID") + @NotNull public String getUserId() { + return userID; + } + + @JsonProperty(required = true, value = "userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public AuthorizationResourceDTO resources(List resources) { + this.resources = resources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("resources") + @Valid public List getResources() { + return resources; + } + + @JsonProperty("resources") + public void setResources(List resources) { + this.resources = resources; + } + + public AuthorizationResourceDTO addResourcesItem(String resourcesItem) { + if (this.resources == null) { + this.resources = new ArrayList<>(); + } + + this.resources.add(resourcesItem); + return this; + } + + public AuthorizationResourceDTO removeResourcesItem(ResourcePermission resourcesItem) { + if (resourcesItem != null && this.resources != null) { + this.resources.remove(resourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AuthorizationResourceDTO authResource = (AuthorizationResourceDTO) o; + return Objects.equals(this.authorizationStatus, authResource.authorizationStatus) && + Objects.equals(this.authorizationType, authResource.authorizationType) && + Objects.equals(this.userID, authResource.userID) && + Objects.equals(this.resources, authResource.resources); + } + + @Override + public int hashCode() { + return Objects.hash(authorizationStatus, authorizationType, userID, resources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuthorizationResourceDTO {\n"); + + sb.append(" authorizationStatus: ").append(toIndentedString(authorizationStatus)).append("\n"); + sb.append(" authorizationType: ").append(toIndentedString(authorizationType)).append("\n"); + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" resources: ").append(toIndentedString(resources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/BulkConsentStatusUpdateResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/BulkConsentStatusUpdateResource.java new file mode 100644 index 000000000..060669bda --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/BulkConsentStatusUpdateResource.java @@ -0,0 +1,222 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("BulkConsentStatusUpdateResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class BulkConsentStatusUpdateResource implements Serializable { + private String clientID; + private String userID; + private String consentType; + private @Valid ArrayList applicableStatusesForStateChange = new ArrayList<>(); + private String status; + private String reason; + + public BulkConsentStatusUpdateResource() { + } + + /** + * + **/ + public BulkConsentStatusUpdateResource clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", value = "") + @JsonProperty("clientID") + public String getClientID() { + return clientID; + } + + @JsonProperty("clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public BulkConsentStatusUpdateResource userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", value = "") + @JsonProperty("userID") + public String getUserId() { + return userID; + } + + @JsonProperty("userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public BulkConsentStatusUpdateResource consentType(String consentType) { + this.consentType = consentType; + return this; + } + + + @ApiModelProperty(example = "Accounts", value = "") + @JsonProperty("consentType") + public String getConsentType() { + return consentType; + } + + @JsonProperty("consentType") + public void setConsentType(String consentType) { + this.consentType = consentType; + } + + /** + * + **/ + public BulkConsentStatusUpdateResource applicableStatusesForStateChange( + ArrayList applicableStatusesForStateChange) { + this.applicableStatusesForStateChange = applicableStatusesForStateChange; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("applicableStatusesForStateChange") + public ArrayList getApplicableStatusesForStateChange() { + return applicableStatusesForStateChange; + } + + @JsonProperty("applicableStatusesForStateChange") + public void setApplicableStatusesForStateChange(ArrayList applicableStatusesForStateChange) { + this.applicableStatusesForStateChange = applicableStatusesForStateChange; + } + + public BulkConsentStatusUpdateResource addApplicableStatusesForStateChangeItem( + String applicableStatusesForStateChangeItem) { + if (this.applicableStatusesForStateChange == null) { + this.applicableStatusesForStateChange = new ArrayList<>(); + } + + this.applicableStatusesForStateChange.add(applicableStatusesForStateChangeItem); + return this; + } + + public BulkConsentStatusUpdateResource removeApplicableStatusesForStateChangeItem( + String applicableStatusesForStateChangeItem) { + if (applicableStatusesForStateChangeItem != null && this.applicableStatusesForStateChange != null) { + this.applicableStatusesForStateChange.remove(applicableStatusesForStateChangeItem); + } + + return this; + } + + /** + * + **/ + public BulkConsentStatusUpdateResource status(String status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "revoked", value = "") + @JsonProperty("status") + public String getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * + **/ + public BulkConsentStatusUpdateResource reason(String reason) { + this.reason = reason; + return this; + } + + + @ApiModelProperty(example = "Revoked by ...", value = "") + @JsonProperty("reason") + public String getReason() { + return reason; + } + + @JsonProperty("reason") + public void setReason(String reason) { + this.reason = reason; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BulkConsentStatusUpdateResource bulkConsentStatusUpdateResource = (BulkConsentStatusUpdateResource) o; + return Objects.equals(this.clientID, bulkConsentStatusUpdateResource.clientID) && + Objects.equals(this.userID, bulkConsentStatusUpdateResource.userID) && + Objects.equals(this.consentType, bulkConsentStatusUpdateResource.consentType) && + Objects.equals(this.applicableStatusesForStateChange, + bulkConsentStatusUpdateResource.applicableStatusesForStateChange) && + Objects.equals(this.status, bulkConsentStatusUpdateResource.status) && + Objects.equals(this.reason, bulkConsentStatusUpdateResource.reason); + } + + @Override + public int hashCode() { + return Objects.hash(clientID, userID, consentType, applicableStatusesForStateChange, status, reason); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BulkConsentStatusUpdateResource {\n"); + + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" consentType: ").append(toIndentedString(consentType)).append("\n"); + sb.append(" applicableStatusesForStateChange: ").append(toIndentedString(applicableStatusesForStateChange)) + .append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentFile.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentFile.java new file mode 100644 index 000000000..f30d9d70d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentFile.java @@ -0,0 +1,174 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.Objects; + + +@JsonTypeName("ConsentFile") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentFile implements Serializable { + private String consentID; + private String consentFile; + private String clientID; + private String userID; + private String applicableStatus; + + public ConsentFile() { + } + + /** + * + **/ + public ConsentFile consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("consentID") + public String getConsentID() { + return consentID; + } + + @JsonProperty("consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public ConsentFile consentFile(String consentFile) { + this.consentFile = consentFile; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("consentFile") + public String getConsentFile() { + return consentFile; + } + + @JsonProperty("consentFile") + public void setConsentFile(String consentFile) { + this.consentFile = consentFile; + } + + /** + * + **/ + public ConsentFile clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", value = "") + @JsonProperty("clientID") + public String getClientID() { + return clientID; + } + + @JsonProperty("clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public ConsentFile userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", value = "") + @JsonProperty("userID") + public String getUserId() { + return userID; + } + + @JsonProperty("userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public ConsentFile applicableStatus(String applicableStatus) { + this.applicableStatus = applicableStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorization", value = "") + @JsonProperty("applicableStatus") + public String getApplicableStatus() { + return applicableStatus; + } + + @JsonProperty("applicableStatus") + public void setApplicableStatus(String applicableStatus) { + this.applicableStatus = applicableStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentFile consentFile = (ConsentFile) o; + return Objects.equals(this.consentID, consentFile.consentID) && + Objects.equals(this.consentFile, consentFile.consentFile) && + Objects.equals(this.clientID, consentFile.clientID) && + Objects.equals(this.userID, consentFile.userID) && + Objects.equals(this.applicableStatus, consentFile.applicableStatus); + } + + @Override + public int hashCode() { + return Objects.hash(consentID, consentFile, clientID, userID, applicableStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentFile {\n"); + + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" consentFile: ").append(toIndentedString(consentFile)).append("\n"); + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" applicableStatus: ").append(toIndentedString(applicableStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentHistory.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentHistory.java new file mode 100644 index 000000000..a1d4cbbc9 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentHistory.java @@ -0,0 +1,199 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("ConsentHistory") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentHistory implements Serializable { + private String historyId; + private String consentID; + private Integer timestamp; + private String reason; + private DetailedConsentResource detailedConsent; + private Object changedMetadata; + + public ConsentHistory() { + } + + /** + * + **/ + public ConsentHistory historyId(String historyId) { + this.historyId = historyId; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("historyId") + public String getHistoryId() { + return historyId; + } + + @JsonProperty("historyId") + public void setHistoryId(String historyId) { + this.historyId = historyId; + } + + /** + * + **/ + public ConsentHistory consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("consentID") + public String getConsentID() { + return consentID; + } + + @JsonProperty("consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public ConsentHistory timestamp(Integer timestamp) { + this.timestamp = timestamp; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("timestamp") + public Integer getTimestamp() { + return timestamp; + } + + @JsonProperty("timestamp") + public void setTimestamp(Integer timestamp) { + this.timestamp = timestamp; + } + + /** + * + **/ + public ConsentHistory reason(String reason) { + this.reason = reason; + return this; + } + + + @ApiModelProperty(example = "amended due to ...", value = "") + @JsonProperty("reason") + public String getReason() { + return reason; + } + + @JsonProperty("reason") + public void setReason(String reason) { + this.reason = reason; + } + + /** + * + **/ + public ConsentHistory detailedConsent(DetailedConsentResource detailedConsent) { + this.detailedConsent = detailedConsent; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("detailedConsent") + @Valid public DetailedConsentResource getDetailedConsent() { + return detailedConsent; + } + + @JsonProperty("detailedConsent") + public void setDetailedConsent(DetailedConsentResource detailedConsent) { + this.detailedConsent = detailedConsent; + } + + /** + * + **/ + public ConsentHistory changedMetadata(Object changedMetadata) { + this.changedMetadata = changedMetadata; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("changedMetadata") + public Object getChangedMetadata() { + return changedMetadata; + } + + @JsonProperty("changedMetadata") + public void setChangedMetadata(Object changedMetadata) { + this.changedMetadata = changedMetadata; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentHistory consentHistory = (ConsentHistory) o; + return Objects.equals(this.historyId, consentHistory.historyId) && + Objects.equals(this.consentID, consentHistory.consentID) && + Objects.equals(this.timestamp, consentHistory.timestamp) && + Objects.equals(this.reason, consentHistory.reason) && + Objects.equals(this.detailedConsent, consentHistory.detailedConsent) && + Objects.equals(this.changedMetadata, consentHistory.changedMetadata); + } + + @Override + public int hashCode() { + return Objects.hash(historyId, consentID, timestamp, reason, detailedConsent, changedMetadata); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentHistory {\n"); + + sb.append(" historyId: ").append(toIndentedString(historyId)).append("\n"); + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n"); + sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); + sb.append(" detailedConsent: ").append(toIndentedString(detailedConsent)).append("\n"); + sb.append(" changedMetadata: ").append(toIndentedString(changedMetadata)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResourceDTO.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResourceDTO.java new file mode 100644 index 000000000..ab3e8d84f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResourceDTO.java @@ -0,0 +1,282 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("ConsentResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentResourceDTO implements Serializable { + private String clientID; + private String consentType; + private String currentStatus; + private String receipt; + private Integer validityPeriod; + private Boolean recurringIndicator; + private Object consentAttributes; + private @Valid List<@Valid AuthorizationResourceDTO> authorizationResources = new ArrayList<>(); + + public ConsentResourceDTO() { + } + + @JsonCreator + public ConsentResourceDTO( + @JsonProperty(required = true, value = "clientID") String clientID, + @JsonProperty(required = true, value = "consentType") String consentType, + @JsonProperty(required = true, value = "currentStatus") String currentStatus, + @JsonProperty(required = true, value = "receipt") String receipt, + @JsonProperty(required = true, value = "validityPeriod") Integer validityPeriod, + @JsonProperty(required = true, value = "recurringIndicator") Boolean recurringIndicator + ) { + this.clientID = clientID; + this.consentType = consentType; + this.currentStatus = currentStatus; + this.receipt = receipt; + this.validityPeriod = validityPeriod; + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public ConsentResourceDTO clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", required = true, value = "") + @JsonProperty(required = true, value = "clientID") + @NotNull public String getClientID() { + return clientID; + } + + @JsonProperty(required = true, value = "clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public ConsentResourceDTO consentType(String consentType) { + this.consentType = consentType; + return this; + } + + + @ApiModelProperty(example = "Accounts", required = true, value = "") + @JsonProperty(required = true, value = "consentType") + @NotNull public String getConsentType() { + return consentType; + } + + @JsonProperty(required = true, value = "consentType") + public void setConsentType(String consentType) { + this.consentType = consentType; + } + + /** + * + **/ + public ConsentResourceDTO currentStatus(String currentStatus) { + this.currentStatus = currentStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorisation", required = true, value = "") + @JsonProperty(required = true, value = "currentStatus") + @NotNull public String getCurrentStatus() { + return currentStatus; + } + + @JsonProperty(required = true, value = "currentStatus") + public void setCurrentStatus(String currentStatus) { + this.currentStatus = currentStatus; + } + + /** + * + **/ + public ConsentResourceDTO receipt(String receipt) { + this.receipt = receipt; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "receipt") + @NotNull public String getReceipt() { + return receipt; + } + + @JsonProperty(required = true, value = "receipt") + public void setReceipt(String receipt) { + this.receipt = receipt; + } + + /** + * + **/ + public ConsentResourceDTO validityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + return this; + } + + + @ApiModelProperty(example = "3600", required = true, value = "") + @JsonProperty(required = true, value = "validityPeriod") + @NotNull public Integer getValidityPeriod() { + return validityPeriod; + } + + @JsonProperty(required = true, value = "validityPeriod") + public void setValidityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + } + + /** + * + **/ + public ConsentResourceDTO recurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "recurringIndicator") + @NotNull public Boolean getRecurringIndicator() { + return recurringIndicator; + } + + @JsonProperty(required = true, value = "recurringIndicator") + public void setRecurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public ConsentResourceDTO consentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("consentAttributes") + public Object getConsentAttributes() { + return consentAttributes; + } + + @JsonProperty("consentAttributes") + public void setConsentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + } + + /** + * + **/ + public ConsentResourceDTO authorizationResources(List<@Valid AuthorizationResourceDTO> authorizationResources) { + this.authorizationResources = authorizationResources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authorizationResources") + @Valid public List<@Valid AuthorizationResourceDTO> getAuthorizationResources() { + return authorizationResources; + } + + @JsonProperty("authorizationResources") + public void setAuthorizationResources(List<@Valid AuthorizationResourceDTO> authorizationResources) { + this.authorizationResources = authorizationResources; + } + + public ConsentResourceDTO addAuthorizationResourcesItem(AuthorizationResourceDTO authorizationResourcesItem) { + if (this.authorizationResources == null) { + this.authorizationResources = new ArrayList<>(); + } + + this.authorizationResources.add(authorizationResourcesItem); + return this; + } + + public ConsentResourceDTO removeAuthorizationResourcesItem(AuthorizationResourceDTO authorizationResourcesItem) { + if (authorizationResourcesItem != null && this.authorizationResources != null) { + this.authorizationResources.remove(authorizationResourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentResourceDTO consentResource = (ConsentResourceDTO) o; + return Objects.equals(this.clientID, consentResource.clientID) && + Objects.equals(this.consentType, consentResource.consentType) && + Objects.equals(this.currentStatus, consentResource.currentStatus) && + Objects.equals(this.receipt, consentResource.receipt) && + Objects.equals(this.validityPeriod, consentResource.validityPeriod) && + Objects.equals(this.recurringIndicator, consentResource.recurringIndicator) && + Objects.equals(this.consentAttributes, consentResource.consentAttributes) && + Objects.equals(this.authorizationResources, consentResource.authorizationResources); + } + + @Override + public int hashCode() { + return Objects.hash(clientID, consentType, currentStatus, receipt, validityPeriod, recurringIndicator, + consentAttributes, authorizationResources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {\n"); + + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" consentType: ").append(toIndentedString(consentType)).append("\n"); + sb.append(" currentStatus: ").append(toIndentedString(currentStatus)).append("\n"); + sb.append(" receipt: ").append(toIndentedString(receipt)).append("\n"); + sb.append(" validityPeriod: ").append(toIndentedString(validityPeriod)).append("\n"); + sb.append(" recurringIndicator: ").append(toIndentedString(recurringIndicator)).append("\n"); + sb.append(" consentAttributes: ").append(toIndentedString(consentAttributes)).append("\n"); + sb.append(" authorizationResources: ").append(toIndentedString(authorizationResources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResponse.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResponse.java new file mode 100644 index 000000000..d4ec9f043 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentResponse.java @@ -0,0 +1,354 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("ConsentResponse") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentResponse implements Serializable { + private String consentID; + private String clientID; + private String consentType; + private String currentStatus; + private Object receipt; + private Integer validityPeriod; + private Boolean recurringIndicator; + private Object consentAttributes; + private List<@Valid AuthResponse> authorizationResources = new ArrayList<>(); + private Integer createdTime; + private Integer updatedTime; + + public ConsentResponse() { + } + + @JsonCreator + public ConsentResponse( + @JsonProperty(required = true, value = "consentID") String consentID, + @JsonProperty(required = true, value = "clientID") String clientID, + @JsonProperty(required = true, value = "consentType") String consentType, + @JsonProperty(required = true, value = "currentStatus") String currentStatus, + @JsonProperty(required = true, value = "receipt") Object receipt, + @JsonProperty(required = true, value = "validityPeriod") Integer validityPeriod, + @JsonProperty(required = true, value = "recurringIndicator") Boolean recurringIndicator + ) { + this.consentID = consentID; + this.clientID = clientID; + this.consentType = consentType; + this.currentStatus = currentStatus; + this.receipt = receipt; + this.validityPeriod = validityPeriod; + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public ConsentResponse consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", required = true, value = "") + @JsonProperty(required = true, value = "consentID") + @NotNull public String getConsentID() { + return consentID; + } + + @JsonProperty(required = true, value = "consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public ConsentResponse clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", required = true, value = "") + @JsonProperty(required = true, value = "clientID") + @NotNull public String getClientID() { + return clientID; + } + + @JsonProperty(required = true, value = "clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public ConsentResponse consentType(String consentType) { + this.consentType = consentType; + return this; + } + + + @ApiModelProperty(example = "Accounts", required = true, value = "") + @JsonProperty(required = true, value = "consentType") + @NotNull public String getConsentType() { + return consentType; + } + + @JsonProperty(required = true, value = "consentType") + public void setConsentType(String consentType) { + this.consentType = consentType; + } + + /** + * + **/ + public ConsentResponse currentStatus(String currentStatus) { + this.currentStatus = currentStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorisation", required = true, value = "") + @JsonProperty(required = true, value = "currentStatus") + @NotNull public String getCurrentStatus() { + return currentStatus; + } + + @JsonProperty(required = true, value = "currentStatus") + public void setCurrentStatus(String currentStatus) { + this.currentStatus = currentStatus; + } + + /** + * + **/ + public ConsentResponse receipt(Object receipt) { + this.receipt = receipt; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "receipt") + @NotNull public Object getReceipt() { + return receipt; + } + + @JsonProperty(required = true, value = "receipt") + public void setReceipt(Object receipt) { + this.receipt = receipt; + } + + /** + * + **/ + public ConsentResponse validityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + return this; + } + + + @ApiModelProperty(example = "3600", required = true, value = "") + @JsonProperty(required = true, value = "validityPeriod") + @NotNull public Integer getValidityPeriod() { + return validityPeriod; + } + + @JsonProperty(required = true, value = "validityPeriod") + public void setValidityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + } + + /** + * + **/ + public ConsentResponse recurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "recurringIndicator") + @NotNull public Boolean getRecurringIndicator() { + return recurringIndicator; + } + + @JsonProperty(required = true, value = "recurringIndicator") + public void setRecurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public ConsentResponse consentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("consentAttributes") + public Object getConsentAttributes() { + return consentAttributes; + } + + @JsonProperty("consentAttributes") + public void setConsentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + } + + /** + * + **/ + public ConsentResponse authorizationResources(List<@Valid AuthResponse> authorizationResources) { + this.authorizationResources = authorizationResources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authorizationResources") + @Valid public List<@Valid AuthResponse> getAuthorizationResources() { + return authorizationResources; + } + + @JsonProperty("authorizationResources") + public void setAuthorizationResources(List<@Valid AuthResponse> authorizationResources) { + this.authorizationResources = authorizationResources; + } + + public ConsentResponse addAuthorizationResourcesItem(AuthResponse authorizationResourcesItem) { + if (this.authorizationResources == null) { + this.authorizationResources = new ArrayList<>(); + } + + this.authorizationResources.add(authorizationResourcesItem); + return this; + } + + public ConsentResponse removeAuthorizationResourcesItem(AuthResponse authorizationResourcesItem) { + if (authorizationResourcesItem != null && this.authorizationResources != null) { + this.authorizationResources.remove(authorizationResourcesItem); + } + + return this; + } + + /** + * + **/ + public ConsentResponse createdTime(Integer createdTime) { + this.createdTime = createdTime; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("createdTime") + public Integer getCreatedTime() { + return createdTime; + } + + @JsonProperty("createdTime") + public void setCreatedTime(Integer createdTime) { + this.createdTime = createdTime; + } + + /** + * + **/ + public ConsentResponse updatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("updatedTime") + public Integer getUpdatedTime() { + return updatedTime; + } + + @JsonProperty("updatedTime") + public void setUpdatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentResponse consentResponse = (ConsentResponse) o; + return Objects.equals(this.consentID, consentResponse.consentID) && + Objects.equals(this.clientID, consentResponse.clientID) && + Objects.equals(this.consentType, consentResponse.consentType) && + Objects.equals(this.currentStatus, consentResponse.currentStatus) && + Objects.equals(this.receipt, consentResponse.receipt) && + Objects.equals(this.validityPeriod, consentResponse.validityPeriod) && + Objects.equals(this.recurringIndicator, consentResponse.recurringIndicator) && + Objects.equals(this.consentAttributes, consentResponse.consentAttributes) && + Objects.equals(this.authorizationResources, consentResponse.authorizationResources) && + Objects.equals(this.createdTime, consentResponse.createdTime) && + Objects.equals(this.updatedTime, consentResponse.updatedTime); + } + + @Override + public int hashCode() { + return Objects.hash(consentID, clientID, consentType, currentStatus, receipt, validityPeriod, + recurringIndicator, consentAttributes, authorizationResources, createdTime, updatedTime); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentResponse {\n"); + + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" consentType: ").append(toIndentedString(consentType)).append("\n"); + sb.append(" currentStatus: ").append(toIndentedString(currentStatus)).append("\n"); + sb.append(" receipt: ").append(toIndentedString(receipt)).append("\n"); + sb.append(" validityPeriod: ").append(toIndentedString(validityPeriod)).append("\n"); + sb.append(" recurringIndicator: ").append(toIndentedString(recurringIndicator)).append("\n"); + sb.append(" consentAttributes: ").append(toIndentedString(consentAttributes)).append("\n"); + sb.append(" authorizationResources: ").append(toIndentedString(authorizationResources)).append("\n"); + sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n"); + sb.append(" updatedTime: ").append(toIndentedString(updatedTime)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentStatusUpdateResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentStatusUpdateResource.java new file mode 100644 index 000000000..ed94f00ac --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentStatusUpdateResource.java @@ -0,0 +1,128 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.Objects; + + +@JsonTypeName("ConsentStatusUpdateResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentStatusUpdateResource implements Serializable { + private String userID; + private String status; + private String reason; + + public ConsentStatusUpdateResource() { + } + + /** + * + **/ + public ConsentStatusUpdateResource userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", value = "") + @JsonProperty("userID") + public String getUserId() { + return userID; + } + + @JsonProperty("userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public ConsentStatusUpdateResource status(String status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "revoked", value = "") + @JsonProperty("status") + public String getStatus() { + return status; + } + + @JsonProperty("status") + public void setStatus(String status) { + this.status = status; + } + + /** + * + **/ + public ConsentStatusUpdateResource reason(String reason) { + this.reason = reason; + return this; + } + + + @ApiModelProperty(example = "Revoked by ...", value = "") + @JsonProperty("reason") + public String getReason() { + return reason; + } + + @JsonProperty("reason") + public void setReason(String reason) { + this.reason = reason; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentStatusUpdateResource consentStatusUpdateResource = (ConsentStatusUpdateResource) o; + return Objects.equals(this.userID, consentStatusUpdateResource.userID) && + Objects.equals(this.status, consentStatusUpdateResource.status) && + Objects.equals(this.reason, consentStatusUpdateResource.reason); + } + + @Override + public int hashCode() { + return Objects.hash(userID, status, reason); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentStatusUpdateResource {\n"); + + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" reason: ").append(toIndentedString(reason)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMapping.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMapping.java new file mode 100644 index 000000000..d31ba713d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMapping.java @@ -0,0 +1,171 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("ConsentUserMapping") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentUserMapping implements Serializable { + private String consentID; + private String newConsentStatus; + private AuthResponse authResource; + private @Valid List<@Valid ResourcePermission> resources = new ArrayList<>(); + + public ConsentUserMapping() { + } + + /** + * + **/ + public ConsentUserMapping consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("consentID") + public String getConsentID() { + return consentID; + } + + @JsonProperty("consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public ConsentUserMapping newConsentStatus(String newConsentStatus) { + this.newConsentStatus = newConsentStatus; + return this; + } + + + @ApiModelProperty(example = "created", value = "") + @JsonProperty("newConsentStatus") + public String getNewConsentStatus() { + return newConsentStatus; + } + + @JsonProperty("newConsentStatus") + public void setNewConsentStatus(String newConsentStatus) { + this.newConsentStatus = newConsentStatus; + } + + /** + * + **/ + public ConsentUserMapping authResource(AuthResponse authResource) { + this.authResource = authResource; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authResource") + @Valid public AuthResponse getAuthResource() { + return authResource; + } + + @JsonProperty("authResource") + public void setAuthResource(AuthResponse authResource) { + this.authResource = authResource; + } + + /** + * + **/ + public ConsentUserMapping resources(List<@Valid ResourcePermission> resources) { + this.resources = resources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("resources") + @Valid public List<@Valid ResourcePermission> getResources() { + return resources; + } + + @JsonProperty("resources") + public void setResources(List<@Valid ResourcePermission> resources) { + this.resources = resources; + } + + public ConsentUserMapping addResourcesItem(ResourcePermission resourcesItem) { + if (this.resources == null) { + this.resources = new ArrayList<>(); + } + + this.resources.add(resourcesItem); + return this; + } + + public ConsentUserMapping removeResourcesItem(ResourcePermission resourcesItem) { + if (resourcesItem != null && this.resources != null) { + this.resources.remove(resourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentUserMapping consentUserMapping = (ConsentUserMapping) o; + return Objects.equals(this.consentID, consentUserMapping.consentID) && + Objects.equals(this.newConsentStatus, consentUserMapping.newConsentStatus) && + Objects.equals(this.authResource, consentUserMapping.authResource) && + Objects.equals(this.resources, consentUserMapping.resources); + } + + @Override + public int hashCode() { + return Objects.hash(consentID, newConsentStatus, authResource, resources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentUserMapping {\n"); + + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" newConsentStatus: ").append(toIndentedString(newConsentStatus)).append("\n"); + sb.append(" authResource: ").append(toIndentedString(authResource)).append("\n"); + sb.append(" resources: ").append(toIndentedString(resources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMappingResponse.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMappingResponse.java new file mode 100644 index 000000000..3f65c7211 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ConsentUserMappingResponse.java @@ -0,0 +1,130 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("ConsentUserMappingResponse") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ConsentUserMappingResponse implements Serializable { + private String consentID; + private AuthResponse authResource; + private Integer updatedTime; + + public ConsentUserMappingResponse() { + } + + /** + * + **/ + public ConsentUserMappingResponse consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("consentID") + public String getConsentID() { + return consentID; + } + + @JsonProperty("consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public ConsentUserMappingResponse authResource(AuthResponse authResource) { + this.authResource = authResource; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authResource") + @Valid public AuthResponse getAuthResource() { + return authResource; + } + + @JsonProperty("authResource") + public void setAuthResource(AuthResponse authResource) { + this.authResource = authResource; + } + + /** + * + **/ + public ConsentUserMappingResponse updatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("updatedTime") + public Integer getUpdatedTime() { + return updatedTime; + } + + @JsonProperty("updatedTime") + public void setUpdatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ConsentUserMappingResponse consentUserMappingResponse = (ConsentUserMappingResponse) o; + return Objects.equals(this.consentID, consentUserMappingResponse.consentID) && + Objects.equals(this.authResource, consentUserMappingResponse.authResource) && + Objects.equals(this.updatedTime, consentUserMappingResponse.updatedTime); + } + + @Override + public int hashCode() { + return Objects.hash(consentID, authResource, updatedTime); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ConsentUserMappingResponse {\n"); + + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" authResource: ").append(toIndentedString(authResource)).append("\n"); + sb.append(" updatedTime: ").append(toIndentedString(updatedTime)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/DetailedConsentResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/DetailedConsentResource.java new file mode 100644 index 000000000..c22562e98 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/DetailedConsentResource.java @@ -0,0 +1,352 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + + +@JsonTypeName("DetailedConsentResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class DetailedConsentResource implements Serializable { + private String consentID; + private String clientID; + private String consentType; + private String currentStatus; + private Object receipt; + private Integer validityPeriod; + private Boolean recurringIndicator; + private Object consentAttributes; + private @Valid List<@Valid AuthResponse> authorizationResources = new ArrayList<>(); + private Integer createdTime; + private Integer updatedTime; + + public DetailedConsentResource() { + } + + @JsonCreator + public DetailedConsentResource( + @JsonProperty(required = true, value = "clientID") String clientID, + @JsonProperty(required = true, value = "consentType") String consentType, + @JsonProperty(required = true, value = "currentStatus") String currentStatus, + @JsonProperty(required = true, value = "receipt") Object receipt, + @JsonProperty(required = true, value = "validityPeriod") Integer validityPeriod, + @JsonProperty(required = true, value = "recurringIndicator") Boolean recurringIndicator + ) { + this.clientID = clientID; + this.consentType = consentType; + this.currentStatus = currentStatus; + this.receipt = receipt; + this.validityPeriod = validityPeriod; + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public DetailedConsentResource consentID(String consentID) { + this.consentID = consentID; + return this; + } + + + @ApiModelProperty(example = "604d9278-4c3b-45d5-b3bb-1e428acdf1ec", value = "") + @JsonProperty("consentID") + public String getConsentID() { + return consentID; + } + + @JsonProperty("consentID") + public void setConsentID(String consentID) { + this.consentID = consentID; + } + + /** + * + **/ + public DetailedConsentResource clientID(String clientID) { + this.clientID = clientID; + return this; + } + + + @ApiModelProperty(example = "TUwYBlObBMmu7zvDnnhs96rZHxka", required = true, value = "") + @JsonProperty(required = true, value = "clientID") + @NotNull public String getClientID() { + return clientID; + } + + @JsonProperty(required = true, value = "clientID") + public void setClientID(String clientID) { + this.clientID = clientID; + } + + /** + * + **/ + public DetailedConsentResource consentType(String consentType) { + this.consentType = consentType; + return this; + } + + + @ApiModelProperty(example = "Accounts", required = true, value = "") + @JsonProperty(required = true, value = "consentType") + @NotNull public String getConsentType() { + return consentType; + } + + @JsonProperty(required = true, value = "consentType") + public void setConsentType(String consentType) { + this.consentType = consentType; + } + + /** + * + **/ + public DetailedConsentResource currentStatus(String currentStatus) { + this.currentStatus = currentStatus; + return this; + } + + + @ApiModelProperty(example = "awaitingAuthorisation", required = true, value = "") + @JsonProperty(required = true, value = "currentStatus") + @NotNull public String getCurrentStatus() { + return currentStatus; + } + + @JsonProperty(required = true, value = "currentStatus") + public void setCurrentStatus(String currentStatus) { + this.currentStatus = currentStatus; + } + + /** + * + **/ + public DetailedConsentResource receipt(Object receipt) { + this.receipt = receipt; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "receipt") + @NotNull public Object getReceipt() { + return receipt; + } + + @JsonProperty(required = true, value = "receipt") + public void setReceipt(Object receipt) { + this.receipt = receipt; + } + + /** + * + **/ + public DetailedConsentResource validityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + return this; + } + + + @ApiModelProperty(example = "3600", required = true, value = "") + @JsonProperty(required = true, value = "validityPeriod") + @NotNull public Integer getValidityPeriod() { + return validityPeriod; + } + + @JsonProperty(required = true, value = "validityPeriod") + public void setValidityPeriod(Integer validityPeriod) { + this.validityPeriod = validityPeriod; + } + + /** + * + **/ + public DetailedConsentResource recurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + return this; + } + + + @ApiModelProperty(required = true, value = "") + @JsonProperty(required = true, value = "recurringIndicator") + @NotNull public Boolean getRecurringIndicator() { + return recurringIndicator; + } + + @JsonProperty(required = true, value = "recurringIndicator") + public void setRecurringIndicator(Boolean recurringIndicator) { + this.recurringIndicator = recurringIndicator; + } + + /** + * + **/ + public DetailedConsentResource consentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("consentAttributes") + public Object getConsentAttributes() { + return consentAttributes; + } + + @JsonProperty("consentAttributes") + public void setConsentAttributes(Object consentAttributes) { + this.consentAttributes = consentAttributes; + } + + /** + * + **/ + public DetailedConsentResource authorizationResources(List<@Valid AuthResponse> authorizationResources) { + this.authorizationResources = authorizationResources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("authorizationResources") + @Valid public List<@Valid AuthResponse> getAuthorizationResources() { + return authorizationResources; + } + + @JsonProperty("authorizationResources") + public void setAuthorizationResources(List<@Valid AuthResponse> authorizationResources) { + this.authorizationResources = authorizationResources; + } + + public DetailedConsentResource addAuthorizationResourcesItem(AuthResponse authorizationResourcesItem) { + if (this.authorizationResources == null) { + this.authorizationResources = new ArrayList<>(); + } + + this.authorizationResources.add(authorizationResourcesItem); + return this; + } + + public DetailedConsentResource removeAuthorizationResourcesItem(AuthResponse authorizationResourcesItem) { + if (authorizationResourcesItem != null && this.authorizationResources != null) { + this.authorizationResources.remove(authorizationResourcesItem); + } + + return this; + } + + /** + * + **/ + public DetailedConsentResource createdTime(Integer createdTime) { + this.createdTime = createdTime; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("createdTime") + public Integer getCreatedTime() { + return createdTime; + } + + @JsonProperty("createdTime") + public void setCreatedTime(Integer createdTime) { + this.createdTime = createdTime; + } + + /** + * + **/ + public DetailedConsentResource updatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("updatedTime") + public Integer getUpdatedTime() { + return updatedTime; + } + + @JsonProperty("updatedTime") + public void setUpdatedTime(Integer updatedTime) { + this.updatedTime = updatedTime; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DetailedConsentResource detailedConsentResource = (DetailedConsentResource) o; + return Objects.equals(this.consentID, detailedConsentResource.consentID) && + Objects.equals(this.clientID, detailedConsentResource.clientID) && + Objects.equals(this.consentType, detailedConsentResource.consentType) && + Objects.equals(this.currentStatus, detailedConsentResource.currentStatus) && + Objects.equals(this.receipt, detailedConsentResource.receipt) && + Objects.equals(this.validityPeriod, detailedConsentResource.validityPeriod) && + Objects.equals(this.recurringIndicator, detailedConsentResource.recurringIndicator) && + Objects.equals(this.consentAttributes, detailedConsentResource.consentAttributes) && + Objects.equals(this.authorizationResources, detailedConsentResource.authorizationResources) && + Objects.equals(this.createdTime, detailedConsentResource.createdTime) && + Objects.equals(this.updatedTime, detailedConsentResource.updatedTime); + } + + @Override + public int hashCode() { + return Objects.hash(consentID, clientID, consentType, currentStatus, receipt, validityPeriod, + recurringIndicator, consentAttributes, authorizationResources, createdTime, updatedTime); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DetailedConsentResource {\n"); + + sb.append(" consentID: ").append(toIndentedString(consentID)).append("\n"); + sb.append(" clientID: ").append(toIndentedString(clientID)).append("\n"); + sb.append(" consentType: ").append(toIndentedString(consentType)).append("\n"); + sb.append(" currentStatus: ").append(toIndentedString(currentStatus)).append("\n"); + sb.append(" receipt: ").append(toIndentedString(receipt)).append("\n"); + sb.append(" validityPeriod: ").append(toIndentedString(validityPeriod)).append("\n"); + sb.append(" recurringIndicator: ").append(toIndentedString(recurringIndicator)).append("\n"); + sb.append(" consentAttributes: ").append(toIndentedString(consentAttributes)).append("\n"); + sb.append(" authorizationResources: ").append(toIndentedString(authorizationResources)).append("\n"); + sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n"); + sb.append(" updatedTime: ").append(toIndentedString(updatedTime)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ReauthorizeResource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ReauthorizeResource.java new file mode 100644 index 000000000..82a613f58 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ReauthorizeResource.java @@ -0,0 +1,194 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; + + +@JsonTypeName("ReauthorizeResource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ReauthorizeResource implements Serializable { + private String authorizationId; + private String userID; + private String authorizationStatus; + private String authorizationType; + private @Valid List<@Valid Resource> resources = new ArrayList<>(); + + public ReauthorizeResource() { + } + + /** + * + **/ + public ReauthorizeResource authId(String authId) { + this.authorizationId = authId; + return this; + } + + + @ApiModelProperty(example = "5162ab67-b4e1-4e88-b429-f0bf34fae343", value = "") + @JsonProperty("authId") + public String getAuthorizationId() { + return authorizationId; + } + + @JsonProperty("authId") + public void setAuthorizationId(String authId) { + this.authorizationId = authId; + } + + /** + * + **/ + public ReauthorizeResource userID(String userID) { + this.userID = userID; + return this; + } + + + @ApiModelProperty(example = "psu@wso2.com", value = "") + @JsonProperty("userID") + public String getUserId() { + return userID; + } + + @JsonProperty("userID") + public void setUserId(String userID) { + this.userID = userID; + } + + /** + * + **/ + public ReauthorizeResource authorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + return this; + } + + + @ApiModelProperty(example = "created", value = "") + @JsonProperty("authorizationStatus") + public String getAuthorizationStatus() { + return authorizationStatus; + } + + @JsonProperty("authorizationStatus") + public void setAuthorizationStatus(String authorizationStatus) { + this.authorizationStatus = authorizationStatus; + } + + /** + * + **/ + public ReauthorizeResource authorizationType(String authorizationType) { + this.authorizationType = authorizationType; + return this; + } + + + @ApiModelProperty(example = "authorization", value = "") + @JsonProperty("authorizationType") + public String getAuthorizationType() { + return authorizationType; + } + + @JsonProperty("authorizationType") + public void setAuthorizationType(String authorizationType) { + this.authorizationType = authorizationType; + } + + /** + * + **/ + public ReauthorizeResource resources(List<@Valid Resource> resources) { + this.resources = resources; + return this; + } + + + @ApiModelProperty(value = "") + @JsonProperty("resources") + @Valid public List<@Valid Resource> getResources() { + return resources; + } + + @JsonProperty("resources") + public void setResources(List<@Valid Resource> resources) { + this.resources = resources; + } + + public ReauthorizeResource addResourcesItem(Resource resourcesItem) { + if (this.resources == null) { + this.resources = new ArrayList<>(); + } + + this.resources.add(resourcesItem); + return this; + } + + public ReauthorizeResource removeResourcesItem(Resource resourcesItem) { + if (resourcesItem != null && this.resources != null) { + this.resources.remove(resourcesItem); + } + + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReauthorizeResource reauthorizeResource = (ReauthorizeResource) o; + return Objects.equals(this.authorizationId, reauthorizeResource.authorizationId) && + Objects.equals(this.userID, reauthorizeResource.userID) && + Objects.equals(this.authorizationStatus, reauthorizeResource.authorizationStatus) && + Objects.equals(this.authorizationType, reauthorizeResource.authorizationType) && + Objects.equals(this.resources, reauthorizeResource.resources); + } + + @Override + public int hashCode() { + return Objects.hash(authorizationId, userID, authorizationStatus, authorizationType, resources); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReauthorizeResource {\n"); + + sb.append(" authId: ").append(toIndentedString(authorizationId)).append("\n"); + sb.append(" userID: ").append(toIndentedString(userID)).append("\n"); + sb.append(" authorizationStatus: ").append(toIndentedString(authorizationStatus)).append("\n"); + sb.append(" authorizationType: ").append(toIndentedString(authorizationType)).append("\n"); + sb.append(" resources: ").append(toIndentedString(resources)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/Resource.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/Resource.java new file mode 100644 index 000000000..84717076f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/Resource.java @@ -0,0 +1,101 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; +import net.minidev.json.JSONObject; + +import java.io.Serializable; +import java.util.Objects; + + +@JsonTypeName("Resource") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class Resource implements Serializable { + private JSONObject resource; + private String resourceMappingId; + private String consentMappingStatus; + + + public Resource() { + } + + public String getConsentMappingStatus() { + return consentMappingStatus; + } + + public void setConsentMappingStatus(String consentMappingStatus) { + this.consentMappingStatus = consentMappingStatus; + } + + public Resource resourceMappingId(String resourceMappingId) { + this.resourceMappingId = resourceMappingId; + return this; + } + + + @ApiModelProperty(example = "1242334", value = "") + @JsonProperty("resourceMappingId") + public String getResourceMappingId() { + return resourceMappingId; + } + + @JsonProperty("resourceMappingId") + public void setResourceMappingId(String resourceMappingId) { + this.resourceMappingId = resourceMappingId; + } + + + public JSONObject getResource() { + return resource; + } + + public void setResource(JSONObject resource) { + this.resource = resource; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Resource resource = (Resource) o; + return + Objects.equals(this.resourceMappingId, resource.resourceMappingId) && + Objects.equals(this.resource, resource.resource); + } + + @Override + public int hashCode() { + return Objects.hash(resourceMappingId, resource); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Resource {\n"); + sb.append(" resourceMappingId: ").append(toIndentedString(resourceMappingId)).append("\n"); + sb.append(" resource: ").append(toIndentedString(resource)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ResourcePermission.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ResourcePermission.java new file mode 100644 index 000000000..b23f73380 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/model/ResourcePermission.java @@ -0,0 +1,105 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.model; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.Objects; + + +@JsonTypeName("ResourcePermission") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen", + date = "2025-03-03T09:27:49.560668411+05:30[Asia/Colombo]", comments = "Generator version: 7.12.0") +public class ResourcePermission implements Serializable { + private String accountID; + private String permission; + + public ResourcePermission() { + } + + /** + * + **/ + public ResourcePermission accountID(String accountID) { + this.accountID = accountID; + return this; + } + + + @ApiModelProperty(example = "account1234", value = "") + @JsonProperty("accountID") + public String getAccountID() { + return accountID; + } + + @JsonProperty("accountID") + public void setAccountID(String accountID) { + this.accountID = accountID; + } + + /** + * + **/ + public ResourcePermission permission(String permission) { + this.permission = permission; + return this; + } + + + @ApiModelProperty(example = "read", value = "") + @JsonProperty("permission") + public String getPermission() { + return permission; + } + + @JsonProperty("permission") + public void setPermission(String permission) { + this.permission = permission; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ResourcePermission resourcePermission = (ResourcePermission) o; + return Objects.equals(this.accountID, resourcePermission.accountID) && + Objects.equals(this.permission, resourcePermission.permission); + } + + @Override + public int hashCode() { + return Objects.hash(accountID, permission); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ResourcePermission {\n"); + + sb.append(" accountID: ").append(toIndentedString(accountID)).append("\n"); + sb.append(" permission: ").append(toIndentedString(permission)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/ConsentUtils.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/ConsentUtils.java new file mode 100644 index 000000000..88fe0b1e7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/ConsentUtils.java @@ -0,0 +1,322 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONArray; +import org.json.JSONObject; +import org.wso2.financial.services.accelerator.consent.mgt.dao.exceptions.ConsentMgtException; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.AuthorizationResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentMappingResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.ConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.dao.models.DetailedConsentResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.constants.ConsentConstant; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AuthResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.AuthorizationResourceDTO; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResourceDTO; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ConsentResponse; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.ReauthorizeResource; +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.model.Resource; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import javax.ws.rs.core.Response; + + +/** + * ConsentUtils. + */ +public class ConsentUtils { + + + + /** + * Validate the consent ID. + * + * @param consentId Consent Id to validate + * @return Whether the consent ID is valid + */ + public static boolean isConsentIdValid(String consentId) { + return (Pattern.matches(ConsentConstant.UUID_REGEX, + consentId)); + } + + + + public static Map convertToMap(Object obj) throws + ConsentMgtException { + + try { + ObjectMapper objectMapper = new ObjectMapper(); + Map map = objectMapper.convertValue(obj, Map.class); + if (map == null) { + return new HashMap<>(); + } + return map.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toString())); + } catch (IllegalArgumentException e) { + throw new ConsentMgtException(Response.Status.BAD_REQUEST, "Invalid consent attributes"); + } + } + + /** + * copy propoerties from consentResource DTO to consentResource DAO + * + * @param consentResourceDTO + */ + public static void copyPropertiesToConsentResource(ConsentResource consentResource, + ConsentResourceDTO consentResourceDTO) throws + ConsentMgtException { + consentResource.setConsentType(consentResourceDTO.getConsentType()); + consentResource.setClientID(consentResourceDTO.getClientID()); + consentResource.setRecurringIndicator(consentResourceDTO.getRecurringIndicator()); + consentResource.setValidityPeriod(consentResourceDTO.getValidityPeriod()); + consentResource.setConsentAttributes(ConsentUtils.convertToMap(consentResourceDTO.getConsentAttributes())); + consentResource.setReceipt(consentResourceDTO.getReceipt()); + consentResource.setCurrentStatus(consentResourceDTO.getCurrentStatus()); + + + } + + /** + * copy properties from authorizationResourceDTo to authorizationResource + */ + public static void copyPropertiesToAuthorizationResource(AuthorizationResource authorizationResource, + AuthorizationResourceDTO authorizationResourceDTO) { + authorizationResource.setAuthorizationType(authorizationResourceDTO.getAuthorizationType()); + authorizationResource.setAuthorizationStatus(authorizationResourceDTO.getAuthorizationStatus()); + authorizationResource.setUserID(authorizationResourceDTO.getUserId()); + } + + /** + * copy properties from authorizationResourceDTo to authorizationResource + */ + public static void copyPropertiesToAuthorizationResource(AuthorizationResource authorizationResource, + ReauthorizeResource authorizationResourceDTO) { + authorizationResource.setAuthorizationID(authorizationResourceDTO.getAuthorizationId()); + authorizationResource.setAuthorizationType(authorizationResourceDTO.getAuthorizationType()); + authorizationResource.setAuthorizationStatus(authorizationResourceDTO.getAuthorizationStatus()); + authorizationResource.setUserID(authorizationResourceDTO.getUserId()); + ArrayList consentMappingResources = new ArrayList<>(); + for (Resource resource : authorizationResourceDTO.getResources()) { + ConsentMappingResource consentMappingResource = new ConsentMappingResource(); + consentMappingResource.setResource(resource.getResource()); + consentMappingResource.setMappingID(resource.getResourceMappingId()); + consentMappingResource.setMappingStatus(resource.getConsentMappingStatus()); + consentMappingResources.add(consentMappingResource); + + } + authorizationResource.setConsentMappingResource(consentMappingResources); + + } + + + /** + * copy properties from consentResource to consentResponse + */ + public static void buildAuthorizationResourceResponse(AuthResponse authorizationResourceResponseResponse, + AuthorizationResource authorizationResource, + ArrayList consentMappingResources) { + authorizationResourceResponseResponse.setAuthId(authorizationResource.getAuthorizationID()); + authorizationResourceResponseResponse.setUserId(authorizationResource.getUserID()); + authorizationResourceResponseResponse.setAuthorizationStatus(authorizationResource.getAuthorizationStatus()); + authorizationResourceResponseResponse.setAuthorizationType(authorizationResource.getAuthorizationType()); + + ArrayList resources = new ArrayList<>(); + + if (consentMappingResources != null) { + for (ConsentMappingResource consentMappingResource : consentMappingResources) { + Resource res = new Resource(); + buildConsentMappingResourceResponse(res, consentMappingResource); + resources.add(res); + } + } + + authorizationResourceResponseResponse.setResources(resources); + + + } + + /** + * copy properties from consentResource to consentResponse + */ + public static void buildAuthorizationResourceResponse(AuthorizationResource authorizationResourceResponseResponse, + AuthorizationResource authorizationResource, + ArrayList consentMappingResources) { + authorizationResourceResponseResponse.setAuthorizationID(authorizationResource.getAuthorizationID()); + authorizationResourceResponseResponse.setUserID(authorizationResource.getUserID()); + authorizationResourceResponseResponse.setAuthorizationStatus(authorizationResource.getAuthorizationStatus()); + authorizationResourceResponseResponse.setAuthorizationType(authorizationResource.getAuthorizationType()); + + + authorizationResourceResponseResponse.setConsentMappingResource(consentMappingResources); + + + } + + /** + * copy properties from consentResourceMapping to consentResourceMappingResponse + */ + public static void buildConsentMappingResourceResponse(Resource consentMappingResourceResponse, + ConsentMappingResource consentMappingResource) { + consentMappingResourceResponse.setResourceMappingId(consentMappingResource.getMappingID()); + consentMappingResourceResponse.setResource(consentMappingResource.getResource()); + consentMappingResourceResponse.setConsentMappingStatus(consentMappingResource.getMappingStatus()); + + } + + /** + * copy properties to consentResourceResponse + */ + public static void buildConsentResourceResponse(ConsentResponse consentResourceResponse, + DetailedConsentResource consentResource, + ArrayList authorizationResources, + ArrayList consentMappingResources, + boolean withAttributes) { + consentResourceResponse.setConsentID(consentResource.getConsentID()); + consentResourceResponse.setClientID(consentResource.getClientID()); + consentResourceResponse.setConsentType(consentResource.getConsentType()); + consentResourceResponse.setRecurringIndicator(consentResource.isRecurringIndicator()); + consentResourceResponse.setCreatedTime((int) consentResource.getCreatedTime()); + consentResourceResponse.setValidityPeriod((int) consentResource.getValidityPeriod()); + consentResourceResponse.setCurrentStatus(consentResource.getCurrentStatus()); + consentResourceResponse.setUpdatedTime((int) consentResource.getUpdatedTime()); + consentResourceResponse.setReceipt(consentResource.getReceipt()); + + if (withAttributes) { + consentResourceResponse.setConsentAttributes(consentResource.getConsentAttributes()); + + } + + // get consent mapping resources for each AuthorizationResource + Map> consentMappingResourcesMap = new HashMap<>(); + for (ConsentMappingResource consentMappingResource : consentMappingResources) { + if (!consentMappingResourcesMap.containsKey(consentMappingResource.getAuthorizationID())) { + consentMappingResourcesMap.put(consentMappingResource.getAuthorizationID(), + new ArrayList<>()); + } + consentMappingResourcesMap.get(consentMappingResource.getAuthorizationID()).add(consentMappingResource); + } + + if (authorizationResources != null) { + ArrayList authResponses = new ArrayList<>(); + for (AuthorizationResource authorizationResource : authorizationResources) { + + AuthResponse authResponse = new AuthResponse(); + buildAuthorizationResourceResponse(authResponse, authorizationResource, + consentMappingResourcesMap.get(authorizationResource.getAuthorizationID())); + authResponses.add(authResponse); + } + consentResourceResponse.setAuthorizationResources(authResponses); + } + } + + + /** + * Convert detailed consent resource to JSON. + * + * @param detailedConsentResource detailed consent resource + * @return JSON object constructed from the detailed consent resource + */ + public static JSONObject detailedConsentToJSON(DetailedConsentResource detailedConsentResource) { + JSONObject consentResource = new JSONObject(); + + consentResource.put(ConsentConstant.CC_CONSENT_ID, + detailedConsentResource.getConsentID()); + consentResource.put(ConsentConstant.CLIENT_ID, + detailedConsentResource.getClientID()); + consentResource.put(ConsentConstant.RECEIPT, + detailedConsentResource.getReceipt()); + + consentResource.put(ConsentConstant.CONSENT_TYPE, + detailedConsentResource.getConsentType()); + consentResource.put(ConsentConstant.CURRENT_STATUS, + detailedConsentResource.getCurrentStatus()); + consentResource.put(ConsentConstant.CONSENT_FREQUENCY, + detailedConsentResource.getConsentFrequency()); + consentResource.put(ConsentConstant.VALIDITY_PERIOD, + detailedConsentResource.getValidityPeriod()); + consentResource.put(ConsentConstant.CREATED_TIMESTAMP, + detailedConsentResource.getCreatedTime()); + consentResource.put(ConsentConstant.UPDATED_TIMESTAMP, + detailedConsentResource.getUpdatedTime()); + consentResource.put(ConsentConstant.RECURRING_INDICATOR, + detailedConsentResource.isRecurringIndicator()); + JSONObject attributes = new JSONObject(); + Map attMap = detailedConsentResource.getConsentAttributes(); + for (Map.Entry entry : attMap.entrySet()) { + attributes.put(entry.getKey(), + entry.getValue()); + } + consentResource.put(ConsentConstant.CONSENT_ATTRIBUTES, + attributes); + JSONArray authorizationResources = new JSONArray(); + ArrayList authArray = detailedConsentResource.getAuthorizationResources(); + for (AuthorizationResource resource : authArray) { + JSONObject resourceJSON = new JSONObject(); + resourceJSON.put(ConsentConstant.AUTH_ID, + resource.getAuthorizationID()); + resourceJSON.put(ConsentConstant.CC_CONSENT_ID, + resource.getConsentID()); + resourceJSON.put(ConsentConstant.USER_ID, + resource.getUserID()); + resourceJSON.put(ConsentConstant.AUTH_STATUS, + resource.getAuthorizationStatus()); + resourceJSON.put(ConsentConstant.AUTH_TYPE, + resource.getAuthorizationType()); + resourceJSON.put(ConsentConstant.UPDATE_TIME, + resource.getUpdatedTime()); + authorizationResources.put(resourceJSON); + } + consentResource.put(ConsentConstant.AUTH_RESOURCES, + authorizationResources); + JSONArray consentMappingResources = new JSONArray(); + ArrayList mappingArray = detailedConsentResource.getConsentMappingResources(); + for (ConsentMappingResource resource : mappingArray) { + JSONObject resourceJSON = new JSONObject(); + resourceJSON.put(ConsentConstant.MAPPING_ID, + resource.getMappingID()); + resourceJSON.put(ConsentConstant.AUTH_ID, + resource.getAuthorizationID()); + resourceJSON.put(ConsentConstant.ACCOUNT_ID, + resource.getAccountID()); + resourceJSON.put(ConsentConstant.PERMISSION, + resource.getPermission()); + resourceJSON.put(ConsentConstant.MAPPING_STATUS, + resource.getMappingStatus()); + consentMappingResources.put(resourceJSON); + } + consentResource.put(ConsentConstant.MAPPING_RESOURCES, + consentMappingResources); + return consentResource; + } + + /** + * Convert detailed consent resource to JSON. + * + * @param consentResource consent resource + * @return JSON object constructed from the consent resource + */ + public static JSONObject consentResourceToJSON(ConsentResource consentResource) { + JSONObject consentResourceJSON = new JSONObject(); + consentResourceJSON.put(ConsentConstant.CONSENT_ID, + consentResource.getConsentID()); + consentResourceJSON.put(ConsentConstant.CLIENT_ID, + consentResource.getClientID()); + consentResourceJSON.put(ConsentConstant.CONSENT_TYPE, + consentResource.getConsentType()); + consentResourceJSON.put(ConsentConstant.CURRENT_STATUS, + consentResource.getCurrentStatus()); + consentResourceJSON.put(ConsentConstant.RECURRING_INDICATOR, + consentResource.isRecurringIndicator()); + consentResourceJSON.put(ConsentConstant.CONSENT_ATTRIBUTES, + consentResource.getConsentAttributes()); + consentResourceJSON.put(ConsentConstant.CREATED_TIME, + consentResource.getCreatedTime()); + return consentResourceJSON; + } + + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/DatabaseInitializer.java b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/DatabaseInitializer.java new file mode 100644 index 000000000..532e7800c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/java/org/wso2/financial/services/accelerator/consent/mgt/endpoint/utils/DatabaseInitializer.java @@ -0,0 +1,59 @@ +package org.wso2.financial.services.accelerator.consent.mgt.endpoint.utils; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import org.wso2.financial.services.accelerator.consent.mgt.dao.util.DatabaseUtils; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.Statement; +import java.util.stream.Collectors; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +/** + * Database initializer for the consent management service. + */ +@SuppressFBWarnings("SQL_INJECTION_JDBC") +public class DatabaseInitializer implements ServletContextListener { + + + private static final String SQL_FILE_PATH = "/WEB-INF/schema.sql"; // Place schema.sql inside WEB-INF + + @SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE") + @Override + public void contextInitialized(ServletContextEvent sce) { + try (Connection conn = DatabaseUtils.getDBConnection(); + Statement stmt = conn.createStatement()) { + + + // Read the SQL file from resources + InputStream inputStream = sce.getServletContext().getResourceAsStream(SQL_FILE_PATH); + if (inputStream == null) { + throw new RuntimeException("SQL file not found: " + SQL_FILE_PATH); + } + + String sql = new BufferedReader(new InputStreamReader(inputStream)) + .lines() + .collect(Collectors.joining("\n")); + + // Execute SQL statements + for (String query : sql.split(";")) { // Split statements by semicolon + if (!query.trim().isEmpty()) { + stmt.execute(query.trim()); + } + } + + + } catch (Exception e) { + throw new RuntimeException("Database initialization failed.", e); + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + // Cleanup logic if needed + } +} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/consent_internal.yaml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/consent_internal.yaml new file mode 100644 index 000000000..9f5293a9a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/consent_internal.yaml @@ -0,0 +1,720 @@ +openapi: 3.0.0 +info: + version: v1.0 + title: ConsentAPI + description: This specifies a RESTful API for making interactions with the consent module + contact: + name: wso2 + url: 'https://wso2.com/solutions/financial-services/' + email: "architecture@wso2.com" + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html +servers: + - url: https://{km_host}:{km_port}/api/fs/consent/ + variables: + km_host: + default: localhost + description: Host of the Key Manager + km_port: + default: "9443" + description: Port of the Key Manager +paths: + /manage: + post: + summary: Post endpoint for manage + operationId: managePost + tags: + - Manage + parameters: + - in: header + name: x-wso2-client-id + required: true + schema: + type: string + requestBody: + description: JSON Consent creation payload + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageCreatePayload" + responses: + "201": + description: Created + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageCreatedResponse" + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + get: + summary: Get endpoint for manage + operationId: manageGet + tags: + - Manage + parameters: + - in: header + name: x-wso2-client-id + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageOKResponse" + "400": + description: Required parameters unavailable or invalid + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + delete: + summary: Delete endpoint for manage + operationId: manageDelete + tags: + - Manage + parameters: + - in: header + name: x-wso2-client-id + required: true + schema: + type: string + responses: + "204": + description: No Content + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + put: + summary: Put endpoint for manage + operationId: managePut + tags: + - Manage + parameters: + - in: header + name: x-wso2-client-id + required: true + schema: + type: string + requestBody: + description: JSON Consent update payload + required: true + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageUpdatePayload" + responses: + "201": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageCreatedResponse" + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + patch: + summary: Patch endpoint for manage + operationId: managePatch + tags: + - Manage + parameters: + - in: header + name: x-wso2-client-id + required: true + schema: + type: string + requestBody: + description: JSON Consent patch payload + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManagePatchPayload" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentManageOKResponse" + "204": + description: No Content + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + /authorize/retrieve/{session-data-key}: + get: + summary: Retrieve data for consent page + operationId: authorizeRetrieve + tags: + - Authorize + parameters: + - name: session-data-key + in: path + description: The session data key of the consent page + required: true + schema: + type: string + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentAuthorizeRetrievalResponse" + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + /authorize/persist/{session-data-key}: + patch: + summary: Persist user consent + operationId: authorizePersist + tags: + - Authorize + parameters: + - name: session-data-key + in: path + description: The session data key of the consent page (used for retrieve) + required: true + schema: + type: string + requestBody: + description: JSON Consent authorize patch payload + required: false + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentAuthorizePatchPayload" + responses: + "302": + description: Post consent redirect + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + /validate: + post: + summary: Validation endpoint used for consent enforcement + operationId: consentValdiate + tags: + - Validate + requestBody: + description: JWT data of request being validated + required: true + content: + application/jwt: + schema: + $ref: "#/components/schemas/ConsentValidateDetail" + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentValidateOKResponse" + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + /admin/search: + get: + summary: Search consent information + operationId: searchConsents + tags: + - Admin + parameters: + - in: query + name: consentIDs + schema: + type: array + items: + type: string + style: form + explode: false + - in: query + name: clientIDs + schema: + type: array + items: + type: string + style: form + explode: false + - in: query + name: consentTypes + schema: + type: array + items: + type: string + style: form + explode: false + - in: query + name: consentStatuses + schema: + type: array + items: + type: string + style: form + explode: false + - in: query + name: userIDs + schema: + type: array + items: + type: string + style: form + explode: false + - in: query + name: fromTime + schema: + type: integer + - in: query + name: toTime + schema: + type: integer + - in: query + name: limit + schema: + type: integer + - in: query + name: offset + schema: + type: integer + responses: + "200": + description: OK + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentSearchOKResponse" + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + /admin/revoke: + delete: + summary: Revoke consents + operationId: revokeConsents + tags: + - Admin + parameters: + - in: query + name: consentID + required: true + schema: + type: string + - in: query + name: userID + required: false + schema: + type: string + responses: + "204": + description: No content. Successful revoke + "400": + description: Required parameters unavailable + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + "500": + description: Internal Server Error + content: + application/json: + schema: + $ref: "#/components/schemas/ConsentErrorCommon" + security: + - basicAuth: [] + +components: + schemas: + ConsentValidateDetail: + type: object + properties: + headers: + description: Object containing keys and values of request headers received to the gateway + type: object + payload: + description: Object containing the request payload received to the gateway + type: object + electedResource: + description: String value of the request path received in the request + type: string + example: "/accounts/1234" + consentId: + description: The consent ID of the consent being valdiated + type: string + example: "cc0961f9-6b38-4c78-a522-b3210a7f2330" + userId: + description: The user ID of the user invoking the API + type: string + example: "admin@carbon.super" + clientId: + description: The client ID of the TPP Application invoking the API + type: string + example: "W4QaMjYv9rn49O7dpeBQD5DLGFQa" + resourceParams: + description: The details of the API context and resource + type: object + properties: + resource: + description: The context including query parameters of the request + type: string + example: "/aisp/accounts/{AccountId}?queryParam=queryParamValue" + httpMethod: + description: The http method of the request + type: string + example: "POST" + context: + description: The base path of the context + type: string + example: "/open-banking/v3.1/aisp" + ConsentManageCreatePayload: + type: object + ConsentManageUpdatePayload: + type: object + ConsentManagePatchPayload: + type: object + ConsentAuthorizePatchPayload: + type: object + properties: + cookies: + type: object + properties: + commonAuthId: + type: string + example: "060711ab-ab8e-44fe-ba3f-9d57fa0c4155" + JSESSIONID: + type: string + example: "A62B65FAA2F16E0172BD9D8825F96E49D1CADD9B55C58CD00C664380F13F8AE95138939A053851856C344A1ADECC0125FF716EE00DD32140BF8574ECECF9A5EDDFAAB641280C5220AC18B1C2F75D62E574C27B8E603A666C4DFF87F0347B460BE3A3B1A370E67559C5936FE2A7700764C9041B5E87118F763731DF9F77B0DDB8" + type: + type: string + example: "accounts" + approval: + type: string + example: "true" + cofAccount: + type: string + example: "12345" + paymentAccount: + type: string + example: "12345" + accountIds: + type: array + items: + type: string + example: "12345" + metadata: + type: object + ConsentErrorCommon: + type: object + properties: + status: + description: Error status code + type: string + title: + description: Error title + type: string + description: + description: Error description + type: string + ConsentValidateOKResponse: + type: object + properties: + isValid: + description: Consent validation result + type: string + example: false + modifiedPayload: + description: Modified payload for in flow + type: string + example: + errorCode: + description: Error code to be sent + type: string + example: Unauthorized + errorMessage: + description: Error message to be sent + type: string + example: "Path requested is invalid" + httpCode: + description: HTTP error code + type: string + example: "401" + consentInformation: + description: Consent information that needs to be passed to the backend + type: string + example: "eyJhbGciOiJSUzI1NiJ9.eyJjbGllbnRJZCI6Ilc0UWFNall2OXJuNDlPN2RwZUJRRDVETEdGUWEiLCJjdXJyZW50U3RhdHVzIjoiUmVqZWN0ZWQiLCJjcmVhdGVkVGltZXN0YW1wIjoxNzE5ODA4NTAzLCJyZWN1cnJpbmdJbmRpY2F0b3IiOmZhbHNlLCJhdXRob3JpemF0aW9uUmVzb3VyY2VzIjpbeyJ1cGRhdGVkVGltZSI6MTcxOTgwODUxNywiY29uc2VudElkIjoiYTc4MTViMmQtMGViMS00MWMwLTg5OWQtYzQwYzk3MThkMTUzIiwiYXV0aG9yaXphdGlvbklkIjoiYmNiZjUwOTgtZTkyZS00ODUxLThmYTktMWUyNjc5YTY1MjI3IiwiYXV0aG9yaXphdGlvblR5cGUiOiJhdXRob3Jpc2F0aW9uIiwidXNlcklkIjoiZTYwY2FkMWItYzhmMS00NjczLWJjMWQtZjIyZTY1ZWRlNTc2IiwiYXV0aG9yaXphdGlvblN0YXR1cyI6IlJlamVjdGVkIn1dLCJ1cGRhdGVkVGltZXN0YW1wIjoxNzE5ODA4NTE3LCJjb25zZW50X3R5cGUiOiJhY2NvdW50cyIsInZhbGlkaXR5UGVyaW9kIjowLCJjb25zZW50QXR0cmlidXRlcyI6e30sImNvbnNlbnRJZCI6ImE3ODE1YjJkLTBlYjEtNDFjMC04OTlkLWM0MGM5NzE4ZDE1MyIsImNvbnNlbnRNYXBwaW5nUmVzb3VyY2VzIjpbeyJtYXBwaW5nSWQiOiIwZmJlN2Q1NS02MDQzLTQ2MTctYmNiOS0xNDg3NWI0Y2M0YzciLCJtYXBwaW5nU3RhdHVzIjoiYWN0aXZlIiwiYWNjb3VudF9pZCI6IjEyMzQ1IiwiYXV0aG9yaXphdGlvbklkIjoiYmNiZjUwOTgtZTkyZS00ODUxLThmYTktMWUyNjc5YTY1MjI3IiwicGVybWlzc2lvbiI6InByaW1hcnkifV0sImFkZGl0aW9uYWxDb25zZW50SW5mbyI6e30sInJlY2VpcHQiOnsiUmlzayI6e30sIkRhdGEiOnsiVHJhbnNhY3Rpb25Ub0RhdGVUaW1lIjoiMjAyNC0wNy0wNFQxMDowNTowMS42OTI5OTArMDU6MzAiLCJFeHBpcmF0aW9uRGF0ZVRpbWUiOiIyMDI0LTA3LTA2VDEwOjA1OjAxLjY4NTMzMCswNTozMCIsIlBlcm1pc3Npb25zIjpbIlJlYWRBY2NvdW50c0RldGFpbCIsIlJlYWRCYWxhbmNlcyIsIlJlYWRUcmFuc2FjdGlvbnNEZXRhaWwiXSwiVHJhbnNhY3Rpb25Gcm9tRGF0ZVRpbWUiOiIyMDI0LTA3LTAxVDEwOjA1OjAxLjY5Mjg0MCswNTozMCJ9fSwiY29uc2VudEZyZXF1ZW5jeSI6MH0.OiJOGfou1n86hzS7PBkRUczDxmmIVswqidxFf9-B8wuIaTLDdAxZnDMFYVs3NCYJvnJXg_ht9m3EEhnX1YgM4BPioBRNcygs1Ns8LMQunB2Y4wOtT71sYvFuDveAPPrwsZy-Z8OV9zrM27aTyLyj-mfHckehGpsDq4pNB9jaOpxaFsBEuxpF9GZxY1Bzy1XmYNxSZ5en2itoStYjKbBwQ3jIlzIvy9DcKkPrnTlukx0ik6RrYyVJ04kctiIbzGaOBQ1x71VvJin9ezriIi8lqHjP2BPxm6zV4GepFY8scxUcut9tRJNQNrQObGDMT0Ib843yf4dDaJ2huJpEEDTNFg" + ConsentSearchOKResponse: + type: object + properties: + data: + description: Detailed consent objects. Search results + type: array + items: + $ref: "#/components/schemas/ConsentDetail" + meatadata: + $ref: "#/components/schemas/ConsentSearchMetadata" + ConsentManageOKResponse: + type: object + ConsentManageCreatedResponse: + type: object + ConsentAuthorizeRetrievalResponse: + type: object + properties: + consentData: + description: Consent data to be shown to the end user + type: array + items: + type: object + properties: + title: + type: string + example: "Permissions" + data: + type: array + items: + type: string + example: "ReadAccountsDetail" + application: + description: Name of the application requesting access + type: string + example: "Test App" + accounts: + description: Accounts retrieved from the bank + type: array + items: + type: object + properties: + account_id: + type: string + example: "12345" + display_name: + type: string + example: "Salary Saver Account" + type: + description: Consent Type + type: string + example: "accounts" + ConsentDetail: + type: object + properties: + clientId: + description: Client ID associated with the consent + type: string + example: "W4QaMjYv9rn49O7dpeBQD5DLGFQa" + currentStatus: + description: Current status of the consent + type: string + example: "AwaitingAuthorisation" + createdTimestamp: + description: Consent created timestamp + type: string + example: "1719810512" + recurringIndicator: + description: Recurring indicator of the consent + type: string + example: "false" + authorizationResources: + description: Authorization resources associated with the consent + type: array + items: + $ref: "#/components/schemas/ConsentAuthorizationResource" + updatedTimestamp: + description: Last updated timestamp + type: string + example: "1719810602" + validityPeriod: + description: Consent validity period + type: string + example: "0" + consentAttributes: + description: Key value pairs of consent attributes + type: object + consentId: + description: Consent ID + type: string + example: "514556fe-57b6-4565-98d1-0b53ff53d62b" + consentMappingResources: + description: Account mapping resources associated with the consent + type: array + items: + $ref: "#/components/schemas/ConsentMappingResource" + consentType: + description: Consent type + type: string + example: "accounts" + receipt: + description: Consent receipt + type: object + consentFrequency: + description: Consent Frequency + type: string + example: "0" + ConsentSearchMetadata: + type: object + properties: + total: + description: Total number of results available despite pagination + type: integer + offset: + description: Pagination offset of result + type: integer + count: + description: Count sent in current response + type: integer + limit: + description: Limit applied for current result + type: integer + ConsentAuthorizationResource: + type: object + properties: + updatedTime: + description: Authorization updated time + type: integer + example: 1719809834569 + consentID: + description: Consent ID of the authorization + type: string + example: "514556fe-57b6-4565-98d1-0b53ff53d62b" + authorizationID: + description: Authorization ID + type: string + example: "96e4033b-6063-4bc8-ba5b-00559c1a9b31" + authorizationType: + description: Type of authorization + type: string + example: "authorisation" + userID: + description: User ID + type: string + example: "admin@carbon.super" + authorizationStatus: + description: Current status of the authorization + type: string + example: "created" + ConsentMappingResource: + type: object + properties: + mappingId: + description: Mapping ID + type: string + example: "ddf5db03-14b2-49f9-a596-0e0cf14e9b03" + mappingStatus: + description: Status of the mapping + type: string + example: "active" + accountId: + description: Accoung ID of the mapping resource + type: string + example: "12345" + authorizationID: + description: Authorization ID associated with the mapping + type: string + example: "96e4033b-6063-4bc8-ba5b-00559c1a9b31" + permission: + description: Mapping permission + type: string + example: "primary" + securitySchemes: + basicAuth: + type: http + scheme: basic diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-exclude.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-exclude.xml new file mode 100644 index 000000000..edb5c7091 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-exclude.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-include.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-include.xml new file mode 100644 index 000000000..aead0b83d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/findbugs-include.xml @@ -0,0 +1,22 @@ + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/openapi.yaml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/openapi.yaml new file mode 100644 index 000000000..d9fc16f4e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/openapi.yaml @@ -0,0 +1,260 @@ +openapi: 3.0.1 +info: + title: Consent Management API + description: Consent Management application API + version: 1.0 +paths: + /consent/authorizationResource/{authorizationId}: + get: + operationId: consentAuthorizationIdGet + parameters: + - name: authorizationId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + responses: + default: + description: default response + content: + application/json: {} + /consent/{consentId}: + get: + operationId: consentConsentIdGet + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + - name: withAuthorizationResources + in: query + schema: + type: boolean + default: true + - name: UserId + in: query + schema: + type: string + - name: WithAttributes + in: query + schema: + type: boolean + responses: + default: + description: default response + content: + application/json: {} + put: + operationId: consentConsentIdPut + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/AmendmentResource" + required: true + responses: + default: + description: default response + content: + application/json: {} + delete: + operationId: consentConsentIdDelete + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + - name: userId + in: query + schema: + type: string + responses: + default: + description: default response + content: + "*/*": {} + /consent/{consentId}/history: + get: + operationId: consentConsentIdHistoryGet + parameters: + - name: consentId + in: path + required: true + schema: + type: string + - name: OrgInfo + in: header + schema: + type: string + default: DEFAULT_ORG + - name: detailed + in: query + schema: + type: boolean + - name: status + in: query + schema: + type: string + - name: actionBy + in: query + schema: + type: string + - name: fromTime + in: query + schema: + type: integer + format: int64 + - name: toTime + in: query + schema: + type: integer + format: int64 + - name: statusAuditId + in: query + schema: + type: string + responses: + default: + description: default response + content: + application/json: {} +components: + schemas: + AmendmentResource: + type: object + properties: + receipt: + type: string + validityPeriod: + type: integer + format: int32 + consentAttributes: + type: object + authorizationResources: + type: array + items: + $ref: "#/components/schemas/ReauthorizeResource" + currentStatus: + type: string + ReauthorizeResource: + type: object + properties: + authId: + type: string + authorizationStatus: + type: string + authorizationType: + type: string + resources: + type: array + items: + $ref: "#/components/schemas/Resource" + userID: + type: string + Resource: + type: object + properties: + resource: + type: string + consentMappingStatus: + type: string + resourceMappingId: + type: string + ConsentStatusUpdateResource: + type: object + properties: + status: + type: string + reason: + type: string + userID: + type: string + AuthorizationResourceDTO: + required: + - authorizationStatus + - authorizationType + - userID + type: object + properties: + authorizationStatus: + type: string + authorizationType: + type: string + userID: + type: string + resources: + type: array + items: + type: string + ConsentResourceDTO: + required: + - clientID + - consentType + - currentStatus + - receipt + - recurringIndicator + - validityPeriod + type: object + properties: + clientID: + type: string + consentType: + type: string + currentStatus: + type: string + receipt: + type: string + validityPeriod: + type: integer + format: int32 + recurringIndicator: + type: boolean + consentAttributes: + type: object + authorizationResources: + type: array + items: + $ref: "#/components/schemas/AuthorizationResourceDTO" + BulkConsentStatusUpdateResource: + type: object + properties: + clientID: + type: string + consentType: + type: string + applicableStatusesForStateChange: + type: array + items: + type: string + status: + type: string + reason: + type: string + userID: + type: string diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/README.mustache new file mode 100644 index 000000000..4718b9d4b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/README.mustache @@ -0,0 +1,33 @@ +# JAX-RS server with OpenAPI + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +The JAX-RS implementation needs to be provided by the application server you are deploying on. + +To run the server from the command line, you can use maven to provision and start a TomEE Server. +Please execute the following: + +``` +mvn -Dtomee-embedded-plugin.http={{serverPort}} package org.apache.tomee.maven:tomee-embedded-maven-plugin:7.0.5:run +``` + +You can then call your server endpoints under: + +``` +http://localhost:{{serverPort}}{{contextPath}}/ +``` + +Note that if you have configured the `host` to be something other than localhost, the calls through +swagger-ui will be directed to that host and not localhost! +{{/interfaceOnly}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestApplication.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestApplication.mustache new file mode 100644 index 000000000..4f7ce12fd --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestApplication.mustache @@ -0,0 +1,17 @@ +package {{invokerPackage}}; + +import {{javaxPackage}}.ws.rs.ApplicationPath; +import {{javaxPackage}}.ws.rs.core.Application; +{{#useMicroProfileOpenAPIAnnotations}}{{#openAPI}}{{#info}} +@org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition( + info = @org.eclipse.microprofile.openapi.annotations.info.Info( + version="{{{appVersion}}}" + {{#appName}},title = "{{{.}}}"{{/appName}} + {{#appDescription}},description = "{{{.}}}"{{/appDescription}} + {{#license}},license = @org.eclipse.microprofile.openapi.annotations.info.License(name = "{{{licenseInfo}}}", url = "{{{licenseUrl}}}"){{/license}} + {{#contact}},contact = @org.eclipse.microprofile.openapi.annotations.info.Contact(name = "{{{infoName}}}", email = "{{{infoEmail}}}", url = "{{{infoUrl}}}"){{/contact}} +)){{/info}}{{/openAPI}}{{/useMicroProfileOpenAPIAnnotations}} +@ApplicationPath(RestResourceRoot.APPLICATION_PATH) +public class RestApplication extends Application { + +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestResourceRoot.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestResourceRoot.mustache new file mode 100644 index 000000000..669fc2b4f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/RestResourceRoot.mustache @@ -0,0 +1,5 @@ +package {{invokerPackage}}; + +public class RestResourceRoot { + public static final String APPLICATION_PATH = "{{{contextPath}}}"; +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalEnumTypeAnnotations.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalEnumTypeAnnotations.mustache new file mode 100644 index 000000000..aa524798b --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalEnumTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalEnumTypeAnnotations}}{{{.}}} +{{/additionalEnumTypeAnnotations}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalModelTypeAnnotations.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalModelTypeAnnotations.mustache new file mode 100644 index 000000000..f4871c02c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/additionalModelTypeAnnotations.mustache @@ -0,0 +1,2 @@ +{{#additionalModelTypeAnnotations}}{{{.}}} +{{/additionalModelTypeAnnotations}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/api.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/api.mustache new file mode 100644 index 000000000..09b446ebd --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/api.mustache @@ -0,0 +1,52 @@ +package {{package}}; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +{{#useSwaggerAnnotations}} + import io.swagger.annotations.Api; + import io.swagger.annotations.ApiOperation; + import io.swagger.annotations.ApiParam; + import io.swagger.annotations.ApiResponse; + import io.swagger.annotations.ApiResponses; +{{/useSwaggerAnnotations}} +import org.wso2.financial.services.accelerator.consent.mgt.endpoint.impl.ConsentMgtApiHandler; +{{#imports}}import {{import}}; +{{/imports}} + + +{{#useBeanValidation}}import {{javaxPackage}}.validation.constraints.NotNull; +import {{javaxPackage}}.validation.Valid; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +{{/useBeanValidation}} + +/** +* Represents a collection of functions to interact with the API endpoints. +*/ +@SuppressFBWarnings("JAXRS_ENDPOINT") +// Suppressed content - Endpoints +// Suppression reason - False Positive : These endpoints are secured with access +// control +@Path("{{commonPath}}"){{#useSwaggerAnnotations}} + @Api(description = "the {{{baseName}}} API"){{/useSwaggerAnnotations}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} +public {{#interfaceOnly}}interface{{/interfaceOnly}}{{^interfaceOnly}}class{{/interfaceOnly}} {{classname}} { +ConsentMgtApiHandler consentMgtApiHandler = new ConsentMgtApiHandler(); + +{{#operations}} + {{#operation}} + + {{#interfaceOnly}}{{>apiInterface}}{{/interfaceOnly}}{{^interfaceOnly}}{{>apiMethod}}{{/interfaceOnly}} + {{/operation}} + } +{{/operations}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiInterface.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiInterface.mustache new file mode 100644 index 000000000..9ee04de30 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiInterface.mustache @@ -0,0 +1,31 @@ + /** + * {{{notes}}} + * + {{#allParams}} + * @param {{paramName}} {{description}} + {{/allParams}} + {{#responses}} + * @return {{{message}}} + {{/responses}} + */ + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}{{#useSwaggerAnnotations}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}"{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}{{#isOAuth}}@Authorization(value = "{{name}}", scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, + {{/-last}}{{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}} + {{^isOAuth}}@Authorization(value = "{{name}}"){{^-last}},{{/-last}} + {{/isOAuth}}{{/authMethods}} }{{/hasAuthMethods}}, tags = { {{#vendorExtensions.x-tags}}"{{tag}}"{{^-last}}, + {{/-last}}{{/vendorExtensions.x-tags}} }) + {{#implicitHeadersParams.0}} + @io.swagger.annotations.ApiImplicitParams({ + {{#implicitHeadersParams}} + @io.swagger.annotations.ApiImplicitParam(name = "{{{baseName}}}", value = "{{{description}}}", {{#required}}required = true,{{/required}} dataType = "{{{dataType}}}", paramType = "header"){{^-last}},{{/-last}} + {{/implicitHeadersParams}} + }) + {{/implicitHeadersParams.0}} + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{baseType}}}.class{{#returnContainer}}, responseContainer = "{{{.}}}"{{/returnContainer}}){{^-last}},{{/-last}}{{/responses}} }){{/useSwaggerAnnotations}} + {{#supportAsync}}{{>returnAsyncTypeInterface}}{{/supportAsync}}{{^supportAsync}}{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{>returnTypeInterface}}{{/returnResponse}}{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>cookieParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}); diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiMethod.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiMethod.mustache new file mode 100644 index 000000000..87846ead6 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/apiMethod.mustache @@ -0,0 +1,31 @@ + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}{{#useSwaggerAnnotations}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnBaseType}}}.class{{#returnContainer}}, responseContainer = "{{{.}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}{{#isOAuth}}@Authorization(value = "{{name}}", scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, + {{/-last}}{{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}} + {{^isOAuth}}@Authorization(value = "{{name}}"){{^-last}},{{/-last}} + {{/isOAuth}}{{/authMethods}} }{{/hasAuthMethods}}, tags = { {{#vendorExtensions.x-tags}}"{{tag}}"{{^-last}}, + {{/-last}}{{/vendorExtensions.x-tags}} }) + {{#implicitHeadersParams.0}} + @io.swagger.annotations.ApiImplicitParams({ + {{#implicitHeadersParams}} + @io.swagger.annotations.ApiImplicitParam(name = "{{{baseName}}}", value = "{{{description}}}", {{#required}}required = true,{{/required}} dataType = "{{{dataType}}}", paramType = "header"){{^-last}},{{/-last}} + {{/implicitHeadersParams}} + }) + {{/implicitHeadersParams.0}} + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{baseType}}}.class{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}},{{/-last}}{{/responses}} + }){{/useSwaggerAnnotations}} + public {{#supportAsync}}CompletionStage<{{/supportAsync}}Response{{#supportAsync}}>{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>cookieParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}) { + try { + return Response.ok().entity(consentMgtApiHandler.{{nickname}}({{#allParams}}{{>param}}{{^-last}},{{/-last}}{{/allParams}})).build(); + } catch (Exception e) { + // Handle other errors + return Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity("An unexpected error occurred: " + e.getMessage()) + .build(); + } + } \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidatedType.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidatedType.mustache new file mode 100644 index 000000000..8f2816b2c --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidatedType.mustache @@ -0,0 +1 @@ +{{#isArray}}{{baseType}}<{{#items}}{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}}{{>beanValidatedType}}{{/items}}>{{/isArray}}{{^isArray}}{{{datatypeWithEnum}}}{{/isArray}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidation.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidation.mustache new file mode 100644 index 000000000..a7f264654 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidation.mustache @@ -0,0 +1 @@ +{{#required}}{{^isReadOnly}}@NotNull {{/isReadOnly}}{{/required}}{{#isContainer}}{{^items.isPrimitiveType}}{{^items.isDate}}{{^items.isDateTime}}{{^items.isString}}{{^items.isFile}}{{^items.isEnumOrRef}}@Valid {{/items.isEnumOrRef}}{{/items.isFile}}{{/items.isString}}{{/items.isDateTime}}{{/items.isDate}}{{/items.isPrimitiveType}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}{{^isDate}}{{^isDateTime}}{{^isString}}{{^isFile}}{{^isEnumOrRef}}@Valid {{/isEnumOrRef}}{{/isFile}}{{/isString}}{{/isDateTime}}{{/isDate}}{{/isPrimitiveType}}{{/isContainer}}{{>beanValidationCore}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationCore.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationCore.mustache new file mode 100644 index 000000000..d6e2f13b4 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationCore.mustache @@ -0,0 +1,20 @@ +{{#pattern}} @Pattern(regexp="{{{.}}}"){{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}} @Size(max={{.}}){{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}} @Size(max={{.}}){{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}} @Min({{.}}){{/minimum}}{{#maximum}} @Max({{.}}){{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}} @Min({{.}}L){{/minimum}}{{#maximum}} @Max({{.}}L){{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin({{#exclusiveMinimum}}value={{/exclusiveMinimum}}"{{minimum}}"{{#exclusiveMinimum}},inclusive=false{{/exclusiveMinimum}}){{/minimum}}{{#maximum}} @DecimalMax({{#exclusiveMaximum}}value={{/exclusiveMaximum}}"{{maximum}}"{{#exclusiveMaximum}},inclusive=false{{/exclusiveMaximum}}){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationHeaderParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationHeaderParams.mustache new file mode 100644 index 000000000..c4ff01d7e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationHeaderParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationPathParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationPathParams.mustache new file mode 100644 index 000000000..051bd53c0 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationQueryParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationQueryParams.mustache new file mode 100644 index 000000000..c4ff01d7e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/bodyParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/bodyParams.mustache new file mode 100644 index 000000000..f938cb5b6 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{#useBeanValidation}}@Valid {{#required}}{{^isNullable}}@NotNull {{/isNullable}}{{/required}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/cookieParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/cookieParams.mustache new file mode 100644 index 000000000..0a58596df --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/cookieParams.mustache @@ -0,0 +1 @@ +{{#isCookieParam}}@CookieParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{^isContainer}}{{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}}{{/isContainer}} {{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}}{{#description}} @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="{{.}}"){{/description}}{{/useMicroProfileOpenAPIAnnotations}} {{{dataType}}} {{paramName}}{{/isCookieParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumClass.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumClass.mustache new file mode 100644 index 000000000..be8cd5eed --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumClass.mustache @@ -0,0 +1,48 @@ +{{>additionalEnumTypeAnnotations}}public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + +{{#isObject}}private Map value;{{^isObject}}private {{{dataType}}} value;{{/isObject}} + + {{datatypeWithEnum}} ({{dataType}} v) { + value = v; + } + + public {{dataType}} value() { + return value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + /** + * Convert a String into {{dataType}}, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static {{datatypeWithEnum}} fromString(String s) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} + } + + @JsonCreator + public static {{datatypeWithEnum}} fromValue({{dataType}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.{{^isString}}equals{{/isString}}{{#isString}}{{#useEnumCaseInsensitive}}equalsIgnoreCase{{/useEnumCaseInsensitive}}{{^useEnumCaseInsensitive}}equals{{/useEnumCaseInsensitive}}{{/isString}}(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumOuterClass.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumOuterClass.mustache new file mode 100644 index 000000000..a139b6593 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/enumOuterClass.mustache @@ -0,0 +1,62 @@ +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + +{{#isObject}}private Map value;{{^isObject}}private {{{dataType}}} value;{{/isObject}} + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + /** + * Convert a String into {{dataType}}, as specified in the + * See JAX RS 2.0 Specification, section 3.2, p. 12 + */ + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + // using Objects.toString() to be safe if value type non-object type + // because types like 'int' etc. will be auto-boxed + if (java.util.Objects.toString(b.value).equals(s)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.{{^isString}}equals{{/isString}}{{#isString}}{{#useEnumCaseInsensitive}}equalsIgnoreCase{{/useEnumCaseInsensitive}}{{^useEnumCaseInsensitive}}equals{{/useEnumCaseInsensitive}}{{/isString}}(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/formParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/formParams.mustache new file mode 100644 index 000000000..885966e64 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/formParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{^isFile}}@FormParam(value = "{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}} @FormParam(value = "{{baseName}}") InputStream {{paramName}}InputStream{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/generatedAnnotation.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/generatedAnnotation.mustache new file mode 100644 index 000000000..e05689d5f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/generatedAnnotation.mustache @@ -0,0 +1 @@ +@{{javaxPackage}}.annotation.Generated(value = "{{generatorClass}}"{{^hideGenerationTimestamp}}, date = "{{generatedDate}}"{{/hideGenerationTimestamp}}, comments = "Generator version: {{generatorVersion}}") \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/headerParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/headerParams.mustache new file mode 100644 index 000000000..94f690704 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@HeaderParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationHeaderParams}}{{/useBeanValidation}} {{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}} {{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}}{{#description}} @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="{{.}}"){{/description}}{{/useMicroProfileOpenAPIAnnotations}} {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/README.mustache new file mode 100644 index 000000000..2661c14e4 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/README.mustache @@ -0,0 +1,43 @@ +# JAX-RS server with OpenAPI using Helidon + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework and +the [Eclipse-MicroProfile-OpenAPI](https://github.com/eclipse/microprofile-open-api) addition. + +The pom file is configured to use [Helidon](https://helidon.io/) as application server. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +To build the server, run this maven command (with JDK 11+): + +```bash +mvn package +``` + +To run the server, run this maven command: + +```bash +java -jar target/{{artifactId}}.jar +``` + +You can then call your server endpoints under: + +``` +http://localhost:8080/ +``` + +You can access the OpenAPI specification at: + +``` +http://localhost:8080/openapi +``` + +{{/interfaceOnly}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/beans.xml.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/beans.xml.mustache new file mode 100644 index 000000000..125ef995e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/beans.xml.mustache @@ -0,0 +1,9 @@ + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/logging.properties.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/logging.properties.mustache new file mode 100644 index 000000000..3e909fb7d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/logging.properties.mustache @@ -0,0 +1,25 @@ +# Example Logging Configuration File +# For more information see $JAVA_HOME/jre/lib/logging.properties + +## Send messages to the console +handlers=io.helidon.common.HelidonConsoleHandler +# +## HelidonConsoleHandler uses a SimpleFormatter subclass that replaces "!thread!" with the current thread +java.util.logging.SimpleFormatter.format=%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS %4$s %3$s !thread!: %5$s%6$s%n +# +## Global logging level. Can be overridden by specific loggers +.level=INFO + +# Quiet Weld +org.jboss.level=WARNING + +# +# Component specific log levels +#io.helidon.webserver.level=INFO +#io.helidon.config.level=INFO +#io.helidon.security.level=INFO +#io.helidon.microprofile.level=INFO +#io.helidon.common.level=INFO +#io.netty.level=INFO +#org.glassfish.jersey.level=INFO +#org.jboss.weld=INFO diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/microprofile-config.properties.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/microprofile-config.properties.mustache new file mode 100644 index 000000000..38988f20e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/microprofile-config.properties.mustache @@ -0,0 +1,11 @@ +# Microprofile server properties + +# Application properties. This is the default greeting +app.greeting=Hello + +# Microprofile server properties +server.port=8080 +server.host=0.0.0.0 + +# Enable the optional MicroProfile Metrics REST.request metrics +metrics.rest-request.enabled=true diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/pom.mustache new file mode 100644 index 000000000..91c575960 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/helidon/pom.mustache @@ -0,0 +1,238 @@ + + + + 4.0.0 + + {{groupId}} + {{artifactId}} + {{artifactVersion}} + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} + + + + {{helidonVersion}} + io.helidon.microprofile.cdi.Main + + 11 + ${maven.compiler.source} + true + UTF-8 + UTF-8 + + + 3.8.1 + 3.0.0 + 2.7.5.1 + 1.6.0 + 3.0.0-M5 + 2.3.0 + 2.3.0 + 1.0.6 + 3.0.2 + 1.5.0.Final + 0.5.1 + 2.7 + 3.0.0-M5 + + + + + + io.helidon + helidon-dependencies + ${helidon.version} + pom + import + + + + + + + io.helidon.microprofile.bundles + helidon-microprofile + + + org.jboss + jandex + runtime + true + + + org.junit.jupiter + junit-jupiter-api + test + + + + + ${project.artifactId} + + + + org.apache.maven.plugins + maven-compiler-plugin + ${version.plugin.compiler} + + + org.apache.maven.plugins + maven-surefire-plugin + ${version.plugin.surefire} + + false + + ${project.build.outputDirectory}/logging.properties + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${version.plugin.failsafe} + + false + true + + + + org.apache.maven.plugins + maven-dependency-plugin + ${version.plugin.dependency} + + + org.apache.maven.plugins + maven-resources-plugin + ${version.plugin.resources} + + + org.apache.maven.plugins + maven-jar-plugin + ${version.plugin.jar} + + + + true + libs + ${mainClass} + false + + + + + + org.jboss.jandex + jandex-maven-plugin + ${version.plugin.jandex} + + + org.codehaus.mojo + exec-maven-plugin + ${version.plugin.exec} + + ${mainClass} + + + + io.helidon.build-tools + helidon-maven-plugin + ${version.plugin.helidon} + + + io.helidon.build-tools + helidon-cli-maven-plugin + ${version.plugin.helidon-cli} + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-libs + prepare-package + + copy-dependencies + + + ${project.build.directory}/libs + false + false + true + true + runtime + test + + + + + + org.jboss.jandex + jandex-maven-plugin + + + make-index + + jandex + + process-classes + + + + + + + + + native-image + + + + io.helidon.build-tools + helidon-maven-plugin + + + native-image + + native-image + + + + + + + + + io.helidon.integrations.graal + helidon-mp-graal-native-image-extension + + + + + jlink-image + + + + io.helidon.build-tools + helidon-maven-plugin + + + + jlink-image + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/README.mustache new file mode 100644 index 000000000..d2ad96e1f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/README.mustache @@ -0,0 +1,42 @@ +# JAX-RS server with OpenAPI using KumuluzEE + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework and +the [Eclipse-MicroProfile-OpenAPI](https://github.com/eclipse/microprofile-open-api) addition. + +The pom file is configured to use [KumuluzEE](https://ee.kumuluz.com/) as application server. + +{{#interfaceOnly}} + This project produces a jar that defines some interfaces. + The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +To build the server, run this maven command: + +```bash +mvn clean package +``` + +To run the server, run this maven command: + +```bash +java -jar target/${project.build.finalName}.jar +``` + +You can then call your server endpoints under: + +``` +http://localhost:8080 +``` + +Example endpoint: + +``` +http://localhost:8080/v2/user/example +``` +{{/interfaceOnly}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/config.yaml.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/config.yaml.mustache new file mode 100644 index 000000000..44562fef8 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/config.yaml.mustache @@ -0,0 +1,5 @@ +kumuluzee: + name: {{artifactId}} + version: {{artifactVersion}} + env: + name: dev \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/pom.mustache new file mode 100644 index 000000000..2e83ada78 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/kumuluzee/pom.mustache @@ -0,0 +1,75 @@ + + + 4.0.0 + + {{groupId}} + {{artifactId}} + {{artifactVersion}} + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} + + Automatically generated KumuluzEE microservice + The microservice was generated automatically with the OpenAPI Generator project + + + 1.8 + 1.8 + UTF-8 + + 3.9.0 + + + + + + com.kumuluz.ee + kumuluzee-bom + ${kumuluzee.version} + pom + import + + + + + + + com.kumuluz.ee + kumuluzee-core + + + com.kumuluz.ee + kumuluzee-servlet-jetty + + + com.kumuluz.ee + kumuluzee-jax-rs-jersey + + + + + + + com.kumuluz.ee + kumuluzee-maven-plugin + ${kumuluzee.version} + + + package + + repackage + + + + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/MANIFEST.MF.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/MANIFEST.MF.mustache new file mode 100644 index 000000000..65b9fe16a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/MANIFEST.MF.mustache @@ -0,0 +1,2 @@ +Manifest-Version: 1.0 +Class-Path: diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/README.mustache new file mode 100644 index 000000000..1db634c6f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/README.mustache @@ -0,0 +1,43 @@ +# JAX-RS server with OpenAPI using Open Liberty + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework and +the [Eclipse-MicroProfile-OpenAPI](https://github.com/eclipse/microprofile-open-api) addition. + +The pom file is configured to use [Open Liberty](https://openliberty.io/) as application server. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +To start the server with maven, run this command: + +```bash +mvn install liberty:start-server +``` + +The OpenAPI specification is available at: + +``` +http://localhost:9080/openapi +``` + +A UI for this OpenAPI Specification is available at: + +``` +http://localhost:9080/openapi/ui +``` + +When you are done stop Open Liberty with: + +``` +mvn liberty:stop-server +``` + +{{/interfaceOnly}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/beans.xml.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/beans.xml.mustache new file mode 100644 index 000000000..17d17df35 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/beans.xml.mustache @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/ibm-web-ext.xml.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/ibm-web-ext.xml.mustache new file mode 100644 index 000000000..62e9c10b5 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/ibm-web-ext.xml.mustache @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/microprofile-config.properties.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/microprofile-config.properties.mustache new file mode 100644 index 000000000..c3fe39023 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/microprofile-config.properties.mustache @@ -0,0 +1 @@ +mp.openapi.scan.disable=true \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/pom.mustache new file mode 100644 index 000000000..c41fed1c5 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/pom.mustache @@ -0,0 +1,127 @@ + + 4.0.0 + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} +{{^parentOverridden}} + + net.wasdev.wlp.maven.parent + liberty-maven-app-parent + 2.6 + +{{/parentOverridden}} + + {{groupId}} + {{artifactId}} + {{artifactVersion}} + war + + + + javax + javaee-api + 8.0 + provided + + + org.eclipse.microprofile + microprofile + 2.0.1 + pom + provided + + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + + + com.fasterxml.jackson.core + jackson-annotations + 2.0.1 + + + + + UTF-8 + 1.8 + 1.8 + false + 3.2.2 + + 19.0.0.7 + 9080 + 9443 + usr + ${project.artifactId} + ${project.build.directory}/${app.name}.zip + 2.0.2 + + + + {{artifactId}} + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + org.apache.maven.plugins + maven-war-plugin + ${version.maven-war-plugin} + + false + pom.xml + + + + + + net.wasdev.wlp.maven.plugins + liberty-maven-plugin + + + io.openliberty + openliberty-runtime + ${version.openliberty-runtime} + zip + + OpenAPIGeneratorServer + true + src/main/liberty/config/server.xml + true + ${package.file} + ${packaging.type} + + ${http.port} + ${https.port} + ${app.name} + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/server.xml.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/server.xml.mustache new file mode 100644 index 000000000..d765cfbdc --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/openliberty/server.xml.mustache @@ -0,0 +1,19 @@ + + + cdi-2.0 + jaxrs-2.1 + mpOpenAPI-1.1 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.jvm.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.jvm.mustache new file mode 100644 index 000000000..5c0779580 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.jvm.mustache @@ -0,0 +1,34 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the docker image run: +# +# mvn package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/{{artifactId}}-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/{{artifactId}}-jvm +# +### +FROM fabric8/java-alpine-openjdk8-jre:1.6.5 +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV AB_ENABLED=jmx_exporter + +# Be prepared for running in OpenShift too +RUN adduser -G root --no-create-home --disabled-password 1001 \ + && chown -R 1001 /deployments \ + && chmod -R "g+rwX" /deployments \ + && chown -R 1001:root /deployments + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/app.jar +EXPOSE 8080 + +# run with user 1001 +USER 1001 + +ENTRYPOINT [ "/deployments/run-java.sh" ] \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.native.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.native.mustache new file mode 100644 index 000000000..b1821fac4 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/Dockerfile.native.mustache @@ -0,0 +1,22 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode +# +# Before building the docker image run: +# +# mvn package -Pnative -Dquarkus.native.container-build=true +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/{{artifactId}} . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/{{artifactId}} +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal +WORKDIR /work/ +COPY target/*-runner /work/application +RUN chmod 775 /work +EXPOSE 8080 +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/README.mustache new file mode 100644 index 000000000..dfcb3d94a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/README.mustache @@ -0,0 +1,39 @@ +# JAX-RS server with OpenAPI using Quarkus + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework and +the [Eclipse-MicroProfile-OpenAPI](https://github.com/eclipse/microprofile-open-api) addition. + +The pom file is configured to use [Quarkus](https://quarkus.io/) as application server. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +To start the server in dev mode, run this maven command: + +```bash +mvn compile quarkus:dev +``` + +You can then call your server endpoints under: + +``` +http://localhost:8080/ +``` + +In dev-mode, you can open Swagger-UI at: + +``` +http://localhost:8080/swagger-ui/ +``` + +Read more in the [Quarkus OpenAPI guide](https://quarkus.io/guides/openapi-swaggerui-guide). + +{{/interfaceOnly}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/api.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/api.mustache new file mode 100644 index 000000000..8f40dc3a9 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/api.mustache @@ -0,0 +1,110 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import {{javaxPackage}}.ws.rs.*; +import {{javaxPackage}}.ws.rs.core.Response; + +{{#useGzipFeature}} +import org.jboss.resteasy.annotations.GZIP; +{{/useGzipFeature}} + +{{#useSwaggerAnnotations}} +import io.swagger.annotations.*; +{{/useSwaggerAnnotations}} + +{{#supportAsync}} +{{#useMutiny}} +import io.smallrye.mutiny.Uni; +{{/useMutiny}} +{{^useMutiny}} +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CompletableFuture; +{{/useMutiny}} +{{/supportAsync}} + +import java.io.InputStream; +import java.util.Map; +import java.util.List; +{{#useBeanValidation}}import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid;{{/useBeanValidation}} + +{{#useMicroProfileOpenAPIAnnotations}}@org.eclipse.microprofile.openapi.annotations.OpenAPIDefinition( + info = @org.eclipse.microprofile.openapi.annotations.info.Info( + title = "{{{operationTagName}}}", version="{{{version}}}", description="{{{operationTagDescription}}}"{{#license}}, + license = @org.eclipse.microprofile.openapi.annotations.info.License(name = "{{{licenseInfo}}}", url = "{{{licenseUrl}}}"){{/license}}{{#contact}}, + contact = @org.eclipse.microprofile.openapi.annotations.info.Contact(name = "{{{infoName}}}", email = "{{{infoEmail}}}"){{/contact}} + ), + tags = @org.eclipse.microprofile.openapi.annotations.tags.Tag(name="{{{operationTagName}}}", description="{{{operationTagDescription}}}") +){{#hasAuthMethods}} +@org.eclipse.microprofile.openapi.annotations.tags.Tag(name="{{{operationTagName}}}", description="{{{operationTagDescription}}}") +@org.eclipse.microprofile.openapi.annotations.security.SecuritySchemes(value = { + {{#authMethods}}{{#isOAuth}}@org.eclipse.microprofile.openapi.annotations.security.SecurityScheme( + securitySchemeName = "{{name}}", + type = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType.OAUTH2, + description = "{{description}}",{{#isImplicit}} + flows = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlows( + implicit = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlow(authorizationUrl = "{{authorizationUrl}}", + tokenUrl = "{{tokenUrl}}", + refreshUrl = "{{refreshUrl}}", + scopes = { + {{#scopes}}@org.eclipse.microprofile.openapi.annotations.security.OAuthScope(name = "{{scope}}", description = "{{description}}"){{^-last}},{{/-last}} + {{/scopes}} })) {{/isImplicit}}{{#isCode}} + flows = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlows( + authorizationCode = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlow(authorizationUrl = "{{authorizationUrl}}", + tokenUrl = "{{tokenUrl}}", + refreshUrl = "{{refreshUrl}}", + scopes = { + {{#scopes}}@org.eclipse.microprofile.openapi.annotations.security.OAuthScope(name = "{{scope}}", description = "{{description}}"){{^-last}},{{/-last}} + {{/scopes}} })) {{/isCode}}{{#isPassword}} + flows = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlows( + password = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlow(authorizationUrl = "{{authorizationUrl}}", + tokenUrl = "{{tokenUrl}}", + refreshUrl = "{{refreshUrl}}", + scopes = { + {{#scopes}}@org.eclipse.microprofile.openapi.annotations.security.OAuthScope(name = "{{scope}}", description = "{{description}}"){{^-last}},{{/-last}} + {{/scopes}} })) {{/isPassword}}{{#isApplication}} + flows = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlows( + clientCredentials = @org.eclipse.microprofile.openapi.annotations.security.OAuthFlow(authorizationUrl = "{{authorizationUrl}}", + tokenUrl = "{{tokenUrl}}", + refreshUrl = "{{refreshUrl}}", + scopes = { + {{#scopes}}@org.eclipse.microprofile.openapi.annotations.security.OAuthScope(name = "{{scope}}", description = "{{description}}"){{^-last}},{{/-last}} + {{/scopes}} })){{/isApplication}} + ){{^-last}}, {{/-last}}{{/isOAuth}}{{#isApiKey}}@org.eclipse.microprofile.openapi.annotations.security.SecurityScheme( + securitySchemeName = "{{name}}", + type = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType.APIKEY, + description = "{{description}}", + apiKeyName = "{{keyParamName}}", + {{#isKeyInHeader}}in = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeIn.HEADER{{/isKeyInHeader}}{{#isKeyInQuery}}in = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeIn.QUERY{{/isKeyInQuery}}{{#isKeyInCookie}}in = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeIn.COOKIE{{/isKeyInCookie}} + ){{^-last}}, {{/-last}}{{/isApiKey}}{{#isBasicBasic}}@org.eclipse.microprofile.openapi.annotations.security.SecurityScheme( + securitySchemeName = "{{name}}", + type = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType.HTTP, + description = "{{description}}", + scheme = "basic" + ){{^-last}}, {{/-last}}{{/isBasicBasic}}{{#isBasicBearer}}@org.eclipse.microprofile.openapi.annotations.security.SecurityScheme( + securitySchemeName = "{{name}}", + type = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType.HTTP, + description = "{{description}}", + scheme = "bearer", bearerFormat = "{{bearerFormat}}" + ){{^-last}}, {{/-last}}{{/isBasicBearer}}{{#isOpenId}}@org.eclipse.microprofile.openapi.annotations.security.SecurityScheme( + securitySchemeName = "{{name}}", + type = org.eclipse.microprofile.openapi.annotations.enums.SecuritySchemeType.OPENIDCONNECT, + description = "{{description}}", + openIdConnectUrl = "{{openIdConnectUrl}}" + ){{^-last}}, {{/-last}}{{/isOpenId}}{{/authMethods}} +}){{/hasAuthMethods}}{{/useMicroProfileOpenAPIAnnotations}}{{#useSwaggerAnnotations}} +@Api(description = "the {{{baseName}}} API"){{/useSwaggerAnnotations}} +@Path("{{commonPath}}"){{#hasConsumes}} +@Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} +@Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}} +{{>generatedAnnotation}} +public {{#interfaceOnly}}interface{{/interfaceOnly}}{{^interfaceOnly}}class{{/interfaceOnly}} {{classname}} { +{{#operations}} +{{#operation}} + +{{#interfaceOnly}}{{>apiInterface}}{{/interfaceOnly}}{{^interfaceOnly}}{{>apiMethod}}{{/interfaceOnly}} +{{/operation}} +} +{{/operations}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiInterface.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiInterface.mustache new file mode 100644 index 000000000..02e2faa0d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiInterface.mustache @@ -0,0 +1,44 @@ + {{#useGzipFeature}} + @GZIP + {{/useGzipFeature}} + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}{{#useSwaggerAnnotations}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}"{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}{{#isOAuth}}@Authorization(value = "{{name}}", scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, + {{/-last}}{{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}} + {{^isOAuth}}@Authorization(value = "{{name}}"){{^-last}},{{/-last}} + {{/isOAuth}}{{/authMethods}} }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{^-last}}, {{/-last}}{{/vendorExtensions.x-tags}} }) + {{#implicitHeadersParams.0}} + @io.swagger.annotations.ApiImplicitParams({ + {{#implicitHeadersParams}} + @io.swagger.annotations.ApiImplicitParam(name = "{{{baseName}}}", value = "{{{description}}}", {{#required}}required = true,{{/required}} dataType = "{{{dataType}}}", paramType = "header"){{^-last}},{{/-last}} + {{/implicitHeadersParams}} + }) + {{/implicitHeadersParams.0}} + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{baseType}}}.class{{#returnContainer}}, responseContainer = "{{{.}}}"{{/returnContainer}}){{^-last}},{{/-last}}{{/responses}} }){{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}} + {{#hasAuthMethods}}@org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value = { + {{#authMethods}}{{#isOAuth}}@org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement( + name = "{{name}}", + scopes = { {{#scopes}} "{{scope}}"{{^-last}},{{/-last}} {{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}}{{^isOAuth}} @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "{{name}}"){{^-last}},{{/-last}}{{/isOAuth}} + {{/authMethods}} }){{/hasAuthMethods}} + @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "{{{operationId}}}", summary = "{{{summary}}}", description = "{{{notes}}}") + {{#vendorExtensions.x-tags}}@org.eclipse.microprofile.openapi.annotations.tags.Tag(name="{{tag}}"){{^-last}}, {{/-last}}{{/vendorExtensions.x-tags}}{{#hasProduces}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponses(value = { {{#responses}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponse(responseCode = "{{{code}}}", description = "{{{message}}}", {{#responseHeaders.0}}headers = { {{#responseHeaders}} + @org.eclipse.microprofile.openapi.annotations.headers.Header(name = "{{{baseName}}}", schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(type = {{{vendorExtensions.x-microprofile-open-api-schema-type}}}), description = "{{{description}}}"){{^-last}},{{/-last}}{{/responseHeaders}} + },{{/responseHeaders.0}} content = { {{#produces}} + @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType = "{{{mediaType}}}"{{^vendorExtensions.x-java-is-response-void}}, schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(implementation = {{{baseType}}}.class{{#vendorExtensions.x-microprofile-open-api-return-schema-container}}, type = {{{.}}} {{/vendorExtensions.x-microprofile-open-api-return-schema-container}}{{#vendorExtensions.x-microprofile-open-api-return-unique-items}}, uniqueItems = true {{/vendorExtensions.x-microprofile-open-api-return-unique-items}}){{/vendorExtensions.x-java-is-response-void}}){{^-last}},{{/-last}}{{/produces}} + }){{^-last}},{{/-last}}{{/responses}} + }){{/hasProduces}}{{^hasProduces}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponses(value = { {{#responses}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponse(responseCode = "{{{code}}}", description = "{{{message}}}", {{#responseHeaders.0}}headers = { {{#responseHeaders}} + @org.eclipse.microprofile.openapi.annotations.headers.Header(name = "{{{baseName}}}", schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(type = {{{vendorExtensions.x-microprofile-open-api-schema-type}}}), description = "{{{description}}}"){{^-last}},{{/-last}}{{/responseHeaders}} + },{{/responseHeaders.0}} content = { + {{^vendorExtensions.x-java-is-response-void}}@org.eclipse.microprofile.openapi.annotations.media.Content(schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(implementation = {{{baseType}}}.class{{#vendorExtensions.x-microprofile-open-api-return-schema-container}}, type = {{{.}}} {{/vendorExtensions.x-microprofile-open-api-return-schema-container}}{{#vendorExtensions.x-microprofile-open-api-return-unique-items}}, uniqueItems = true {{/vendorExtensions.x-microprofile-open-api-return-unique-items}})){{/vendorExtensions.x-java-is-response-void}} + }){{^-last}},{{/-last}}{{/responses}} + }){{/hasProduces}}{{/useMicroProfileOpenAPIAnnotations}} + {{#supportAsync}}{{>returnAsyncTypeInterface}}{{/supportAsync}}{{^supportAsync}}{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{>returnTypeInterface}}{{/returnResponse}}{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}); \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiMethod.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiMethod.mustache new file mode 100644 index 000000000..5bd7a3e4e --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/apiMethod.mustache @@ -0,0 +1,45 @@ + {{#useGzipFeature}} + @GZIP + {{/useGzipFeature}} + @{{httpMethod}}{{#subresourceOperation}} + @Path("{{{path}}}"){{/subresourceOperation}}{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} }){{/hasConsumes}}{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }){{/hasProduces}}{{#useSwaggerAnnotations}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnBaseType}}}.class{{#returnContainer}}, responseContainer = "{{{.}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}{{#isOAuth}}@Authorization(value = "{{name}}", scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}}, + {{/-last}}{{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}} + {{^isOAuth}}@Authorization(value = "{{name}}"){{^-last}},{{/-last}} + {{/isOAuth}}{{/authMethods}} }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{^-last}}, {{/-last}}{{/vendorExtensions.x-tags}} }) + {{#implicitHeadersParams.0}} + @io.swagger.annotations.ApiImplicitParams({ + {{#implicitHeadersParams}} + @io.swagger.annotations.ApiImplicitParam(name = "{{{baseName}}}", value = "{{{description}}}", {{#required}}required = true,{{/required}} dataType = "{{{dataType}}}", paramType = "header"){{^-last}},{{/-last}} + {{/implicitHeadersParams}} + }) + {{/implicitHeadersParams.0}} + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{baseType}}}.class{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}},{{/-last}}{{/responses}} + }){{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}} + {{#hasAuthMethods}}@org.eclipse.microprofile.openapi.annotations.security.SecurityRequirements(value={ + {{#authMethods}}{{#isOAuth}}@org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "{{name}}", scopes = { {{#scopes}} "{{scope}}"{{^-last}},{{/-last}} {{/scopes}} }){{^-last}},{{/-last}}{{/isOAuth}}{{^isOAuth}} @org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement(name = "{{name}}"){{^-last}},{{/-last}}{{/isOAuth}} + {{/authMethods}} }){{/hasAuthMethods}} + @org.eclipse.microprofile.openapi.annotations.Operation(operationId = "{{{operationId}}}", summary = "{{{summary}}}", description = "{{{notes}}}") + {{#vendorExtensions.x-tags}}@org.eclipse.microprofile.openapi.annotations.tags.Tag(name="{{tag}}"){{^-last}}, {{/-last}}{{/vendorExtensions.x-tags}}{{#hasProduces}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponses(value = { {{#responses}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponse(responseCode = "{{{code}}}", description = "{{{message}}}", {{#responseHeaders.0}}headers = { {{#responseHeaders}} + @org.eclipse.microprofile.openapi.annotations.headers.Header(name = "{{{baseName}}}", schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(type = {{{vendorExtensions.x-microprofile-open-api-schema-type}}}), description = "{{{description}}}"){{^-last}},{{/-last}}{{/responseHeaders}} + },{{/responseHeaders.0}} content = { {{#produces}} + @org.eclipse.microprofile.openapi.annotations.media.Content(mediaType="{{{mediaType}}}"{{^vendorExtensions.x-java-is-response-void}}, schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(implementation = {{{baseType}}}.class{{#vendorExtensions.x-microprofile-open-api-return-schema-container}}, type = {{{.}}} {{/vendorExtensions.x-microprofile-open-api-return-schema-container}}{{#vendorExtensions.x-microprofile-open-api-return-unique-items}}, uniqueItems = true {{/vendorExtensions.x-microprofile-open-api-return-unique-items}}){{/vendorExtensions.x-java-is-response-void}}){{^-last}},{{/-last}}{{/produces}} + }){{^-last}},{{/-last}}{{/responses}} + }){{/hasProduces}}{{^hasProduces}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponses(value = { {{#responses}} + @org.eclipse.microprofile.openapi.annotations.responses.APIResponse(responseCode = "{{{code}}}", description = "{{{message}}}", {{#responseHeaders.0}}headers = { {{#responseHeaders}} + @org.eclipse.microprofile.openapi.annotations.headers.Header(name = "{{{baseName}}}", schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(type = {{{vendorExtensions.x-microprofile-open-api-schema-type}}}), description = "{{{description}}}"){{^-last}},{{/-last}}{{/responseHeaders}} + },{{/responseHeaders.0}} content = { + {{^vendorExtensions.x-java-is-response-void}}@org.eclipse.microprofile.openapi.annotations.media.Content(schema = @org.eclipse.microprofile.openapi.annotations.media.Schema(implementation = {{{baseType}}}.class{{#vendorExtensions.x-microprofile-open-api-return-schema-container}}, type = {{{.}}} {{/vendorExtensions.x-microprofile-open-api-return-schema-container}}{{#vendorExtensions.x-microprofile-open-api-return-unique-items}}, uniqueItems = true {{/vendorExtensions.x-microprofile-open-api-return-unique-items}})){{/vendorExtensions.x-java-is-response-void}} + }){{^-last}},{{/-last}}{{/responses}} + }){{/hasProduces}}{{/useMicroProfileOpenAPIAnnotations}} + public {{#supportAsync}}{{#useMutiny}}Uni{{/useMutiny}}{{^useMutiny}}CompletionStage{{/useMutiny}}<{{/supportAsync}}Response{{#supportAsync}}>{{/supportAsync}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>cookieParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}) { + return {{#supportAsync}}{{#useMutiny}}Uni.createFrom().item({{/useMutiny}}{{^useMutiny}}CompletableFuture.supplyAsync(() -> {{/useMutiny}}{{/supportAsync}}Response.ok().entity("magic!").build(){{#supportAsync}}){{/supportAsync}}; + } \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/application.properties.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/application.properties.mustache new file mode 100644 index 000000000..54d251726 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/application.properties.mustache @@ -0,0 +1,9 @@ +# Configuration file +# key = value + +mp.openapi.scan.disable=true + +{{#useGzipFeature}} +quarkus.resteasy.gzip.enabled=true +quarkus.resteasy.gzip.max-input=10M +{{/useGzipFeature}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/dockerignore.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/dockerignore.mustache new file mode 100644 index 000000000..b86c7ac34 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/dockerignore.mustache @@ -0,0 +1,4 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/pom.mustache new file mode 100644 index 000000000..ef91cc3df --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/pom.mustache @@ -0,0 +1,206 @@ + + + 4.0.0 + {{groupId}} + {{artifactId}} + {{artifactId}} + {{artifactVersion}} + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} + + + 3.8.1 + true + 1.8 + 1.8 + UTF-8 + UTF-8 +{{#useJakartaEe}} + 3.0.1.Final + 3.0.1.Final +{{/useJakartaEe}} +{{^useJakartaEe}} + 1.13.7.Final + 1.13.7.Final +{{/useJakartaEe}} + quarkus-universe-bom + io.quarkus + 2.22.1 +{{#useJakartaEe}} + 3.1.0 + 2.1.1 +{{/useJakartaEe}} +{{^useJakartaEe}} + 2.1.1 + 1.3.2 +{{/useJakartaEe}} +{{#useSwaggerAnnotations}} + 1.6.10 +{{/useSwaggerAnnotations}} +{{#useMutiny}} + 1.2.1 +{{/useMutiny}} + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + io.quarkus + quarkus-smallrye-openapi + +{{#useJakartaEe}} + + jakarta.ws.rs + jakarta.ws.rs-api + ${jakarta.ws.rs-version} + provided + + + jakarta.annotation + jakarta.annotation-api + ${jakarta.annotation-api-version} + +{{/useJakartaEe}} +{{^useJakartaEe}} + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs-version} + provided + + + javax.annotation + javax.annotation-api + ${javax.annotation-api-version} + +{{/useJakartaEe}} +{{#useSwaggerAnnotations}} + + io.swagger + swagger-annotations + ${io.swagger.annotations.version} + provided + +{{/useSwaggerAnnotations}} +{{#useMutiny}} + + io.smallrye + smallrye-rest-client + ${smallrye.rest.client.version} + test + +{{/useMutiny}} + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + io.quarkus + quarkus-maven-plugin + ${quarkus-plugin.version} + + + + build + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + + + + + + + + + native + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/returnAsyncTypeInterface.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/returnAsyncTypeInterface.mustache new file mode 100644 index 000000000..93f1098e4 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/quarkus/returnAsyncTypeInterface.mustache @@ -0,0 +1 @@ +{{#useMutiny}}Uni{{/useMutiny}}{{^useMutiny}}CompletionStage{{/useMutiny}}<{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{#returnContainer}}{{#isMap}}Map{{/isMap}}{{#isArray}}{{{returnContainer}}}<{{{returnBaseType}}}>{{/isArray}}{{/returnContainer}}{{^returnContainer}}{{{returnBaseType}}}{{/returnContainer}}{{/returnResponse}}> \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/README.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/README.mustache new file mode 100644 index 000000000..c4ec90cbd --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/README.mustache @@ -0,0 +1,37 @@ +# JAX-RS server with OpenAPI using Thorntail + +## Overview +This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using an +[OpenAPI-Spec](https://openapis.org), you can easily generate a server stub. + +This is an example of building a OpenAPI-enabled JAX-RS server. +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework and +the [Eclipse-MicroProfile-OpenAPI](https://github.com/eclipse/microprofile-open-api) addition. + +The pom file is configured to use [Thorntail](https://thorntail.io) as application server. + +{{#interfaceOnly}} +This project produces a jar that defines some interfaces. +The jar can be used in combination with another project providing the implementation. +{{/interfaceOnly}} + +{{^interfaceOnly}} +To start the server with maven, run this command: + +```bash +mvn thorntail:run +``` + +You can then call your server endpoints under: + +``` +http://localhost:8080/ +``` + +The OpenAPI specification is available at: + +``` +http://localhost:8080/openapi +``` + +{{/interfaceOnly}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/pom.mustache new file mode 100644 index 000000000..77121b6b5 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/libraries/thorntail/pom.mustache @@ -0,0 +1,90 @@ + + + 4.0.0 + {{groupId}} + {{artifactId}} + {{artifactId}} + {{artifactVersion}} + war + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} + + + 2.5.0.Final + 4.8.1 + 1.8 + 1.8 + false + UTF-8 + + + + + io.thorntail + bom-all + ${version.thorntail} + import + pom + + + + + + io.thorntail + jaxrs + + + io.thorntail + microprofile-openapi + + + junit + junit + ${version.junit} + test + + + + {{artifactId}} + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + io.thorntail + thorntail-maven-plugin + ${version.thorntail} + + + + package + + + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/model.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/model.mustache new file mode 100644 index 000000000..470b8eaf8 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/model.mustache @@ -0,0 +1,10 @@ +package {{package}}; + +{{#models}} + {{#model}} + {{#isEnum}} + {{>enumOuterClass}} + {{/isEnum}} + {{^isEnum}}{{>pojo}}{{/isEnum}} + {{/model}} +{{/models}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/openapi.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/openapi.mustache new file mode 100644 index 000000000..51ebafb01 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/openapi.mustache @@ -0,0 +1 @@ +{{{openapi-yaml}}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/param.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/param.mustache new file mode 100644 index 000000000..3141dee2d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/param.mustache @@ -0,0 +1 @@ +{{#isQueryParam}} {{paramName}}{{/isQueryParam}}{{#isPathParam}} {{paramName}}{{/isPathParam}}{{#isBodyParam}} {{paramName}}{{/isBodyParam}}{{#isHeaderParam}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pathParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pathParams.mustache new file mode 100644 index 000000000..fea718e31 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}}{{#description}} @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="{{.}}"){{/description}}{{/useMicroProfileOpenAPIAnnotations}} {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pojo.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pojo.mustache new file mode 100644 index 000000000..e63362eb2 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pojo.mustache @@ -0,0 +1,228 @@ +{{#hasRequired}}import com.fasterxml.jackson.annotation.JsonCreator;{{/hasRequired}} +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonTypeName; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import javax.validation.Valid; +{{#hasRequired}}import javax.validation.constraints.NotNull;{{/hasRequired}} + +{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{#description}}/** +* {{.}} +**/{{/description}} +{{#useSwaggerAnnotations}}{{#description}}@ApiModel(description = "{{{.}}}"){{/description}}{{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}} + @org.eclipse.microprofile.openapi.annotations.media.Schema({{#title}}title="{{{.}}}", {{/title}}{{#description}}description="{{{.}}}"{{/description}}{{^description}}description=""{{/description}}){{/useMicroProfileOpenAPIAnnotations}} +@JsonTypeName("{{name}}") +{{>generatedAnnotation}}{{>additionalModelTypeAnnotations}} +{{#vendorExtensions.x-class-extra-annotation}} + {{{vendorExtensions.x-class-extra-annotation}}} +{{/vendorExtensions.x-class-extra-annotation}} +public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { +{{#vars}} + {{#isEnum}} + {{^isContainer}} + {{>enumClass}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} + {{>enumClass}} + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#vendorExtensions.x-field-extra-annotation}} + {{{vendorExtensions.x-field-extra-annotation}}} + {{/vendorExtensions.x-field-extra-annotation}} + private {{#isContainer}}{{#useBeanValidation}}@Valid {{/useBeanValidation}}{{/isContainer}}{{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; +{{/vars}} + +{{#generateBuilders}} + {{^additionalProperties}} + protected {{classname}}({{classname}}Builder b) { + {{#parent}} + super(b); + {{/parent}} + {{#vars}} + this.{{name}} = b.{{name}}; + {{/vars}} + } + + {{/additionalProperties}} +{{/generateBuilders}} +public {{classname}}() { +} + +{{#hasRequired}} + @JsonCreator + public {{classname}}( + {{#requiredVars}} + @JsonProperty(required = {{required}}, value = "{{baseName}}") {{>beanValidatedType}} {{name}}{{^-last}},{{/-last}} + {{/requiredVars}} + ) { + {{#parent}} + super( + {{#parentRequiredVars}} + {{name}}{{^-last}},{{/-last}} + {{/parentRequiredVars}} + ); + {{/parent}} + {{#vars}} + {{#required}} + this.{{name}} = {{name}}; + {{/required}} + {{/vars}} + } + +{{/hasRequired}} +{{#vars}} + /** + {{#description}} + * {{.}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + **/ + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + + {{#vendorExtensions.x-extra-annotation}}{{{vendorExtensions.x-extra-annotation}}}{{/vendorExtensions.x-extra-annotation}}{{#useSwaggerAnnotations}} + @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}"){{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}} + @org.eclipse.microprofile.openapi.annotations.media.Schema({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}description = "{{{description}}}"){{/useMicroProfileOpenAPIAnnotations}} + @JsonProperty({{#required}}required = {{required}}, value = {{/required}}"{{baseName}}") + {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}}public {{>beanValidatedType}} {{getter}}() { + return {{name}}; + } + + @JsonProperty({{#required}}required = {{required}}, value = {{/required}}"{{baseName}}") + {{#vendorExtensions.x-setter-extra-annotation}}{{{vendorExtensions.x-setter-extra-annotation}}} + {{/vendorExtensions.x-setter-extra-annotation}}public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{#isArray}} + public {{classname}} add{{nameInPascalCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}; + } + + this.{{name}}.add({{name}}Item); + return this; + } + + public {{classname}} remove{{nameInPascalCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + if ({{name}}Item != null && this.{{name}} != null) { + this.{{name}}.remove({{name}}Item); + } + + return this; + } + {{/isArray}} + {{#isMap}} + public {{classname}} put{{nameInPascalCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}; + } + + this.{{name}}.put(key, {{name}}Item); + return this; + } + + public {{classname}} remove{{nameInPascalCase}}Item(String key) { + if (this.{{name}} != null) { + this.{{name}}.remove(key); + } + + return this; + } + {{/isMap}} +{{/vars}} + +@Override +public boolean equals(Object o) { +if (this == o) { +return true; +} +if (o == null || getClass() != o.getClass()) { +return false; +}{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + {{/-last}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} +} + +@Override +public int hashCode() { +return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); +} + +@Override +public String toString() { +StringBuilder sb = new StringBuilder(); +sb.append("class {{classname}} {\n"); +{{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} +{{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); +{{/vars}}sb.append("}"); +return sb.toString(); +} + +/** +* Convert the given object to string with each line indented by 4 spaces +* (except the first line). +*/ +private String toIndentedString(Object o) { +if (o == null) { +return "null"; +} +return o.toString().replace("\n", "\n "); +} + +{{#generateBuilders}}{{^additionalProperties}} + public static {{classname}}Builder builder() { + return new {{classname}}BuilderImpl(); + } + + private static final class {{classname}}BuilderImpl extends {{classname}}Builder<{{classname}}, {{classname}}BuilderImpl> { + + @Override + protected {{classname}}BuilderImpl self() { + return this; + } + + @Override + public {{classname}} build() { + return new {{classname}}(this); + } + } + + public static abstract class {{classname}}Builder + > {{#parent}}extends {{{.}}}Builder + {{/parent}} { + {{#vars}} + private {{#removeAnnotations}}{{{datatypeWithEnum}}}{{/removeAnnotations}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/vars}} + {{^parent}} + protected abstract B self(); + + public abstract C build(); + {{/parent}} + + {{#vars}} + public B {{name}}({{#removeAnnotations}}{{{datatypeWithEnum}}}{{/removeAnnotations}} {{name}}) { + this.{{name}} = {{name}}; + return self(); + } + {{/vars}} + }{{/additionalProperties}}{{/generateBuilders}} +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pom.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pom.mustache new file mode 100644 index 000000000..e3e888baf --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/pom.mustache @@ -0,0 +1,206 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + {{#interfaceOnly}}jar{{/interfaceOnly}}{{^interfaceOnly}}war{{/interfaceOnly}} + {{artifactId}} + {{artifactVersion}} + +{{#parentOverridden}} + + {{parentGroupId}} + {{parentArtifactId}} + {{parentVersion}} + +{{/parentOverridden}} + + + src/main/java + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + {{#interfaceOnly}} + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + {{/interfaceOnly}} + {{^interfaceOnly}} + + org.apache.maven.plugins + maven-war-plugin + 3.1.0 + + false + + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + {{/interfaceOnly}} + + + + + jakarta.ws.rs + jakarta.ws.rs-api + ${jakarta.ws.rs-version} + provided + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + {{^useJakartaEe}} + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + {{/useJakartaEe}} + {{#useJakartaEe}} + + com.fasterxml.jackson.jakarta.rs + jackson-jakarta-rs-json-provider + ${jackson-version} + + {{/useJakartaEe}} + + joda-time + joda-time + ${joda-version} + + {{#useJakartaEe}} + + jakarta.annotation + jakarta.annotation-api + ${javax.annotation-api-version} + + {{/useJakartaEe}} + {{^useJakartaEe}} + + javax.annotation + javax.annotation-api + ${javax.annotation-api-version} + + {{/useJakartaEe}} + {{#useSwaggerAnnotations}} + + io.swagger + swagger-annotations + provided + 1.5.3 + + {{/useSwaggerAnnotations}} + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + junit + junit + ${junit-version} + test + + {{^interfaceOnly}} + + org.testng + testng + 6.8.8 + test + + + junit + junit + + + snakeyaml + org.yaml + + + bsh + org.beanshell + + + + {{/interfaceOnly}} + {{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + provided + + {{/useBeanValidation}} + {{#openApiNullable}} + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + {{/openApiNullable}} + + + 1.8 + ${java.version} + ${java.version} + UTF-8 + 2.17.1 + 4.13.2 + 2.10.13 +{{#useJakartaEe}} + 2.1.1 +{{/useJakartaEe}} +{{^useJakartaEe}} + 1.3.2 +{{/useJakartaEe}} +{{#useBeanValidation}} +{{#useJakartaEe}} + 3.0.2 +{{/useJakartaEe}} +{{^useJakartaEe}} + 2.0.2 +{{/useJakartaEe}} +{{/useBeanValidation}} +{{#useJakartaEe}} + 3.1.0 +{{/useJakartaEe}} +{{^useJakartaEe}} + 2.1.6 +{{/useJakartaEe}} +{{#openApiNullable}} + 0.2.6 +{{/openApiNullable}} + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/queryParams.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/queryParams.mustache new file mode 100644 index 000000000..b8a505afe --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/queryParams.mustache @@ -0,0 +1,3 @@ +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation +}}{{^isContainer}}{{#defaultValue}} @DefaultValue("{{{.}}}"){{/defaultValue}}{{/isContainer}} {{#useSwaggerAnnotations}}{{#description}} @ApiParam("{{.}}"){{/description}}{{/useSwaggerAnnotations}}{{#useMicroProfileOpenAPIAnnotations}}{{#description}} @org.eclipse.microprofile.openapi.annotations.parameters.Parameter(description="{{.}}"){{/description}}{{/useMicroProfileOpenAPIAnnotations}}{{#isBoolean}}boolean{{/isBoolean}}{{#isByte}}byte{{/isByte}}{{#isShort}}short{{/isShort}}{{#isInt}}int{{/isInt}}{{#isLong}}long{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}double{{/isDouble}}{{#isChar}}char{{/isChar}}{{#isByteObject}}byte{{/isByteObject}}{{#isShortObject}}short{{/isShortObject}}{{#isInteger}}int{{/isInteger}}{{#isLongObject}}long{{/isLongObject}}{{#isFloatObject}}float{{/isFloatObject}}{{#isDoubleObject}}Double{{/isDoubleObject}}{{#isString}}String{{/isString}} {{paramName}}{{/isQueryParam}} + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnAsyncTypeInterface.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnAsyncTypeInterface.mustache new file mode 100644 index 000000000..0da348c7a --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnAsyncTypeInterface.mustache @@ -0,0 +1 @@ +CompletionStage<{{#returnResponse}}Response{{/returnResponse}}{{^returnResponse}}{{#returnContainer}}{{#isMap}}Map{{/isMap}}{{#isArray}}{{{returnContainer}}}<{{{returnBaseType}}}>{{/isArray}}{{/returnContainer}}{{^returnContainer}}{{{returnBaseType}}}{{/returnContainer}}{{/returnResponse}}> \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnTypeInterface.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnTypeInterface.mustache new file mode 100644 index 000000000..1bfa056f0 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/returnTypeInterface.mustache @@ -0,0 +1 @@ +{{{returnType}}} \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/typeInfoAnnotation.mustache b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/typeInfoAnnotation.mustache new file mode 100644 index 000000000..5b7bb5cd3 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/resources/template-for-openapi-code-generation/typeInfoAnnotation.mustache @@ -0,0 +1,8 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{{discriminator.propertyBaseName}}}", visible = true) +@JsonSubTypes({ + {{#discriminator.mappedModels}} + @JsonSubTypes.Type(value = {{modelName}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{mappingName}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/discriminator.mappedModels}} +}) +{{/jackson}} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/context.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/context.xml new file mode 100644 index 000000000..62f0fe8e2 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/context.xml @@ -0,0 +1,9 @@ + + + + + \ No newline at end of file diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/webapp-classloading.xml b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 000000000..ffebb8c36 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,35 @@ + + + + + + + + + false + + + CXF3 + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/schema.sql b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/schema.sql new file mode 100644 index 000000000..1c0dddfd7 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/schema.sql @@ -0,0 +1,65 @@ + +CREATE TABLE IF NOT EXISTS FS_CONSENT ( + CONSENT_ID VARCHAR(255) NOT NULL, + RECEIPT BLOB NOT NULL, + CREATED_TIME BIGINT NOT NULL, + UPDATED_TIME BIGINT NOT NULL, + CLIENT_ID VARCHAR(255) NOT NULL, + ORG_ID VARCHAR(255) DEFAULT 'DEFAULT_ORG', + CONSENT_TYPE VARCHAR(64) NOT NULL, + CURRENT_STATUS VARCHAR(64) NOT NULL, + CONSENT_FREQUENCY INT, + VALIDITY_TIME BIGINT, + RECURRING_INDICATOR BOOLEAN, + PRIMARY KEY (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_AUTH_RESOURCE ( + AUTH_ID VARCHAR(255) NOT NULL, + CONSENT_ID VARCHAR(255) NOT NULL, + AUTH_TYPE VARCHAR(255) NOT NULL, + USER_ID VARCHAR(255), + AUTH_STATUS VARCHAR(255) NOT NULL, + UPDATED_TIME BIGINT NOT NULL, + PRIMARY KEY(AUTH_ID), + CONSTRAINT FK_ID_FS_CONSENT_AUTH_RESOURCE FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_MAPPING ( + MAPPING_ID VARCHAR(255) NOT NULL, + AUTH_ID VARCHAR(255) NOT NULL, + MAPPING_STATUS VARCHAR(255) NOT NULL, + RESOURCE BLOB NOT NULL, + PRIMARY KEY(MAPPING_ID), + CONSTRAINT FK_FS_CONSENT_MAPPING FOREIGN KEY (AUTH_ID) REFERENCES FS_CONSENT_AUTH_RESOURCE (AUTH_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_STATUS_AUDIT ( + STATUS_AUDIT_ID VARCHAR(255) NOT NULL, + CONSENT_ID VARCHAR(255) NOT NULL, + CURRENT_STATUS VARCHAR(255) NOT NULL, + ACTION_TIME BIGINT NOT NULL, + REASON VARCHAR(255), + ACTION_BY VARCHAR(255), + PREVIOUS_STATUS VARCHAR(255), + PRIMARY KEY(STATUS_AUDIT_ID), + CONSTRAINT FK_FS_CONSENT_STATUS_AUDIT FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_ATTRIBUTE ( + CONSENT_ID VARCHAR(255) NOT NULL, + ATT_KEY VARCHAR(255) NOT NULL, + ATT_VALUE LONGTEXT NOT NULL, + PRIMARY KEY(CONSENT_ID, ATT_KEY), + CONSTRAINT FK_FS_CONSENT_ATTRIBUTE FOREIGN KEY (CONSENT_ID) REFERENCES FS_CONSENT (CONSENT_ID) +); + +CREATE TABLE IF NOT EXISTS FS_CONSENT_HISTORY ( + TABLE_ID VARCHAR(10) NOT NULL, + RECORD_ID VARCHAR(255) NOT NULL, + HISTORY_ID VARCHAR(255) NOT NULL, + CHANGED_VALUES BLOB NOT NULL, + REASON VARCHAR(255) NOT NULL, + EFFECTIVE_TIMESTAMP BIGINT NOT NULL, +PRIMARY KEY (TABLE_ID,RECORD_ID,HISTORY_ID) +); diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-16x16.png b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-16x16.png new file mode 100644 index 000000000..8b194e617 Binary files /dev/null and b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-16x16.png differ diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-32x32.png b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-32x32.png new file mode 100644 index 000000000..249737fe4 Binary files /dev/null and b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/favicon-32x32.png differ diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.css b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.css new file mode 100644 index 000000000..f2376fdaa --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.css @@ -0,0 +1,16 @@ +html { + box-sizing: border-box; + overflow: -moz-scrollbars-vertical; + overflow-y: scroll; +} + +*, +*:before, +*:after { + box-sizing: inherit; +} + +body { + margin: 0; + background: #fafafa; +} diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.html b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.html new file mode 100644 index 000000000..84ae62d3d --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/index.html @@ -0,0 +1,19 @@ + + + + + + Swagger UI + + + + + + + +
+ + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/oauth2-redirect.html b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/oauth2-redirect.html new file mode 100644 index 000000000..564091718 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/oauth2-redirect.html @@ -0,0 +1,79 @@ + + + + Swagger UI: OAuth2 Redirect + + + + + diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-initializer.js b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-initializer.js new file mode 100644 index 000000000..900eeac3f --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-initializer.js @@ -0,0 +1,20 @@ +window.onload = function() { + // + + // the following lines will be replaced by docker/configurator, when it runs in a docker-container + window.ui = SwaggerUIBundle({ + url: "http://localhost:8080/api/openapi.json", + dom_id: '#swagger-ui', + deepLinking: true, + presets: [ + SwaggerUIBundle.presets.apis, + SwaggerUIStandalonePreset + ], + plugins: [ + SwaggerUIBundle.plugins.DownloadUrl + ], + layout: "StandaloneLayout" + }); + + // +}; diff --git a/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-ui-bundle.js b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-ui-bundle.js new file mode 100644 index 000000000..8c898e475 --- /dev/null +++ b/financial-services-accelerator/components/org.wso2.financial.services.accelerator.consent.mgt.api/webapp/org.wso2.financial.services.accelerator.consent.mgt.endpoint/src/main/webapp/WEB-INF/swagger-ui/swagger-ui-bundle.js @@ -0,0 +1,2 @@ +/*! For license information please see swagger-ui-bundle.js.LICENSE.txt */ +!function webpackUniversalModuleDefinition(s,o){"object"==typeof exports&&"object"==typeof module?module.exports=o():"function"==typeof define&&define.amd?define([],o):"object"==typeof exports?exports.SwaggerUIBundle=o():s.SwaggerUIBundle=o()}(this,(()=>(()=>{var s={251:(s,o)=>{o.read=function(s,o,i,a,u){var _,w,x=8*u-a-1,C=(1<>1,L=-7,B=i?u-1:0,$=i?-1:1,V=s[o+B];for(B+=$,_=V&(1<<-L)-1,V>>=-L,L+=x;L>0;_=256*_+s[o+B],B+=$,L-=8);for(w=_&(1<<-L)-1,_>>=-L,L+=a;L>0;w=256*w+s[o+B],B+=$,L-=8);if(0===_)_=1-j;else{if(_===C)return w?NaN:1/0*(V?-1:1);w+=Math.pow(2,a),_-=j}return(V?-1:1)*w*Math.pow(2,_-a)},o.write=function(s,o,i,a,u,_){var w,x,C,j=8*_-u-1,L=(1<>1,$=23===u?Math.pow(2,-24)-Math.pow(2,-77):0,V=a?0:_-1,U=a?1:-1,z=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(x=isNaN(o)?1:0,w=L):(w=Math.floor(Math.log(o)/Math.LN2),o*(C=Math.pow(2,-w))<1&&(w--,C*=2),(o+=w+B>=1?$/C:$*Math.pow(2,1-B))*C>=2&&(w++,C/=2),w+B>=L?(x=0,w=L):w+B>=1?(x=(o*C-1)*Math.pow(2,u),w+=B):(x=o*Math.pow(2,B-1)*Math.pow(2,u),w=0));u>=8;s[i+V]=255&x,V+=U,x/=256,u-=8);for(w=w<0;s[i+V]=255&w,V+=U,w/=256,j-=8);s[i+V-U]|=128*z}},462:(s,o,i)=>{"use strict";var a=i(40975);s.exports=a},659:(s,o,i)=>{var a=i(51873),u=Object.prototype,_=u.hasOwnProperty,w=u.toString,x=a?a.toStringTag:void 0;s.exports=function getRawTag(s){var o=_.call(s,x),i=s[x];try{s[x]=void 0;var a=!0}catch(s){}var u=w.call(s);return a&&(o?s[x]=i:delete s[x]),u}},694:(s,o,i)=>{"use strict";i(91599);var a=i(37257);i(12560),s.exports=a},953:(s,o,i)=>{"use strict";s.exports=i(53375)},1733:s=>{var o=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;s.exports=function asciiWords(s){return s.match(o)||[]}},1882:(s,o,i)=>{var a=i(72552),u=i(23805);s.exports=function isFunction(s){if(!u(s))return!1;var o=a(s);return"[object Function]"==o||"[object GeneratorFunction]"==o||"[object AsyncFunction]"==o||"[object Proxy]"==o}},1907:(s,o,i)=>{"use strict";var a=i(41505),u=Function.prototype,_=u.call,w=a&&u.bind.bind(_,_);s.exports=a?w:function(s){return function(){return _.apply(s,arguments)}}},2205:function(s,o,i){var a;a=void 0!==i.g?i.g:this,s.exports=function(s){if(s.CSS&&s.CSS.escape)return s.CSS.escape;var cssEscape=function(s){if(0==arguments.length)throw new TypeError("`CSS.escape` requires an argument.");for(var o,i=String(s),a=i.length,u=-1,_="",w=i.charCodeAt(0);++u=1&&o<=31||127==o||0==u&&o>=48&&o<=57||1==u&&o>=48&&o<=57&&45==w?"\\"+o.toString(16)+" ":0==u&&1==a&&45==o||!(o>=128||45==o||95==o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122)?"\\"+i.charAt(u):i.charAt(u):_+="�";return _};return s.CSS||(s.CSS={}),s.CSS.escape=cssEscape,cssEscape}(a)},2209:(s,o,i)=>{"use strict";var a,u=i(9404),_=function productionTypeChecker(){invariant(!1,"ImmutablePropTypes type checking code is stripped in production.")};_.isRequired=_;var w=function getProductionTypeChecker(){return _};function getPropType(s){var o=typeof s;return Array.isArray(s)?"array":s instanceof RegExp?"object":s instanceof u.Iterable?"Immutable."+s.toSource().split(" ")[0]:o}function createChainableTypeChecker(s){function checkType(o,i,a,u,_,w){for(var x=arguments.length,C=Array(x>6?x-6:0),j=6;j>",null!=i[a]?s.apply(void 0,[i,a,u,_,w].concat(C)):o?new Error("Required "+_+" `"+w+"` was not specified in `"+u+"`."):void 0}var o=checkType.bind(null,!1);return o.isRequired=checkType.bind(null,!0),o}function createIterableSubclassTypeChecker(s,o){return function createImmutableTypeChecker(s,o){return createChainableTypeChecker((function validate(i,a,u,_,w){var x=i[a];if(!o(x)){var C=getPropType(x);return new Error("Invalid "+_+" `"+w+"` of type `"+C+"` supplied to `"+u+"`, expected `"+s+"`.")}return null}))}("Iterable."+s,(function(s){return u.Iterable.isIterable(s)&&o(s)}))}(a={listOf:w,mapOf:w,orderedMapOf:w,setOf:w,orderedSetOf:w,stackOf:w,iterableOf:w,recordOf:w,shape:w,contains:w,mapContains:w,orderedMapContains:w,list:_,map:_,orderedMap:_,set:_,orderedSet:_,stack:_,seq:_,record:_,iterable:_}).iterable.indexed=createIterableSubclassTypeChecker("Indexed",u.Iterable.isIndexed),a.iterable.keyed=createIterableSubclassTypeChecker("Keyed",u.Iterable.isKeyed),s.exports=a},2404:(s,o,i)=>{var a=i(60270);s.exports=function isEqual(s,o){return a(s,o)}},2523:s=>{s.exports=function baseFindIndex(s,o,i,a){for(var u=s.length,_=i+(a?1:-1);a?_--:++_{"use strict";var a=i(45951),u=Object.defineProperty;s.exports=function(s,o){try{u(a,s,{value:o,configurable:!0,writable:!0})}catch(i){a[s]=o}return o}},2694:(s,o,i)=>{"use strict";var a=i(6925);function emptyFunction(){}function emptyFunctionWithReset(){}emptyFunctionWithReset.resetWarningCache=emptyFunction,s.exports=function(){function shim(s,o,i,u,_,w){if(w!==a){var x=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw x.name="Invariant Violation",x}}function getShim(){return shim}shim.isRequired=shim;var s={array:shim,bigint:shim,bool:shim,func:shim,number:shim,object:shim,string:shim,symbol:shim,any:shim,arrayOf:getShim,element:shim,elementType:shim,instanceOf:getShim,node:shim,objectOf:getShim,oneOf:getShim,oneOfType:getShim,shape:getShim,exact:getShim,checkPropTypes:emptyFunctionWithReset,resetWarningCache:emptyFunction};return s.PropTypes=s,s}},2874:s=>{s.exports={}},2875:(s,o,i)=>{"use strict";var a=i(23045),u=i(80376);s.exports=Object.keys||function keys(s){return a(s,u)}},2955:(s,o,i)=>{"use strict";var a,u=i(65606);function _defineProperty(s,o,i){return(o=function _toPropertyKey(s){var o=function _toPrimitive(s,o){if("object"!=typeof s||null===s)return s;var i=s[Symbol.toPrimitive];if(void 0!==i){var a=i.call(s,o||"default");if("object"!=typeof a)return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===o?String:Number)(s)}(s,"string");return"symbol"==typeof o?o:String(o)}(o))in s?Object.defineProperty(s,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):s[o]=i,s}var _=i(86238),w=Symbol("lastResolve"),x=Symbol("lastReject"),C=Symbol("error"),j=Symbol("ended"),L=Symbol("lastPromise"),B=Symbol("handlePromise"),$=Symbol("stream");function createIterResult(s,o){return{value:s,done:o}}function readAndResolve(s){var o=s[w];if(null!==o){var i=s[$].read();null!==i&&(s[L]=null,s[w]=null,s[x]=null,o(createIterResult(i,!1)))}}function onReadable(s){u.nextTick(readAndResolve,s)}var V=Object.getPrototypeOf((function(){})),U=Object.setPrototypeOf((_defineProperty(a={get stream(){return this[$]},next:function next(){var s=this,o=this[C];if(null!==o)return Promise.reject(o);if(this[j])return Promise.resolve(createIterResult(void 0,!0));if(this[$].destroyed)return new Promise((function(o,i){u.nextTick((function(){s[C]?i(s[C]):o(createIterResult(void 0,!0))}))}));var i,a=this[L];if(a)i=new Promise(function wrapForNext(s,o){return function(i,a){s.then((function(){o[j]?i(createIterResult(void 0,!0)):o[B](i,a)}),a)}}(a,this));else{var _=this[$].read();if(null!==_)return Promise.resolve(createIterResult(_,!1));i=new Promise(this[B])}return this[L]=i,i}},Symbol.asyncIterator,(function(){return this})),_defineProperty(a,"return",(function _return(){var s=this;return new Promise((function(o,i){s[$].destroy(null,(function(s){s?i(s):o(createIterResult(void 0,!0))}))}))})),a),V);s.exports=function createReadableStreamAsyncIterator(s){var o,i=Object.create(U,(_defineProperty(o={},$,{value:s,writable:!0}),_defineProperty(o,w,{value:null,writable:!0}),_defineProperty(o,x,{value:null,writable:!0}),_defineProperty(o,C,{value:null,writable:!0}),_defineProperty(o,j,{value:s._readableState.endEmitted,writable:!0}),_defineProperty(o,B,{value:function value(s,o){var a=i[$].read();a?(i[L]=null,i[w]=null,i[x]=null,s(createIterResult(a,!1))):(i[w]=s,i[x]=o)},writable:!0}),o));return i[L]=null,_(s,(function(s){if(s&&"ERR_STREAM_PREMATURE_CLOSE"!==s.code){var o=i[x];return null!==o&&(i[L]=null,i[w]=null,i[x]=null,o(s)),void(i[C]=s)}var a=i[w];null!==a&&(i[L]=null,i[w]=null,i[x]=null,a(createIterResult(void 0,!0))),i[j]=!0})),s.on("readable",onReadable.bind(null,i)),i}},3110:(s,o,i)=>{const a=i(5187),u=i(85015),_=i(98023),w=i(53812),x=i(23805),C=i(85105),j=i(86804);class Namespace{constructor(s){this.elementMap={},this.elementDetection=[],this.Element=j.Element,this.KeyValuePair=j.KeyValuePair,s&&s.noDefault||this.useDefault(),this._attributeElementKeys=[],this._attributeElementArrayKeys=[]}use(s){return s.namespace&&s.namespace({base:this}),s.load&&s.load({base:this}),this}useDefault(){return this.register("null",j.NullElement).register("string",j.StringElement).register("number",j.NumberElement).register("boolean",j.BooleanElement).register("array",j.ArrayElement).register("object",j.ObjectElement).register("member",j.MemberElement).register("ref",j.RefElement).register("link",j.LinkElement),this.detect(a,j.NullElement,!1).detect(u,j.StringElement,!1).detect(_,j.NumberElement,!1).detect(w,j.BooleanElement,!1).detect(Array.isArray,j.ArrayElement,!1).detect(x,j.ObjectElement,!1),this}register(s,o){return this._elements=void 0,this.elementMap[s]=o,this}unregister(s){return this._elements=void 0,delete this.elementMap[s],this}detect(s,o,i){return void 0===i||i?this.elementDetection.unshift([s,o]):this.elementDetection.push([s,o]),this}toElement(s){if(s instanceof this.Element)return s;let o;for(let i=0;i{const o=s[0].toUpperCase()+s.substr(1);this._elements[o]=this.elementMap[s]}))),this._elements}get serialiser(){return new C(this)}}C.prototype.Namespace=Namespace,s.exports=Namespace},3121:(s,o,i)=>{"use strict";var a=i(65482),u=Math.min;s.exports=function(s){var o=a(s);return o>0?u(o,9007199254740991):0}},3209:(s,o,i)=>{var a=i(91596),u=i(53320),_=i(36306),w="__lodash_placeholder__",x=128,C=Math.min;s.exports=function mergeData(s,o){var i=s[1],j=o[1],L=i|j,B=L<131,$=j==x&&8==i||j==x&&256==i&&s[7].length<=o[8]||384==j&&o[7].length<=o[8]&&8==i;if(!B&&!$)return s;1&j&&(s[2]=o[2],L|=1&i?0:4);var V=o[3];if(V){var U=s[3];s[3]=U?a(U,V,o[4]):V,s[4]=U?_(s[3],w):o[4]}return(V=o[5])&&(U=s[5],s[5]=U?u(U,V,o[6]):V,s[6]=U?_(s[5],w):o[6]),(V=o[7])&&(s[7]=V),j&x&&(s[8]=null==s[8]?o[8]:C(s[8],o[8])),null==s[9]&&(s[9]=o[9]),s[0]=o[0],s[1]=L,s}},3650:(s,o,i)=>{var a=i(74335)(Object.keys,Object);s.exports=a},3656:(s,o,i)=>{s=i.nmd(s);var a=i(9325),u=i(89935),_=o&&!o.nodeType&&o,w=_&&s&&!s.nodeType&&s,x=w&&w.exports===_?a.Buffer:void 0,C=(x?x.isBuffer:void 0)||u;s.exports=C},4509:(s,o,i)=>{var a=i(12651);s.exports=function mapCacheHas(s){return a(this,s).has(s)}},4640:s=>{"use strict";var o=String;s.exports=function(s){try{return o(s)}catch(s){return"Object"}}},4664:(s,o,i)=>{var a=i(79770),u=i(63345),_=Object.prototype.propertyIsEnumerable,w=Object.getOwnPropertySymbols,x=w?function(s){return null==s?[]:(s=Object(s),a(w(s),(function(o){return _.call(s,o)})))}:u;s.exports=x},4901:(s,o,i)=>{var a=i(72552),u=i(30294),_=i(40346),w={};w["[object Float32Array]"]=w["[object Float64Array]"]=w["[object Int8Array]"]=w["[object Int16Array]"]=w["[object Int32Array]"]=w["[object Uint8Array]"]=w["[object Uint8ClampedArray]"]=w["[object Uint16Array]"]=w["[object Uint32Array]"]=!0,w["[object Arguments]"]=w["[object Array]"]=w["[object ArrayBuffer]"]=w["[object Boolean]"]=w["[object DataView]"]=w["[object Date]"]=w["[object Error]"]=w["[object Function]"]=w["[object Map]"]=w["[object Number]"]=w["[object Object]"]=w["[object RegExp]"]=w["[object Set]"]=w["[object String]"]=w["[object WeakMap]"]=!1,s.exports=function baseIsTypedArray(s){return _(s)&&u(s.length)&&!!w[a(s)]}},4993:(s,o,i)=>{"use strict";var a=i(16946),u=i(74239);s.exports=function(s){return a(u(s))}},5187:s=>{s.exports=function isNull(s){return null===s}},5419:s=>{s.exports=function(s,o,i,a){var u=new Blob(void 0!==a?[a,s]:[s],{type:i||"application/octet-stream"});if(void 0!==window.navigator.msSaveBlob)window.navigator.msSaveBlob(u,o);else{var _=window.URL&&window.URL.createObjectURL?window.URL.createObjectURL(u):window.webkitURL.createObjectURL(u),w=document.createElement("a");w.style.display="none",w.href=_,w.setAttribute("download",o),void 0===w.download&&w.setAttribute("target","_blank"),document.body.appendChild(w),w.click(),setTimeout((function(){document.body.removeChild(w),window.URL.revokeObjectURL(_)}),200)}}},5556:(s,o,i)=>{s.exports=i(2694)()},5861:(s,o,i)=>{var a=i(55580),u=i(68223),_=i(32804),w=i(76545),x=i(28303),C=i(72552),j=i(47473),L="[object Map]",B="[object Promise]",$="[object Set]",V="[object WeakMap]",U="[object DataView]",z=j(a),Y=j(u),Z=j(_),ee=j(w),ie=j(x),ae=C;(a&&ae(new a(new ArrayBuffer(1)))!=U||u&&ae(new u)!=L||_&&ae(_.resolve())!=B||w&&ae(new w)!=$||x&&ae(new x)!=V)&&(ae=function(s){var o=C(s),i="[object Object]"==o?s.constructor:void 0,a=i?j(i):"";if(a)switch(a){case z:return U;case Y:return L;case Z:return B;case ee:return $;case ie:return V}return o}),s.exports=ae},6048:s=>{s.exports=function negate(s){if("function"!=typeof s)throw new TypeError("Expected a function");return function(){var o=arguments;switch(o.length){case 0:return!s.call(this);case 1:return!s.call(this,o[0]);case 2:return!s.call(this,o[0],o[1]);case 3:return!s.call(this,o[0],o[1],o[2])}return!s.apply(this,o)}}},6205:s=>{s.exports={ROOT:0,GROUP:1,POSITION:2,SET:3,RANGE:4,REPETITION:5,REFERENCE:6,CHAR:7}},6233:(s,o,i)=>{const a=i(6048),u=i(10316),_=i(92340);class ArrayElement extends u{constructor(s,o,i){super(s||[],o,i),this.element="array"}primitive(){return"array"}get(s){return this.content[s]}getValue(s){const o=this.get(s);if(o)return o.toValue()}getIndex(s){return this.content[s]}set(s,o){return this.content[s]=this.refract(o),this}remove(s){const o=this.content.splice(s,1);return o.length?o[0]:null}map(s,o){return this.content.map(s,o)}flatMap(s,o){return this.map(s,o).reduce(((s,o)=>s.concat(o)),[])}compactMap(s,o){const i=[];return this.forEach((a=>{const u=s.bind(o)(a);u&&i.push(u)})),i}filter(s,o){return new _(this.content.filter(s,o))}reject(s,o){return this.filter(a(s),o)}reduce(s,o){let i,a;void 0!==o?(i=0,a=this.refract(o)):(i=1,a="object"===this.primitive()?this.first.value:this.first);for(let o=i;o{s.bind(o)(i,this.refract(a))}))}shift(){return this.content.shift()}unshift(s){this.content.unshift(this.refract(s))}push(s){return this.content.push(this.refract(s)),this}add(s){this.push(s)}findElements(s,o){const i=o||{},a=!!i.recursive,u=void 0===i.results?[]:i.results;return this.forEach(((o,i,_)=>{a&&void 0!==o.findElements&&o.findElements(s,{results:u,recursive:a}),s(o,i,_)&&u.push(o)})),u}find(s){return new _(this.findElements(s,{recursive:!0}))}findByElement(s){return this.find((o=>o.element===s))}findByClass(s){return this.find((o=>o.classes.includes(s)))}getById(s){return this.find((o=>o.id.toValue()===s)).first}includes(s){return this.content.some((o=>o.equals(s)))}contains(s){return this.includes(s)}empty(){return new this.constructor([])}"fantasy-land/empty"(){return this.empty()}concat(s){return new this.constructor(this.content.concat(s.content))}"fantasy-land/concat"(s){return this.concat(s)}"fantasy-land/map"(s){return new this.constructor(this.map(s))}"fantasy-land/chain"(s){return this.map((o=>s(o)),this).reduce(((s,o)=>s.concat(o)),this.empty())}"fantasy-land/filter"(s){return new this.constructor(this.content.filter(s))}"fantasy-land/reduce"(s,o){return this.content.reduce(s,o)}get length(){return this.content.length}get isEmpty(){return 0===this.content.length}get first(){return this.getIndex(0)}get second(){return this.getIndex(1)}get last(){return this.getIndex(this.length-1)}}ArrayElement.empty=function empty(){return new this},ArrayElement["fantasy-land/empty"]=ArrayElement.empty,"undefined"!=typeof Symbol&&(ArrayElement.prototype[Symbol.iterator]=function symbol(){return this.content[Symbol.iterator]()}),s.exports=ArrayElement},6499:(s,o,i)=>{"use strict";var a=i(1907),u=0,_=Math.random(),w=a(1..toString);s.exports=function(s){return"Symbol("+(void 0===s?"":s)+")_"+w(++u+_,36)}},6925:s=>{"use strict";s.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},7057:(s,o,i)=>{"use strict";var a=i(11470).charAt,u=i(90160),_=i(64932),w=i(60183),x=i(59550),C="String Iterator",j=_.set,L=_.getterFor(C);w(String,"String",(function(s){j(this,{type:C,string:u(s),index:0})}),(function next(){var s,o=L(this),i=o.string,u=o.index;return u>=i.length?x(void 0,!0):(s=a(i,u),o.index+=s.length,x(s,!1))}))},7309:(s,o,i)=>{var a=i(62006)(i(24713));s.exports=a},7376:s=>{"use strict";s.exports=!0},7463:(s,o,i)=>{"use strict";var a=i(98828),u=i(62250),_=/#|\.prototype\./,isForced=function(s,o){var i=x[w(s)];return i===j||i!==C&&(u(o)?a(o):!!o)},w=isForced.normalize=function(s){return String(s).replace(_,".").toLowerCase()},x=isForced.data={},C=isForced.NATIVE="N",j=isForced.POLYFILL="P";s.exports=isForced},7666:(s,o,i)=>{var a=i(84851),u=i(953);function _extends(){var o;return s.exports=_extends=a?u(o=a).call(o):function(s){for(var o=1;o{const a=i(6205);o.wordBoundary=()=>({type:a.POSITION,value:"b"}),o.nonWordBoundary=()=>({type:a.POSITION,value:"B"}),o.begin=()=>({type:a.POSITION,value:"^"}),o.end=()=>({type:a.POSITION,value:"$"})},8068:s=>{"use strict";var o=(()=>{var s=Object.defineProperty,o=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,_=Object.prototype.propertyIsEnumerable,__defNormalProp=(o,i,a)=>i in o?s(o,i,{enumerable:!0,configurable:!0,writable:!0,value:a}):o[i]=a,__spreadValues=(s,o)=>{for(var i in o||(o={}))u.call(o,i)&&__defNormalProp(s,i,o[i]);if(a)for(var i of a(o))_.call(o,i)&&__defNormalProp(s,i,o[i]);return s},__publicField=(s,o,i)=>(__defNormalProp(s,"symbol"!=typeof o?o+"":o,i),i),w={};((o,i)=>{for(var a in i)s(o,a,{get:i[a],enumerable:!0})})(w,{DEFAULT_OPTIONS:()=>C,DEFAULT_UUID_LENGTH:()=>x,default:()=>B});var x=6,C={dictionary:"alphanum",shuffle:!0,debug:!1,length:x,counter:0},j=class _ShortUniqueId{constructor(s={}){__publicField(this,"counter"),__publicField(this,"debug"),__publicField(this,"dict"),__publicField(this,"version"),__publicField(this,"dictIndex",0),__publicField(this,"dictRange",[]),__publicField(this,"lowerBound",0),__publicField(this,"upperBound",0),__publicField(this,"dictLength",0),__publicField(this,"uuidLength"),__publicField(this,"_digit_first_ascii",48),__publicField(this,"_digit_last_ascii",58),__publicField(this,"_alpha_lower_first_ascii",97),__publicField(this,"_alpha_lower_last_ascii",123),__publicField(this,"_hex_last_ascii",103),__publicField(this,"_alpha_upper_first_ascii",65),__publicField(this,"_alpha_upper_last_ascii",91),__publicField(this,"_number_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii]}),__publicField(this,"_alpha_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]}),__publicField(this,"_alpha_lower_dict_ranges",{lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]}),__publicField(this,"_alpha_upper_dict_ranges",{upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]}),__publicField(this,"_alphanum_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]}),__publicField(this,"_alphanum_lower_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]}),__publicField(this,"_alphanum_upper_dict_ranges",{digits:[this._digit_first_ascii,this._digit_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]}),__publicField(this,"_hex_dict_ranges",{decDigits:[this._digit_first_ascii,this._digit_last_ascii],alphaDigits:[this._alpha_lower_first_ascii,this._hex_last_ascii]}),__publicField(this,"_dict_ranges",{_number_dict_ranges:this._number_dict_ranges,_alpha_dict_ranges:this._alpha_dict_ranges,_alpha_lower_dict_ranges:this._alpha_lower_dict_ranges,_alpha_upper_dict_ranges:this._alpha_upper_dict_ranges,_alphanum_dict_ranges:this._alphanum_dict_ranges,_alphanum_lower_dict_ranges:this._alphanum_lower_dict_ranges,_alphanum_upper_dict_ranges:this._alphanum_upper_dict_ranges,_hex_dict_ranges:this._hex_dict_ranges}),__publicField(this,"log",((...s)=>{const o=[...s];if(o[0]=`[short-unique-id] ${s[0]}`,!0===this.debug&&"undefined"!=typeof console&&null!==console)return console.log(...o)})),__publicField(this,"_normalizeDictionary",((s,o)=>{let i;if(s&&Array.isArray(s)&&s.length>1)i=s;else{let o;i=[],this.dictIndex=o=0;const a=`_${s}_dict_ranges`,u=this._dict_ranges[a];Object.keys(u).forEach((s=>{const a=s;for(this.dictRange=u[a],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=o=this.lowerBound;this.lowerBound<=this.upperBound?othis.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?o+=1:o-=1)i.push(String.fromCharCode(this.dictIndex))}))}if(o){const s=.5;i=i.sort((()=>Math.random()-s))}return i})),__publicField(this,"setDictionary",((s,o)=>{this.dict=this._normalizeDictionary(s,o),this.dictLength=this.dict.length,this.setCounter(0)})),__publicField(this,"seq",(()=>this.sequentialUUID())),__publicField(this,"sequentialUUID",(()=>{let s,o,i="";s=this.counter;do{o=s%this.dictLength,s=Math.trunc(s/this.dictLength),i+=this.dict[o]}while(0!==s);return this.counter+=1,i})),__publicField(this,"rnd",((s=this.uuidLength||x)=>this.randomUUID(s))),__publicField(this,"randomUUID",((s=this.uuidLength||x)=>{let o,i,a;if(null==s||s<1)throw new Error("Invalid UUID Length Provided");for(o="",a=0;athis.formattedUUID(s,o))),__publicField(this,"formattedUUID",((s,o)=>{const i={$r:this.randomUUID,$s:this.sequentialUUID,$t:this.stamp};return s.replace(/\$[rs]\d{0,}|\$t0|\$t[1-9]\d{1,}/g,(s=>{const a=s.slice(0,2),u=parseInt(s.slice(2),10);return"$s"===a?i[a]().padStart(u,"0"):"$t"===a&&o?i[a](u,o):i[a](u)}))})),__publicField(this,"availableUUIDs",((s=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,s).toFixed(0)))),__publicField(this,"approxMaxBeforeCollision",((s=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*s).toFixed(20)))),__publicField(this,"collisionProbability",((s=this.availableUUIDs(this.uuidLength),o=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(s)/this.availableUUIDs(o)).toFixed(20)))),__publicField(this,"uniqueness",((s=this.availableUUIDs(this.uuidLength))=>{const o=parseFloat((1-this.approxMaxBeforeCollision(s)/s).toFixed(20));return o>1?1:o<0?0:o})),__publicField(this,"getVersion",(()=>this.version)),__publicField(this,"stamp",((s,o)=>{const i=Math.floor(+(o||new Date)/1e3).toString(16);if("number"==typeof s&&0===s)return i;if("number"!=typeof s||s<10)throw new Error(["Param finalLength must be a number greater than or equal to 10,","or 0 if you want the raw hexadecimal timestamp"].join("\n"));const a=s-9,u=Math.round(Math.random()*(a>15?15:a)),_=this.randomUUID(a);return`${_.substring(0,u)}${i}${_.substring(u)}${u.toString(16)}`})),__publicField(this,"parseStamp",((s,o)=>{if(o&&!/t0|t[1-9]\d{1,}/.test(o))throw new Error("Cannot extract date from a formated UUID with no timestamp in the format");const i=o?o.replace(/\$[rs]\d{0,}|\$t0|\$t[1-9]\d{1,}/g,(s=>{const o={$r:s=>[...Array(s)].map((()=>"r")).join(""),$s:s=>[...Array(s)].map((()=>"s")).join(""),$t:s=>[...Array(s)].map((()=>"t")).join("")},i=s.slice(0,2),a=parseInt(s.slice(2),10);return o[i](a)})).replace(/^(.*?)(t{8,})(.*)$/g,((o,i,a)=>s.substring(i.length,i.length+a.length))):s;if(8===i.length)return new Date(1e3*parseInt(i,16));if(i.length<10)throw new Error("Stamp length invalid");const a=parseInt(i.substring(i.length-1),16);return new Date(1e3*parseInt(i.substring(a,a+8),16))})),__publicField(this,"setCounter",(s=>{this.counter=s})),__publicField(this,"validate",((s,o)=>{const i=o?this._normalizeDictionary(o):this.dict;return s.split("").every((s=>i.includes(s)))}));const o=__spreadValues(__spreadValues({},C),s);this.counter=0,this.debug=!1,this.dict=[],this.version="5.2.0";const{dictionary:i,shuffle:a,length:u,counter:_}=o;return this.uuidLength=u,this.setDictionary(i,a),this.setCounter(_),this.debug=o.debug,this.log(this.dict),this.log(`Generator instantiated with Dictionary Size ${this.dictLength} and counter set to ${this.counter}`),this.log=this.log.bind(this),this.setDictionary=this.setDictionary.bind(this),this.setCounter=this.setCounter.bind(this),this.seq=this.seq.bind(this),this.sequentialUUID=this.sequentialUUID.bind(this),this.rnd=this.rnd.bind(this),this.randomUUID=this.randomUUID.bind(this),this.fmt=this.fmt.bind(this),this.formattedUUID=this.formattedUUID.bind(this),this.availableUUIDs=this.availableUUIDs.bind(this),this.approxMaxBeforeCollision=this.approxMaxBeforeCollision.bind(this),this.collisionProbability=this.collisionProbability.bind(this),this.uniqueness=this.uniqueness.bind(this),this.getVersion=this.getVersion.bind(this),this.stamp=this.stamp.bind(this),this.parseStamp=this.parseStamp.bind(this),this}};__publicField(j,"default",j);var L,B=j;return L=w,((a,_,w,x)=>{if(_&&"object"==typeof _||"function"==typeof _)for(let C of i(_))u.call(a,C)||C===w||s(a,C,{get:()=>_[C],enumerable:!(x=o(_,C))||x.enumerable});return a})(s({},"__esModule",{value:!0}),L)})();s.exports=o.default,"undefined"!=typeof window&&(o=o.default)},9325:(s,o,i)=>{var a=i(34840),u="object"==typeof self&&self&&self.Object===Object&&self,_=a||u||Function("return this")();s.exports=_},9404:function(s){s.exports=function(){"use strict";var s=Array.prototype.slice;function createClass(s,o){o&&(s.prototype=Object.create(o.prototype)),s.prototype.constructor=s}function Iterable(s){return isIterable(s)?s:Seq(s)}function KeyedIterable(s){return isKeyed(s)?s:KeyedSeq(s)}function IndexedIterable(s){return isIndexed(s)?s:IndexedSeq(s)}function SetIterable(s){return isIterable(s)&&!isAssociative(s)?s:SetSeq(s)}function isIterable(s){return!(!s||!s[o])}function isKeyed(s){return!(!s||!s[i])}function isIndexed(s){return!(!s||!s[a])}function isAssociative(s){return isKeyed(s)||isIndexed(s)}function isOrdered(s){return!(!s||!s[u])}createClass(KeyedIterable,Iterable),createClass(IndexedIterable,Iterable),createClass(SetIterable,Iterable),Iterable.isIterable=isIterable,Iterable.isKeyed=isKeyed,Iterable.isIndexed=isIndexed,Iterable.isAssociative=isAssociative,Iterable.isOrdered=isOrdered,Iterable.Keyed=KeyedIterable,Iterable.Indexed=IndexedIterable,Iterable.Set=SetIterable;var o="@@__IMMUTABLE_ITERABLE__@@",i="@@__IMMUTABLE_KEYED__@@",a="@@__IMMUTABLE_INDEXED__@@",u="@@__IMMUTABLE_ORDERED__@@",_="delete",w=5,x=1<>>0;if(""+i!==o||4294967295===i)return NaN;o=i}return o<0?ensureSize(s)+o:o}function returnTrue(){return!0}function wholeSlice(s,o,i){return(0===s||void 0!==i&&s<=-i)&&(void 0===o||void 0!==i&&o>=i)}function resolveBegin(s,o){return resolveIndex(s,o,0)}function resolveEnd(s,o){return resolveIndex(s,o,o)}function resolveIndex(s,o,i){return void 0===s?i:s<0?Math.max(0,o+s):void 0===o?s:Math.min(o,s)}var $=0,V=1,U=2,z="function"==typeof Symbol&&Symbol.iterator,Y="@@iterator",Z=z||Y;function Iterator(s){this.next=s}function iteratorValue(s,o,i,a){var u=0===s?o:1===s?i:[o,i];return a?a.value=u:a={value:u,done:!1},a}function iteratorDone(){return{value:void 0,done:!0}}function hasIterator(s){return!!getIteratorFn(s)}function isIterator(s){return s&&"function"==typeof s.next}function getIterator(s){var o=getIteratorFn(s);return o&&o.call(s)}function getIteratorFn(s){var o=s&&(z&&s[z]||s[Y]);if("function"==typeof o)return o}function isArrayLike(s){return s&&"number"==typeof s.length}function Seq(s){return null==s?emptySequence():isIterable(s)?s.toSeq():seqFromValue(s)}function KeyedSeq(s){return null==s?emptySequence().toKeyedSeq():isIterable(s)?isKeyed(s)?s.toSeq():s.fromEntrySeq():keyedSeqFromValue(s)}function IndexedSeq(s){return null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s.toIndexedSeq():indexedSeqFromValue(s)}function SetSeq(s){return(null==s?emptySequence():isIterable(s)?isKeyed(s)?s.entrySeq():s:indexedSeqFromValue(s)).toSetSeq()}Iterator.prototype.toString=function(){return"[Iterator]"},Iterator.KEYS=$,Iterator.VALUES=V,Iterator.ENTRIES=U,Iterator.prototype.inspect=Iterator.prototype.toSource=function(){return this.toString()},Iterator.prototype[Z]=function(){return this},createClass(Seq,Iterable),Seq.of=function(){return Seq(arguments)},Seq.prototype.toSeq=function(){return this},Seq.prototype.toString=function(){return this.__toString("Seq {","}")},Seq.prototype.cacheResult=function(){return!this._cache&&this.__iterateUncached&&(this._cache=this.entrySeq().toArray(),this.size=this._cache.length),this},Seq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!0)},Seq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!0)},createClass(KeyedSeq,Seq),KeyedSeq.prototype.toKeyedSeq=function(){return this},createClass(IndexedSeq,Seq),IndexedSeq.of=function(){return IndexedSeq(arguments)},IndexedSeq.prototype.toIndexedSeq=function(){return this},IndexedSeq.prototype.toString=function(){return this.__toString("Seq [","]")},IndexedSeq.prototype.__iterate=function(s,o){return seqIterate(this,s,o,!1)},IndexedSeq.prototype.__iterator=function(s,o){return seqIterator(this,s,o,!1)},createClass(SetSeq,Seq),SetSeq.of=function(){return SetSeq(arguments)},SetSeq.prototype.toSetSeq=function(){return this},Seq.isSeq=isSeq,Seq.Keyed=KeyedSeq,Seq.Set=SetSeq,Seq.Indexed=IndexedSeq;var ee,ie,ae,ce="@@__IMMUTABLE_SEQ__@@";function ArraySeq(s){this._array=s,this.size=s.length}function ObjectSeq(s){var o=Object.keys(s);this._object=s,this._keys=o,this.size=o.length}function IterableSeq(s){this._iterable=s,this.size=s.length||s.size}function IteratorSeq(s){this._iterator=s,this._iteratorCache=[]}function isSeq(s){return!(!s||!s[ce])}function emptySequence(){return ee||(ee=new ArraySeq([]))}function keyedSeqFromValue(s){var o=Array.isArray(s)?new ArraySeq(s).fromEntrySeq():isIterator(s)?new IteratorSeq(s).fromEntrySeq():hasIterator(s)?new IterableSeq(s).fromEntrySeq():"object"==typeof s?new ObjectSeq(s):void 0;if(!o)throw new TypeError("Expected Array or iterable object of [k, v] entries, or keyed object: "+s);return o}function indexedSeqFromValue(s){var o=maybeIndexedSeqFromValue(s);if(!o)throw new TypeError("Expected Array or iterable object of values: "+s);return o}function seqFromValue(s){var o=maybeIndexedSeqFromValue(s)||"object"==typeof s&&new ObjectSeq(s);if(!o)throw new TypeError("Expected Array or iterable object of values, or keyed object: "+s);return o}function maybeIndexedSeqFromValue(s){return isArrayLike(s)?new ArraySeq(s):isIterator(s)?new IteratorSeq(s):hasIterator(s)?new IterableSeq(s):void 0}function seqIterate(s,o,i,a){var u=s._cache;if(u){for(var _=u.length-1,w=0;w<=_;w++){var x=u[i?_-w:w];if(!1===o(x[1],a?x[0]:w,s))return w+1}return w}return s.__iterateUncached(o,i)}function seqIterator(s,o,i,a){var u=s._cache;if(u){var _=u.length-1,w=0;return new Iterator((function(){var s=u[i?_-w:w];return w++>_?iteratorDone():iteratorValue(o,a?s[0]:w-1,s[1])}))}return s.__iteratorUncached(o,i)}function fromJS(s,o){return o?fromJSWith(o,s,"",{"":s}):fromJSDefault(s)}function fromJSWith(s,o,i,a){return Array.isArray(o)?s.call(a,i,IndexedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):isPlainObj(o)?s.call(a,i,KeyedSeq(o).map((function(i,a){return fromJSWith(s,i,a,o)}))):o}function fromJSDefault(s){return Array.isArray(s)?IndexedSeq(s).map(fromJSDefault).toList():isPlainObj(s)?KeyedSeq(s).map(fromJSDefault).toMap():s}function isPlainObj(s){return s&&(s.constructor===Object||void 0===s.constructor)}function is(s,o){if(s===o||s!=s&&o!=o)return!0;if(!s||!o)return!1;if("function"==typeof s.valueOf&&"function"==typeof o.valueOf){if((s=s.valueOf())===(o=o.valueOf())||s!=s&&o!=o)return!0;if(!s||!o)return!1}return!("function"!=typeof s.equals||"function"!=typeof o.equals||!s.equals(o))}function deepEqual(s,o){if(s===o)return!0;if(!isIterable(o)||void 0!==s.size&&void 0!==o.size&&s.size!==o.size||void 0!==s.__hash&&void 0!==o.__hash&&s.__hash!==o.__hash||isKeyed(s)!==isKeyed(o)||isIndexed(s)!==isIndexed(o)||isOrdered(s)!==isOrdered(o))return!1;if(0===s.size&&0===o.size)return!0;var i=!isAssociative(s);if(isOrdered(s)){var a=s.entries();return o.every((function(s,o){var u=a.next().value;return u&&is(u[1],s)&&(i||is(u[0],o))}))&&a.next().done}var u=!1;if(void 0===s.size)if(void 0===o.size)"function"==typeof s.cacheResult&&s.cacheResult();else{u=!0;var _=s;s=o,o=_}var w=!0,x=o.__iterate((function(o,a){if(i?!s.has(o):u?!is(o,s.get(a,j)):!is(s.get(a,j),o))return w=!1,!1}));return w&&s.size===x}function Repeat(s,o){if(!(this instanceof Repeat))return new Repeat(s,o);if(this._value=s,this.size=void 0===o?1/0:Math.max(0,o),0===this.size){if(ie)return ie;ie=this}}function invariant(s,o){if(!s)throw new Error(o)}function Range(s,o,i){if(!(this instanceof Range))return new Range(s,o,i);if(invariant(0!==i,"Cannot step a Range by 0"),s=s||0,void 0===o&&(o=1/0),i=void 0===i?1:Math.abs(i),oa?iteratorDone():iteratorValue(s,u,i[o?a-u++:u++])}))},createClass(ObjectSeq,KeyedSeq),ObjectSeq.prototype.get=function(s,o){return void 0===o||this.has(s)?this._object[s]:o},ObjectSeq.prototype.has=function(s){return this._object.hasOwnProperty(s)},ObjectSeq.prototype.__iterate=function(s,o){for(var i=this._object,a=this._keys,u=a.length-1,_=0;_<=u;_++){var w=a[o?u-_:_];if(!1===s(i[w],w,this))return _+1}return _},ObjectSeq.prototype.__iterator=function(s,o){var i=this._object,a=this._keys,u=a.length-1,_=0;return new Iterator((function(){var w=a[o?u-_:_];return _++>u?iteratorDone():iteratorValue(s,w,i[w])}))},ObjectSeq.prototype[u]=!0,createClass(IterableSeq,IndexedSeq),IterableSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);var i=getIterator(this._iterable),a=0;if(isIterator(i))for(var u;!(u=i.next()).done&&!1!==s(u.value,a++,this););return a},IterableSeq.prototype.__iteratorUncached=function(s,o){if(o)return this.cacheResult().__iterator(s,o);var i=getIterator(this._iterable);if(!isIterator(i))return new Iterator(iteratorDone);var a=0;return new Iterator((function(){var o=i.next();return o.done?o:iteratorValue(s,a++,o.value)}))},createClass(IteratorSeq,IndexedSeq),IteratorSeq.prototype.__iterateUncached=function(s,o){if(o)return this.cacheResult().__iterate(s,o);for(var i,a=this._iterator,u=this._iteratorCache,_=0;_=a.length){var o=i.next();if(o.done)return o;a[u]=o.value}return iteratorValue(s,u,a[u++])}))},createClass(Repeat,IndexedSeq),Repeat.prototype.toString=function(){return 0===this.size?"Repeat []":"Repeat [ "+this._value+" "+this.size+" times ]"},Repeat.prototype.get=function(s,o){return this.has(s)?this._value:o},Repeat.prototype.includes=function(s){return is(this._value,s)},Repeat.prototype.slice=function(s,o){var i=this.size;return wholeSlice(s,o,i)?this:new Repeat(this._value,resolveEnd(o,i)-resolveBegin(s,i))},Repeat.prototype.reverse=function(){return this},Repeat.prototype.indexOf=function(s){return is(this._value,s)?0:-1},Repeat.prototype.lastIndexOf=function(s){return is(this._value,s)?this.size:-1},Repeat.prototype.__iterate=function(s,o){for(var i=0;i=0&&o=0&&ii?iteratorDone():iteratorValue(s,_++,w)}))},Range.prototype.equals=function(s){return s instanceof Range?this._start===s._start&&this._end===s._end&&this._step===s._step:deepEqual(this,s)},createClass(Collection,Iterable),createClass(KeyedCollection,Collection),createClass(IndexedCollection,Collection),createClass(SetCollection,Collection),Collection.Keyed=KeyedCollection,Collection.Indexed=IndexedCollection,Collection.Set=SetCollection;var le="function"==typeof Math.imul&&-2===Math.imul(4294967295,2)?Math.imul:function imul(s,o){var i=65535&(s|=0),a=65535&(o|=0);return i*a+((s>>>16)*a+i*(o>>>16)<<16>>>0)|0};function smi(s){return s>>>1&1073741824|3221225471&s}function hash(s){if(!1===s||null==s)return 0;if("function"==typeof s.valueOf&&(!1===(s=s.valueOf())||null==s))return 0;if(!0===s)return 1;var o=typeof s;if("number"===o){if(s!=s||s===1/0)return 0;var i=0|s;for(i!==s&&(i^=4294967295*s);s>4294967295;)i^=s/=4294967295;return smi(i)}if("string"===o)return s.length>Se?cachedHashString(s):hashString(s);if("function"==typeof s.hashCode)return s.hashCode();if("object"===o)return hashJSObj(s);if("function"==typeof s.toString)return hashString(s.toString());throw new Error("Value type "+o+" cannot be hashed.")}function cachedHashString(s){var o=Pe[s];return void 0===o&&(o=hashString(s),xe===we&&(xe=0,Pe={}),xe++,Pe[s]=o),o}function hashString(s){for(var o=0,i=0;i0)switch(s.nodeType){case 1:return s.uniqueID;case 9:return s.documentElement&&s.documentElement.uniqueID}}var fe,ye="function"==typeof WeakMap;ye&&(fe=new WeakMap);var be=0,_e="__immutablehash__";"function"==typeof Symbol&&(_e=Symbol(_e));var Se=16,we=255,xe=0,Pe={};function assertNotInfinite(s){invariant(s!==1/0,"Cannot perform this action with an infinite size.")}function Map(s){return null==s?emptyMap():isMap(s)&&!isOrdered(s)?s:emptyMap().withMutations((function(o){var i=KeyedIterable(s);assertNotInfinite(i.size),i.forEach((function(s,i){return o.set(i,s)}))}))}function isMap(s){return!(!s||!s[Re])}createClass(Map,KeyedCollection),Map.of=function(){var o=s.call(arguments,0);return emptyMap().withMutations((function(s){for(var i=0;i=o.length)throw new Error("Missing value for key: "+o[i]);s.set(o[i],o[i+1])}}))},Map.prototype.toString=function(){return this.__toString("Map {","}")},Map.prototype.get=function(s,o){return this._root?this._root.get(0,void 0,s,o):o},Map.prototype.set=function(s,o){return updateMap(this,s,o)},Map.prototype.setIn=function(s,o){return this.updateIn(s,j,(function(){return o}))},Map.prototype.remove=function(s){return updateMap(this,s,j)},Map.prototype.deleteIn=function(s){return this.updateIn(s,(function(){return j}))},Map.prototype.update=function(s,o,i){return 1===arguments.length?s(this):this.updateIn([s],o,i)},Map.prototype.updateIn=function(s,o,i){i||(i=o,o=void 0);var a=updateInDeepMap(this,forceIterator(s),o,i);return a===j?void 0:a},Map.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._root=null,this.__hash=void 0,this.__altered=!0,this):emptyMap()},Map.prototype.merge=function(){return mergeIntoMapWith(this,void 0,arguments)},Map.prototype.mergeWith=function(o){return mergeIntoMapWith(this,o,s.call(arguments,1))},Map.prototype.mergeIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.merge?s.merge.apply(s,i):i[i.length-1]}))},Map.prototype.mergeDeep=function(){return mergeIntoMapWith(this,deepMerger,arguments)},Map.prototype.mergeDeepWith=function(o){var i=s.call(arguments,1);return mergeIntoMapWith(this,deepMergerWith(o),i)},Map.prototype.mergeDeepIn=function(o){var i=s.call(arguments,1);return this.updateIn(o,emptyMap(),(function(s){return"function"==typeof s.mergeDeep?s.mergeDeep.apply(s,i):i[i.length-1]}))},Map.prototype.sort=function(s){return OrderedMap(sortFactory(this,s))},Map.prototype.sortBy=function(s,o){return OrderedMap(sortFactory(this,o,s))},Map.prototype.withMutations=function(s){var o=this.asMutable();return s(o),o.wasAltered()?o.__ensureOwner(this.__ownerID):this},Map.prototype.asMutable=function(){return this.__ownerID?this:this.__ensureOwner(new OwnerID)},Map.prototype.asImmutable=function(){return this.__ensureOwner()},Map.prototype.wasAltered=function(){return this.__altered},Map.prototype.__iterator=function(s,o){return new MapIterator(this,s,o)},Map.prototype.__iterate=function(s,o){var i=this,a=0;return this._root&&this._root.iterate((function(o){return a++,s(o[1],o[0],i)}),o),a},Map.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeMap(this.size,this._root,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Map.isMap=isMap;var Te,Re="@@__IMMUTABLE_MAP__@@",qe=Map.prototype;function ArrayMapNode(s,o){this.ownerID=s,this.entries=o}function BitmapIndexedNode(s,o,i){this.ownerID=s,this.bitmap=o,this.nodes=i}function HashArrayMapNode(s,o,i){this.ownerID=s,this.count=o,this.nodes=i}function HashCollisionNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entries=i}function ValueNode(s,o,i){this.ownerID=s,this.keyHash=o,this.entry=i}function MapIterator(s,o,i){this._type=o,this._reverse=i,this._stack=s._root&&mapIteratorFrame(s._root)}function mapIteratorValue(s,o){return iteratorValue(s,o[0],o[1])}function mapIteratorFrame(s,o){return{node:s,index:0,__prev:o}}function makeMap(s,o,i,a){var u=Object.create(qe);return u.size=s,u._root=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyMap(){return Te||(Te=makeMap(0))}function updateMap(s,o,i){var a,u;if(s._root){var _=MakeRef(L),w=MakeRef(B);if(a=updateNode(s._root,s.__ownerID,0,void 0,o,i,_,w),!w.value)return s;u=s.size+(_.value?i===j?-1:1:0)}else{if(i===j)return s;u=1,a=new ArrayMapNode(s.__ownerID,[[o,i]])}return s.__ownerID?(s.size=u,s._root=a,s.__hash=void 0,s.__altered=!0,s):a?makeMap(u,a):emptyMap()}function updateNode(s,o,i,a,u,_,w,x){return s?s.update(o,i,a,u,_,w,x):_===j?s:(SetRef(x),SetRef(w),new ValueNode(o,a,[u,_]))}function isLeafNode(s){return s.constructor===ValueNode||s.constructor===HashCollisionNode}function mergeIntoNode(s,o,i,a,u){if(s.keyHash===a)return new HashCollisionNode(o,a,[s.entry,u]);var _,x=(0===i?s.keyHash:s.keyHash>>>i)&C,j=(0===i?a:a>>>i)&C;return new BitmapIndexedNode(o,1<>>=1)w[C]=1&i?o[_++]:void 0;return w[a]=u,new HashArrayMapNode(s,_+1,w)}function mergeIntoMapWith(s,o,i){for(var a=[],u=0;u>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135,s+=s>>8,127&(s+=s>>16)}function setIn(s,o,i,a){var u=a?s:arrCopy(s);return u[o]=i,u}function spliceIn(s,o,i,a){var u=s.length+1;if(a&&o+1===u)return s[o]=i,s;for(var _=new Array(u),w=0,x=0;x=$e)return createNodes(s,C,a,u);var V=s&&s===this.ownerID,U=V?C:arrCopy(C);return $?x?L===B-1?U.pop():U[L]=U.pop():U[L]=[a,u]:U.push([a,u]),V?(this.entries=U,this):new ArrayMapNode(s,U)}},BitmapIndexedNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=1<<((0===s?o:o>>>s)&C),_=this.bitmap;return _&u?this.nodes[popCount(_&u-1)].get(s+w,o,i,a):a},BitmapIndexedNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=1<=ze)return expandNodes(s,z,$,L,Z);if(V&&!Z&&2===z.length&&isLeafNode(z[1^U]))return z[1^U];if(V&&Z&&1===z.length&&isLeafNode(Z))return Z;var ee=s&&s===this.ownerID,ie=V?Z?$:$^B:$|B,ae=V?Z?setIn(z,U,Z,ee):spliceOut(z,U,ee):spliceIn(z,U,Z,ee);return ee?(this.bitmap=ie,this.nodes=ae,this):new BitmapIndexedNode(s,ie,ae)},HashArrayMapNode.prototype.get=function(s,o,i,a){void 0===o&&(o=hash(i));var u=(0===s?o:o>>>s)&C,_=this.nodes[u];return _?_.get(s+w,o,i,a):a},HashArrayMapNode.prototype.update=function(s,o,i,a,u,_,x){void 0===i&&(i=hash(a));var L=(0===o?i:i>>>o)&C,B=u===j,$=this.nodes,V=$[L];if(B&&!V)return this;var U=updateNode(V,s,o+w,i,a,u,_,x);if(U===V)return this;var z=this.count;if(V){if(!U&&--z0&&a=0&&s>>o&C;if(a>=this.array.length)return new VNode([],s);var u,_=0===a;if(o>0){var x=this.array[a];if((u=x&&x.removeBefore(s,o-w,i))===x&&_)return this}if(_&&!u)return this;var j=editableVNode(this,s);if(!_)for(var L=0;L>>o&C;if(u>=this.array.length)return this;if(o>0){var _=this.array[u];if((a=_&&_.removeAfter(s,o-w,i))===_&&u===this.array.length-1)return this}var x=editableVNode(this,s);return x.array.splice(u+1),a&&(x.array[u]=a),x};var Ye,Qe,et={};function iterateList(s,o){var i=s._origin,a=s._capacity,u=getTailOffset(a),_=s._tail;return iterateNodeOrLeaf(s._root,s._level,0);function iterateNodeOrLeaf(s,o,i){return 0===o?iterateLeaf(s,i):iterateNode(s,o,i)}function iterateLeaf(s,w){var C=w===u?_&&_.array:s&&s.array,j=w>i?0:i-w,L=a-w;return L>x&&(L=x),function(){if(j===L)return et;var s=o?--L:j++;return C&&C[s]}}function iterateNode(s,u,_){var C,j=s&&s.array,L=_>i?0:i-_>>u,B=1+(a-_>>u);return B>x&&(B=x),function(){for(;;){if(C){var s=C();if(s!==et)return s;C=null}if(L===B)return et;var i=o?--B:L++;C=iterateNodeOrLeaf(j&&j[i],u-w,_+(i<=s.size||o<0)return s.withMutations((function(s){o<0?setListBounds(s,o).set(0,i):setListBounds(s,0,o+1).set(o,i)}));o+=s._origin;var a=s._tail,u=s._root,_=MakeRef(B);return o>=getTailOffset(s._capacity)?a=updateVNode(a,s.__ownerID,0,o,i,_):u=updateVNode(u,s.__ownerID,s._level,o,i,_),_.value?s.__ownerID?(s._root=u,s._tail=a,s.__hash=void 0,s.__altered=!0,s):makeList(s._origin,s._capacity,s._level,u,a):s}function updateVNode(s,o,i,a,u,_){var x,j=a>>>i&C,L=s&&j0){var B=s&&s.array[j],$=updateVNode(B,o,i-w,a,u,_);return $===B?s:((x=editableVNode(s,o)).array[j]=$,x)}return L&&s.array[j]===u?s:(SetRef(_),x=editableVNode(s,o),void 0===u&&j===x.array.length-1?x.array.pop():x.array[j]=u,x)}function editableVNode(s,o){return o&&s&&o===s.ownerID?s:new VNode(s?s.array.slice():[],o)}function listNodeFor(s,o){if(o>=getTailOffset(s._capacity))return s._tail;if(o<1<0;)i=i.array[o>>>a&C],a-=w;return i}}function setListBounds(s,o,i){void 0!==o&&(o|=0),void 0!==i&&(i|=0);var a=s.__ownerID||new OwnerID,u=s._origin,_=s._capacity,x=u+o,j=void 0===i?_:i<0?_+i:u+i;if(x===u&&j===_)return s;if(x>=j)return s.clear();for(var L=s._level,B=s._root,$=0;x+$<0;)B=new VNode(B&&B.array.length?[void 0,B]:[],a),$+=1<<(L+=w);$&&(x+=$,u+=$,j+=$,_+=$);for(var V=getTailOffset(_),U=getTailOffset(j);U>=1<V?new VNode([],a):z;if(z&&U>V&&x<_&&z.array.length){for(var Z=B=editableVNode(B,a),ee=L;ee>w;ee-=w){var ie=V>>>ee&C;Z=Z.array[ie]=editableVNode(Z.array[ie],a)}Z.array[V>>>w&C]=z}if(j<_&&(Y=Y&&Y.removeAfter(a,0,j)),x>=U)x-=U,j-=U,L=w,B=null,Y=Y&&Y.removeBefore(a,0,x);else if(x>u||U>>L&C;if(ae!==U>>>L&C)break;ae&&($+=(1<u&&(B=B.removeBefore(a,L,x-$)),B&&Uu&&(u=x.size),isIterable(w)||(x=x.map((function(s){return fromJS(s)}))),a.push(x)}return u>s.size&&(s=s.setSize(u)),mergeIntoCollectionWith(s,o,a)}function getTailOffset(s){return s>>w<=x&&w.size>=2*_.size?(a=(u=w.filter((function(s,o){return void 0!==s&&C!==o}))).toKeyedSeq().map((function(s){return s[0]})).flip().toMap(),s.__ownerID&&(a.__ownerID=u.__ownerID=s.__ownerID)):(a=_.remove(o),u=C===w.size-1?w.pop():w.set(C,void 0))}else if(L){if(i===w.get(C)[1])return s;a=_,u=w.set(C,[o,i])}else a=_.set(o,w.size),u=w.set(w.size,[o,i]);return s.__ownerID?(s.size=a.size,s._map=a,s._list=u,s.__hash=void 0,s):makeOrderedMap(a,u)}function ToKeyedSequence(s,o){this._iter=s,this._useKeys=o,this.size=s.size}function ToIndexedSequence(s){this._iter=s,this.size=s.size}function ToSetSequence(s){this._iter=s,this.size=s.size}function FromEntriesSequence(s){this._iter=s,this.size=s.size}function flipFactory(s){var o=makeSequence(s);return o._iter=s,o.size=s.size,o.flip=function(){return s},o.reverse=function(){var o=s.reverse.apply(this);return o.flip=function(){return s.reverse()},o},o.has=function(o){return s.includes(o)},o.includes=function(o){return s.has(o)},o.cacheResult=cacheResultThrough,o.__iterateUncached=function(o,i){var a=this;return s.__iterate((function(s,i){return!1!==o(i,s,a)}),i)},o.__iteratorUncached=function(o,i){if(o===U){var a=s.__iterator(o,i);return new Iterator((function(){var s=a.next();if(!s.done){var o=s.value[0];s.value[0]=s.value[1],s.value[1]=o}return s}))}return s.__iterator(o===V?$:V,i)},o}function mapFactory(s,o,i){var a=makeSequence(s);return a.size=s.size,a.has=function(o){return s.has(o)},a.get=function(a,u){var _=s.get(a,j);return _===j?u:o.call(i,_,a,s)},a.__iterateUncached=function(a,u){var _=this;return s.__iterate((function(s,u,w){return!1!==a(o.call(i,s,u,w),u,_)}),u)},a.__iteratorUncached=function(a,u){var _=s.__iterator(U,u);return new Iterator((function(){var u=_.next();if(u.done)return u;var w=u.value,x=w[0];return iteratorValue(a,x,o.call(i,w[1],x,s),u)}))},a}function reverseFactory(s,o){var i=makeSequence(s);return i._iter=s,i.size=s.size,i.reverse=function(){return s},s.flip&&(i.flip=function(){var o=flipFactory(s);return o.reverse=function(){return s.flip()},o}),i.get=function(i,a){return s.get(o?i:-1-i,a)},i.has=function(i){return s.has(o?i:-1-i)},i.includes=function(o){return s.includes(o)},i.cacheResult=cacheResultThrough,i.__iterate=function(o,i){var a=this;return s.__iterate((function(s,i){return o(s,i,a)}),!i)},i.__iterator=function(o,i){return s.__iterator(o,!i)},i}function filterFactory(s,o,i,a){var u=makeSequence(s);return a&&(u.has=function(a){var u=s.get(a,j);return u!==j&&!!o.call(i,u,a,s)},u.get=function(a,u){var _=s.get(a,j);return _!==j&&o.call(i,_,a,s)?_:u}),u.__iterateUncached=function(u,_){var w=this,x=0;return s.__iterate((function(s,_,C){if(o.call(i,s,_,C))return x++,u(s,a?_:x-1,w)}),_),x},u.__iteratorUncached=function(u,_){var w=s.__iterator(U,_),x=0;return new Iterator((function(){for(;;){var _=w.next();if(_.done)return _;var C=_.value,j=C[0],L=C[1];if(o.call(i,L,j,s))return iteratorValue(u,a?j:x++,L,_)}}))},u}function countByFactory(s,o,i){var a=Map().asMutable();return s.__iterate((function(u,_){a.update(o.call(i,u,_,s),0,(function(s){return s+1}))})),a.asImmutable()}function groupByFactory(s,o,i){var a=isKeyed(s),u=(isOrdered(s)?OrderedMap():Map()).asMutable();s.__iterate((function(_,w){u.update(o.call(i,_,w,s),(function(s){return(s=s||[]).push(a?[w,_]:_),s}))}));var _=iterableClass(s);return u.map((function(o){return reify(s,_(o))}))}function sliceFactory(s,o,i,a){var u=s.size;if(void 0!==o&&(o|=0),void 0!==i&&(i===1/0?i=u:i|=0),wholeSlice(o,i,u))return s;var _=resolveBegin(o,u),w=resolveEnd(i,u);if(_!=_||w!=w)return sliceFactory(s.toSeq().cacheResult(),o,i,a);var x,C=w-_;C==C&&(x=C<0?0:C);var j=makeSequence(s);return j.size=0===x?x:s.size&&x||void 0,!a&&isSeq(s)&&x>=0&&(j.get=function(o,i){return(o=wrapIndex(this,o))>=0&&ox)return iteratorDone();var s=u.next();return a||o===V?s:iteratorValue(o,C-1,o===$?void 0:s.value[1],s)}))},j}function takeWhileFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterate(a,u);var w=0;return s.__iterate((function(s,u,x){return o.call(i,s,u,x)&&++w&&a(s,u,_)})),w},a.__iteratorUncached=function(a,u){var _=this;if(u)return this.cacheResult().__iterator(a,u);var w=s.__iterator(U,u),x=!0;return new Iterator((function(){if(!x)return iteratorDone();var s=w.next();if(s.done)return s;var u=s.value,C=u[0],j=u[1];return o.call(i,j,C,_)?a===U?s:iteratorValue(a,C,j,s):(x=!1,iteratorDone())}))},a}function skipWhileFactory(s,o,i,a){var u=makeSequence(s);return u.__iterateUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterate(u,_);var x=!0,C=0;return s.__iterate((function(s,_,j){if(!x||!(x=o.call(i,s,_,j)))return C++,u(s,a?_:C-1,w)})),C},u.__iteratorUncached=function(u,_){var w=this;if(_)return this.cacheResult().__iterator(u,_);var x=s.__iterator(U,_),C=!0,j=0;return new Iterator((function(){var s,_,L;do{if((s=x.next()).done)return a||u===V?s:iteratorValue(u,j++,u===$?void 0:s.value[1],s);var B=s.value;_=B[0],L=B[1],C&&(C=o.call(i,L,_,w))}while(C);return u===U?s:iteratorValue(u,_,L,s)}))},u}function concatFactory(s,o){var i=isKeyed(s),a=[s].concat(o).map((function(s){return isIterable(s)?i&&(s=KeyedIterable(s)):s=i?keyedSeqFromValue(s):indexedSeqFromValue(Array.isArray(s)?s:[s]),s})).filter((function(s){return 0!==s.size}));if(0===a.length)return s;if(1===a.length){var u=a[0];if(u===s||i&&isKeyed(u)||isIndexed(s)&&isIndexed(u))return u}var _=new ArraySeq(a);return i?_=_.toKeyedSeq():isIndexed(s)||(_=_.toSetSeq()),(_=_.flatten(!0)).size=a.reduce((function(s,o){if(void 0!==s){var i=o.size;if(void 0!==i)return s+i}}),0),_}function flattenFactory(s,o,i){var a=makeSequence(s);return a.__iterateUncached=function(a,u){var _=0,w=!1;function flatDeep(s,x){var C=this;s.__iterate((function(s,u){return(!o||x0}function zipWithFactory(s,o,i){var a=makeSequence(s);return a.size=new ArraySeq(i).map((function(s){return s.size})).min(),a.__iterate=function(s,o){for(var i,a=this.__iterator(V,o),u=0;!(i=a.next()).done&&!1!==s(i.value,u++,this););return u},a.__iteratorUncached=function(s,a){var u=i.map((function(s){return s=Iterable(s),getIterator(a?s.reverse():s)})),_=0,w=!1;return new Iterator((function(){var i;return w||(i=u.map((function(s){return s.next()})),w=i.some((function(s){return s.done}))),w?iteratorDone():iteratorValue(s,_++,o.apply(null,i.map((function(s){return s.value}))))}))},a}function reify(s,o){return isSeq(s)?o:s.constructor(o)}function validateEntry(s){if(s!==Object(s))throw new TypeError("Expected [K, V] tuple: "+s)}function resolveSize(s){return assertNotInfinite(s.size),ensureSize(s)}function iterableClass(s){return isKeyed(s)?KeyedIterable:isIndexed(s)?IndexedIterable:SetIterable}function makeSequence(s){return Object.create((isKeyed(s)?KeyedSeq:isIndexed(s)?IndexedSeq:SetSeq).prototype)}function cacheResultThrough(){return this._iter.cacheResult?(this._iter.cacheResult(),this.size=this._iter.size,this):Seq.prototype.cacheResult.call(this)}function defaultComparator(s,o){return s>o?1:s=0;i--)o={value:arguments[i],next:o};return this.__ownerID?(this.size=s,this._head=o,this.__hash=void 0,this.__altered=!0,this):makeStack(s,o)},Stack.prototype.pushAll=function(s){if(0===(s=IndexedIterable(s)).size)return this;assertNotInfinite(s.size);var o=this.size,i=this._head;return s.reverse().forEach((function(s){o++,i={value:s,next:i}})),this.__ownerID?(this.size=o,this._head=i,this.__hash=void 0,this.__altered=!0,this):makeStack(o,i)},Stack.prototype.pop=function(){return this.slice(1)},Stack.prototype.unshift=function(){return this.push.apply(this,arguments)},Stack.prototype.unshiftAll=function(s){return this.pushAll(s)},Stack.prototype.shift=function(){return this.pop.apply(this,arguments)},Stack.prototype.clear=function(){return 0===this.size?this:this.__ownerID?(this.size=0,this._head=void 0,this.__hash=void 0,this.__altered=!0,this):emptyStack()},Stack.prototype.slice=function(s,o){if(wholeSlice(s,o,this.size))return this;var i=resolveBegin(s,this.size);if(resolveEnd(o,this.size)!==this.size)return IndexedCollection.prototype.slice.call(this,s,o);for(var a=this.size-i,u=this._head;i--;)u=u.next;return this.__ownerID?(this.size=a,this._head=u,this.__hash=void 0,this.__altered=!0,this):makeStack(a,u)},Stack.prototype.__ensureOwner=function(s){return s===this.__ownerID?this:s?makeStack(this.size,this._head,s,this.__hash):(this.__ownerID=s,this.__altered=!1,this)},Stack.prototype.__iterate=function(s,o){if(o)return this.reverse().__iterate(s);for(var i=0,a=this._head;a&&!1!==s(a.value,i++,this);)a=a.next;return i},Stack.prototype.__iterator=function(s,o){if(o)return this.reverse().__iterator(s);var i=0,a=this._head;return new Iterator((function(){if(a){var o=a.value;return a=a.next,iteratorValue(s,i++,o)}return iteratorDone()}))},Stack.isStack=isStack;var at,ct="@@__IMMUTABLE_STACK__@@",lt=Stack.prototype;function makeStack(s,o,i,a){var u=Object.create(lt);return u.size=s,u._head=o,u.__ownerID=i,u.__hash=a,u.__altered=!1,u}function emptyStack(){return at||(at=makeStack(0))}function mixin(s,o){var keyCopier=function(i){s.prototype[i]=o[i]};return Object.keys(o).forEach(keyCopier),Object.getOwnPropertySymbols&&Object.getOwnPropertySymbols(o).forEach(keyCopier),s}lt[ct]=!0,lt.withMutations=qe.withMutations,lt.asMutable=qe.asMutable,lt.asImmutable=qe.asImmutable,lt.wasAltered=qe.wasAltered,Iterable.Iterator=Iterator,mixin(Iterable,{toArray:function(){assertNotInfinite(this.size);var s=new Array(this.size||0);return this.valueSeq().__iterate((function(o,i){s[i]=o})),s},toIndexedSeq:function(){return new ToIndexedSequence(this)},toJS:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJS?s.toJS():s})).__toJS()},toJSON:function(){return this.toSeq().map((function(s){return s&&"function"==typeof s.toJSON?s.toJSON():s})).__toJS()},toKeyedSeq:function(){return new ToKeyedSequence(this,!0)},toMap:function(){return Map(this.toKeyedSeq())},toObject:function(){assertNotInfinite(this.size);var s={};return this.__iterate((function(o,i){s[i]=o})),s},toOrderedMap:function(){return OrderedMap(this.toKeyedSeq())},toOrderedSet:function(){return OrderedSet(isKeyed(this)?this.valueSeq():this)},toSet:function(){return Set(isKeyed(this)?this.valueSeq():this)},toSetSeq:function(){return new ToSetSequence(this)},toSeq:function(){return isIndexed(this)?this.toIndexedSeq():isKeyed(this)?this.toKeyedSeq():this.toSetSeq()},toStack:function(){return Stack(isKeyed(this)?this.valueSeq():this)},toList:function(){return List(isKeyed(this)?this.valueSeq():this)},toString:function(){return"[Iterable]"},__toString:function(s,o){return 0===this.size?s+o:s+" "+this.toSeq().map(this.__toStringMapper).join(", ")+" "+o},concat:function(){return reify(this,concatFactory(this,s.call(arguments,0)))},includes:function(s){return this.some((function(o){return is(o,s)}))},entries:function(){return this.__iterator(U)},every:function(s,o){assertNotInfinite(this.size);var i=!0;return this.__iterate((function(a,u,_){if(!s.call(o,a,u,_))return i=!1,!1})),i},filter:function(s,o){return reify(this,filterFactory(this,s,o,!0))},find:function(s,o,i){var a=this.findEntry(s,o);return a?a[1]:i},forEach:function(s,o){return assertNotInfinite(this.size),this.__iterate(o?s.bind(o):s)},join:function(s){assertNotInfinite(this.size),s=void 0!==s?""+s:",";var o="",i=!0;return this.__iterate((function(a){i?i=!1:o+=s,o+=null!=a?a.toString():""})),o},keys:function(){return this.__iterator($)},map:function(s,o){return reify(this,mapFactory(this,s,o))},reduce:function(s,o,i){var a,u;return assertNotInfinite(this.size),arguments.length<2?u=!0:a=o,this.__iterate((function(o,_,w){u?(u=!1,a=o):a=s.call(i,a,o,_,w)})),a},reduceRight:function(s,o,i){var a=this.toKeyedSeq().reverse();return a.reduce.apply(a,arguments)},reverse:function(){return reify(this,reverseFactory(this,!0))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!0))},some:function(s,o){return!this.every(not(s),o)},sort:function(s){return reify(this,sortFactory(this,s))},values:function(){return this.__iterator(V)},butLast:function(){return this.slice(0,-1)},isEmpty:function(){return void 0!==this.size?0===this.size:!this.some((function(){return!0}))},count:function(s,o){return ensureSize(s?this.toSeq().filter(s,o):this)},countBy:function(s,o){return countByFactory(this,s,o)},equals:function(s){return deepEqual(this,s)},entrySeq:function(){var s=this;if(s._cache)return new ArraySeq(s._cache);var o=s.toSeq().map(entryMapper).toIndexedSeq();return o.fromEntrySeq=function(){return s.toSeq()},o},filterNot:function(s,o){return this.filter(not(s),o)},findEntry:function(s,o,i){var a=i;return this.__iterate((function(i,u,_){if(s.call(o,i,u,_))return a=[u,i],!1})),a},findKey:function(s,o){var i=this.findEntry(s,o);return i&&i[0]},findLast:function(s,o,i){return this.toKeyedSeq().reverse().find(s,o,i)},findLastEntry:function(s,o,i){return this.toKeyedSeq().reverse().findEntry(s,o,i)},findLastKey:function(s,o){return this.toKeyedSeq().reverse().findKey(s,o)},first:function(){return this.find(returnTrue)},flatMap:function(s,o){return reify(this,flatMapFactory(this,s,o))},flatten:function(s){return reify(this,flattenFactory(this,s,!0))},fromEntrySeq:function(){return new FromEntriesSequence(this)},get:function(s,o){return this.find((function(o,i){return is(i,s)}),void 0,o)},getIn:function(s,o){for(var i,a=this,u=forceIterator(s);!(i=u.next()).done;){var _=i.value;if((a=a&&a.get?a.get(_,j):j)===j)return o}return a},groupBy:function(s,o){return groupByFactory(this,s,o)},has:function(s){return this.get(s,j)!==j},hasIn:function(s){return this.getIn(s,j)!==j},isSubset:function(s){return s="function"==typeof s.includes?s:Iterable(s),this.every((function(o){return s.includes(o)}))},isSuperset:function(s){return(s="function"==typeof s.isSubset?s:Iterable(s)).isSubset(this)},keyOf:function(s){return this.findKey((function(o){return is(o,s)}))},keySeq:function(){return this.toSeq().map(keyMapper).toIndexedSeq()},last:function(){return this.toSeq().reverse().first()},lastKeyOf:function(s){return this.toKeyedSeq().reverse().keyOf(s)},max:function(s){return maxFactory(this,s)},maxBy:function(s,o){return maxFactory(this,o,s)},min:function(s){return maxFactory(this,s?neg(s):defaultNegComparator)},minBy:function(s,o){return maxFactory(this,o?neg(o):defaultNegComparator,s)},rest:function(){return this.slice(1)},skip:function(s){return this.slice(Math.max(0,s))},skipLast:function(s){return reify(this,this.toSeq().reverse().skip(s).reverse())},skipWhile:function(s,o){return reify(this,skipWhileFactory(this,s,o,!0))},skipUntil:function(s,o){return this.skipWhile(not(s),o)},sortBy:function(s,o){return reify(this,sortFactory(this,o,s))},take:function(s){return this.slice(0,Math.max(0,s))},takeLast:function(s){return reify(this,this.toSeq().reverse().take(s).reverse())},takeWhile:function(s,o){return reify(this,takeWhileFactory(this,s,o))},takeUntil:function(s,o){return this.takeWhile(not(s),o)},valueSeq:function(){return this.toIndexedSeq()},hashCode:function(){return this.__hash||(this.__hash=hashIterable(this))}});var ut=Iterable.prototype;ut[o]=!0,ut[Z]=ut.values,ut.__toJS=ut.toArray,ut.__toStringMapper=quoteString,ut.inspect=ut.toSource=function(){return this.toString()},ut.chain=ut.flatMap,ut.contains=ut.includes,mixin(KeyedIterable,{flip:function(){return reify(this,flipFactory(this))},mapEntries:function(s,o){var i=this,a=0;return reify(this,this.toSeq().map((function(u,_){return s.call(o,[_,u],a++,i)})).fromEntrySeq())},mapKeys:function(s,o){var i=this;return reify(this,this.toSeq().flip().map((function(a,u){return s.call(o,a,u,i)})).flip())}});var pt=KeyedIterable.prototype;function keyMapper(s,o){return o}function entryMapper(s,o){return[o,s]}function not(s){return function(){return!s.apply(this,arguments)}}function neg(s){return function(){return-s.apply(this,arguments)}}function quoteString(s){return"string"==typeof s?JSON.stringify(s):String(s)}function defaultZipper(){return arrCopy(arguments)}function defaultNegComparator(s,o){return so?-1:0}function hashIterable(s){if(s.size===1/0)return 0;var o=isOrdered(s),i=isKeyed(s),a=o?1:0;return murmurHashOfSize(s.__iterate(i?o?function(s,o){a=31*a+hashMerge(hash(s),hash(o))|0}:function(s,o){a=a+hashMerge(hash(s),hash(o))|0}:o?function(s){a=31*a+hash(s)|0}:function(s){a=a+hash(s)|0}),a)}function murmurHashOfSize(s,o){return o=le(o,3432918353),o=le(o<<15|o>>>-15,461845907),o=le(o<<13|o>>>-13,5),o=le((o=o+3864292196^s)^o>>>16,2246822507),o=smi((o=le(o^o>>>13,3266489909))^o>>>16)}function hashMerge(s,o){return s^o+2654435769+(s<<6)+(s>>2)}return pt[i]=!0,pt[Z]=ut.entries,pt.__toJS=ut.toObject,pt.__toStringMapper=function(s,o){return JSON.stringify(o)+": "+quoteString(s)},mixin(IndexedIterable,{toKeyedSeq:function(){return new ToKeyedSequence(this,!1)},filter:function(s,o){return reify(this,filterFactory(this,s,o,!1))},findIndex:function(s,o){var i=this.findEntry(s,o);return i?i[0]:-1},indexOf:function(s){var o=this.keyOf(s);return void 0===o?-1:o},lastIndexOf:function(s){var o=this.lastKeyOf(s);return void 0===o?-1:o},reverse:function(){return reify(this,reverseFactory(this,!1))},slice:function(s,o){return reify(this,sliceFactory(this,s,o,!1))},splice:function(s,o){var i=arguments.length;if(o=Math.max(0|o,0),0===i||2===i&&!o)return this;s=resolveBegin(s,s<0?this.count():this.size);var a=this.slice(0,s);return reify(this,1===i?a:a.concat(arrCopy(arguments,2),this.slice(s+o)))},findLastIndex:function(s,o){var i=this.findLastEntry(s,o);return i?i[0]:-1},first:function(){return this.get(0)},flatten:function(s){return reify(this,flattenFactory(this,s,!1))},get:function(s,o){return(s=wrapIndex(this,s))<0||this.size===1/0||void 0!==this.size&&s>this.size?o:this.find((function(o,i){return i===s}),void 0,o)},has:function(s){return(s=wrapIndex(this,s))>=0&&(void 0!==this.size?this.size===1/0||s{"use strict";i(71340);var a=i(92046);s.exports=a.Object.assign},9999:(s,o,i)=>{var a=i(37217),u=i(83729),_=i(16547),w=i(74733),x=i(43838),C=i(93290),j=i(23007),L=i(92271),B=i(48948),$=i(50002),V=i(83349),U=i(5861),z=i(76189),Y=i(77199),Z=i(35529),ee=i(56449),ie=i(3656),ae=i(87730),ce=i(23805),le=i(38440),pe=i(95950),de=i(37241),fe="[object Arguments]",ye="[object Function]",be="[object Object]",_e={};_e[fe]=_e["[object Array]"]=_e["[object ArrayBuffer]"]=_e["[object DataView]"]=_e["[object Boolean]"]=_e["[object Date]"]=_e["[object Float32Array]"]=_e["[object Float64Array]"]=_e["[object Int8Array]"]=_e["[object Int16Array]"]=_e["[object Int32Array]"]=_e["[object Map]"]=_e["[object Number]"]=_e[be]=_e["[object RegExp]"]=_e["[object Set]"]=_e["[object String]"]=_e["[object Symbol]"]=_e["[object Uint8Array]"]=_e["[object Uint8ClampedArray]"]=_e["[object Uint16Array]"]=_e["[object Uint32Array]"]=!0,_e["[object Error]"]=_e[ye]=_e["[object WeakMap]"]=!1,s.exports=function baseClone(s,o,i,Se,we,xe){var Pe,Te=1&o,Re=2&o,qe=4&o;if(i&&(Pe=we?i(s,Se,we,xe):i(s)),void 0!==Pe)return Pe;if(!ce(s))return s;var $e=ee(s);if($e){if(Pe=z(s),!Te)return j(s,Pe)}else{var ze=U(s),We=ze==ye||"[object GeneratorFunction]"==ze;if(ie(s))return C(s,Te);if(ze==be||ze==fe||We&&!we){if(Pe=Re||We?{}:Z(s),!Te)return Re?B(s,x(Pe,s)):L(s,w(Pe,s))}else{if(!_e[ze])return we?s:{};Pe=Y(s,ze,Te)}}xe||(xe=new a);var He=xe.get(s);if(He)return He;xe.set(s,Pe),le(s)?s.forEach((function(a){Pe.add(baseClone(a,o,i,a,s,xe))})):ae(s)&&s.forEach((function(a,u){Pe.set(u,baseClone(a,o,i,u,s,xe))}));var Xe=$e?void 0:(qe?Re?V:$:Re?de:pe)(s);return u(Xe||s,(function(a,u){Xe&&(a=s[u=a]),_(Pe,u,baseClone(a,o,i,u,s,xe))})),Pe}},10023:(s,o,i)=>{const a=i(6205),INTS=()=>[{type:a.RANGE,from:48,to:57}],WORDS=()=>[{type:a.CHAR,value:95},{type:a.RANGE,from:97,to:122},{type:a.RANGE,from:65,to:90}].concat(INTS()),WHITESPACE=()=>[{type:a.CHAR,value:9},{type:a.CHAR,value:10},{type:a.CHAR,value:11},{type:a.CHAR,value:12},{type:a.CHAR,value:13},{type:a.CHAR,value:32},{type:a.CHAR,value:160},{type:a.CHAR,value:5760},{type:a.RANGE,from:8192,to:8202},{type:a.CHAR,value:8232},{type:a.CHAR,value:8233},{type:a.CHAR,value:8239},{type:a.CHAR,value:8287},{type:a.CHAR,value:12288},{type:a.CHAR,value:65279}];o.words=()=>({type:a.SET,set:WORDS(),not:!1}),o.notWords=()=>({type:a.SET,set:WORDS(),not:!0}),o.ints=()=>({type:a.SET,set:INTS(),not:!1}),o.notInts=()=>({type:a.SET,set:INTS(),not:!0}),o.whitespace=()=>({type:a.SET,set:WHITESPACE(),not:!1}),o.notWhitespace=()=>({type:a.SET,set:WHITESPACE(),not:!0}),o.anyChar=()=>({type:a.SET,set:[{type:a.CHAR,value:10},{type:a.CHAR,value:13},{type:a.CHAR,value:8232},{type:a.CHAR,value:8233}],not:!0})},10043:(s,o,i)=>{"use strict";var a=i(54018),u=String,_=TypeError;s.exports=function(s){if(a(s))return s;throw new _("Can't set "+u(s)+" as a prototype")}},10124:(s,o,i)=>{var a=i(9325);s.exports=function(){return a.Date.now()}},10300:(s,o,i)=>{"use strict";var a=i(13930),u=i(82159),_=i(36624),w=i(4640),x=i(73448),C=TypeError;s.exports=function(s,o){var i=arguments.length<2?x(s):o;if(u(i))return _(a(i,s));throw new C(w(s)+" is not iterable")}},10316:(s,o,i)=>{const a=i(2404),u=i(55973),_=i(92340);class Element{constructor(s,o,i){o&&(this.meta=o),i&&(this.attributes=i),this.content=s}freeze(){Object.isFrozen(this)||(this._meta&&(this.meta.parent=this,this.meta.freeze()),this._attributes&&(this.attributes.parent=this,this.attributes.freeze()),this.children.forEach((s=>{s.parent=this,s.freeze()}),this),this.content&&Array.isArray(this.content)&&Object.freeze(this.content),Object.freeze(this))}primitive(){}clone(){const s=new this.constructor;return s.element=this.element,this.meta.length&&(s._meta=this.meta.clone()),this.attributes.length&&(s._attributes=this.attributes.clone()),this.content?this.content.clone?s.content=this.content.clone():Array.isArray(this.content)?s.content=this.content.map((s=>s.clone())):s.content=this.content:s.content=this.content,s}toValue(){return this.content instanceof Element?this.content.toValue():this.content instanceof u?{key:this.content.key.toValue(),value:this.content.value?this.content.value.toValue():void 0}:this.content&&this.content.map?this.content.map((s=>s.toValue()),this):this.content}toRef(s){if(""===this.id.toValue())throw Error("Cannot create reference to an element that does not contain an ID");const o=new this.RefElement(this.id.toValue());return s&&(o.path=s),o}findRecursive(...s){if(arguments.length>1&&!this.isFrozen)throw new Error("Cannot find recursive with multiple element names without first freezing the element. Call `element.freeze()`");const o=s.pop();let i=new _;const append=(s,o)=>(s.push(o),s),checkElement=(s,i)=>{i.element===o&&s.push(i);const a=i.findRecursive(o);return a&&a.reduce(append,s),i.content instanceof u&&(i.content.key&&checkElement(s,i.content.key),i.content.value&&checkElement(s,i.content.value)),s};return this.content&&(this.content.element&&checkElement(i,this.content),Array.isArray(this.content)&&this.content.reduce(checkElement,i)),s.isEmpty||(i=i.filter((o=>{let i=o.parents.map((s=>s.element));for(const o in s){const a=s[o],u=i.indexOf(a);if(-1===u)return!1;i=i.splice(0,u)}return!0}))),i}set(s){return this.content=s,this}equals(s){return a(this.toValue(),s)}getMetaProperty(s,o){if(!this.meta.hasKey(s)){if(this.isFrozen){const s=this.refract(o);return s.freeze(),s}this.meta.set(s,o)}return this.meta.get(s)}setMetaProperty(s,o){this.meta.set(s,o)}get element(){return this._storedElement||"element"}set element(s){this._storedElement=s}get content(){return this._content}set content(s){if(s instanceof Element)this._content=s;else if(s instanceof _)this.content=s.elements;else if("string"==typeof s||"number"==typeof s||"boolean"==typeof s||"null"===s||null==s)this._content=s;else if(s instanceof u)this._content=s;else if(Array.isArray(s))this._content=s.map(this.refract);else{if("object"!=typeof s)throw new Error("Cannot set content to given value");this._content=Object.keys(s).map((o=>new this.MemberElement(o,s[o])))}}get meta(){if(!this._meta){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._meta=new this.ObjectElement}return this._meta}set meta(s){s instanceof this.ObjectElement?this._meta=s:this.meta.set(s||{})}get attributes(){if(!this._attributes){if(this.isFrozen){const s=new this.ObjectElement;return s.freeze(),s}this._attributes=new this.ObjectElement}return this._attributes}set attributes(s){s instanceof this.ObjectElement?this._attributes=s:this.attributes.set(s||{})}get id(){return this.getMetaProperty("id","")}set id(s){this.setMetaProperty("id",s)}get classes(){return this.getMetaProperty("classes",[])}set classes(s){this.setMetaProperty("classes",s)}get title(){return this.getMetaProperty("title","")}set title(s){this.setMetaProperty("title",s)}get description(){return this.getMetaProperty("description","")}set description(s){this.setMetaProperty("description",s)}get links(){return this.getMetaProperty("links",[])}set links(s){this.setMetaProperty("links",s)}get isFrozen(){return Object.isFrozen(this)}get parents(){let{parent:s}=this;const o=new _;for(;s;)o.push(s),s=s.parent;return o}get children(){if(Array.isArray(this.content))return new _(this.content);if(this.content instanceof u){const s=new _([this.content.key]);return this.content.value&&s.push(this.content.value),s}return this.content instanceof Element?new _([this.content]):new _}get recursiveChildren(){const s=new _;return this.children.forEach((o=>{s.push(o),o.recursiveChildren.forEach((o=>{s.push(o)}))})),s}}s.exports=Element},10392:s=>{s.exports=function getValue(s,o){return null==s?void 0:s[o]}},10776:(s,o,i)=>{var a=i(30756),u=i(95950);s.exports=function getMatchData(s){for(var o=u(s),i=o.length;i--;){var _=o[i],w=s[_];o[i]=[_,w,a(w)]}return o}},10866:(s,o,i)=>{const a=i(6048),u=i(92340);class ObjectSlice extends u{map(s,o){return this.elements.map((i=>s.bind(o)(i.value,i.key,i)))}filter(s,o){return new ObjectSlice(this.elements.filter((i=>s.bind(o)(i.value,i.key,i))))}reject(s,o){return this.filter(a(s.bind(o)))}forEach(s,o){return this.elements.forEach(((i,a)=>{s.bind(o)(i.value,i.key,i,a)}))}keys(){return this.map(((s,o)=>o.toValue()))}values(){return this.map((s=>s.toValue()))}}s.exports=ObjectSlice},11042:(s,o,i)=>{"use strict";var a=i(85582),u=i(1907),_=i(24443),w=i(87170),x=i(36624),C=u([].concat);s.exports=a("Reflect","ownKeys")||function ownKeys(s){var o=_.f(x(s)),i=w.f;return i?C(o,i(s)):o}},11091:(s,o,i)=>{"use strict";var a=i(45951),u=i(76024),_=i(92361),w=i(62250),x=i(13846).f,C=i(7463),j=i(92046),L=i(28311),B=i(61626),$=i(49724);i(36128);var wrapConstructor=function(s){var Wrapper=function(o,i,a){if(this instanceof Wrapper){switch(arguments.length){case 0:return new s;case 1:return new s(o);case 2:return new s(o,i)}return new s(o,i,a)}return u(s,this,arguments)};return Wrapper.prototype=s.prototype,Wrapper};s.exports=function(s,o){var i,u,V,U,z,Y,Z,ee,ie,ae=s.target,ce=s.global,le=s.stat,pe=s.proto,de=ce?a:le?a[ae]:a[ae]&&a[ae].prototype,fe=ce?j:j[ae]||B(j,ae,{})[ae],ye=fe.prototype;for(U in o)u=!(i=C(ce?U:ae+(le?".":"#")+U,s.forced))&&de&&$(de,U),Y=fe[U],u&&(Z=s.dontCallGetSet?(ie=x(de,U))&&ie.value:de[U]),z=u&&Z?Z:o[U],(i||pe||typeof Y!=typeof z)&&(ee=s.bind&&u?L(z,a):s.wrap&&u?wrapConstructor(z):pe&&w(z)?_(z):z,(s.sham||z&&z.sham||Y&&Y.sham)&&B(ee,"sham",!0),B(fe,U,ee),pe&&($(j,V=ae+"Prototype")||B(j,V,{}),B(j[V],U,z),s.real&&ye&&(i||!ye[U])&&B(ye,U,z)))}},11287:s=>{s.exports=function getHolder(s){return s.placeholder}},11331:(s,o,i)=>{var a=i(72552),u=i(28879),_=i(40346),w=Function.prototype,x=Object.prototype,C=w.toString,j=x.hasOwnProperty,L=C.call(Object);s.exports=function isPlainObject(s){if(!_(s)||"[object Object]"!=a(s))return!1;var o=u(s);if(null===o)return!0;var i=j.call(o,"constructor")&&o.constructor;return"function"==typeof i&&i instanceof i&&C.call(i)==L}},11470:(s,o,i)=>{"use strict";var a=i(1907),u=i(65482),_=i(90160),w=i(74239),x=a("".charAt),C=a("".charCodeAt),j=a("".slice),createMethod=function(s){return function(o,i){var a,L,B=_(w(o)),$=u(i),V=B.length;return $<0||$>=V?s?"":void 0:(a=C(B,$))<55296||a>56319||$+1===V||(L=C(B,$+1))<56320||L>57343?s?x(B,$):a:s?j(B,$,$+2):L-56320+(a-55296<<10)+65536}};s.exports={codeAt:createMethod(!1),charAt:createMethod(!0)}},11842:(s,o,i)=>{var a=i(82819),u=i(9325);s.exports=function createBind(s,o,i){var _=1&o,w=a(s);return function wrapper(){return(this&&this!==u&&this instanceof wrapper?w:s).apply(_?i:this,arguments)}}},12242:(s,o,i)=>{const a=i(10316);s.exports=class BooleanElement extends a{constructor(s,o,i){super(s,o,i),this.element="boolean"}primitive(){return"boolean"}}},12507:(s,o,i)=>{var a=i(28754),u=i(49698),_=i(63912),w=i(13222);s.exports=function createCaseFirst(s){return function(o){o=w(o);var i=u(o)?_(o):void 0,x=i?i[0]:o.charAt(0),C=i?a(i,1).join(""):o.slice(1);return x[s]()+C}}},12560:(s,o,i)=>{"use strict";i(99363);var a=i(19287),u=i(45951),_=i(14840),w=i(93742);for(var x in a)_(u[x],x),w[x]=w.Array},12651:(s,o,i)=>{var a=i(74218);s.exports=function getMapData(s,o){var i=s.__data__;return a(o)?i["string"==typeof o?"string":"hash"]:i.map}},12749:(s,o,i)=>{var a=i(81042),u=Object.prototype.hasOwnProperty;s.exports=function hashHas(s){var o=this.__data__;return a?void 0!==o[s]:u.call(o,s)}},13222:(s,o,i)=>{var a=i(77556);s.exports=function toString(s){return null==s?"":a(s)}},13846:(s,o,i)=>{"use strict";var a=i(39447),u=i(13930),_=i(22574),w=i(75817),x=i(4993),C=i(70470),j=i(49724),L=i(73648),B=Object.getOwnPropertyDescriptor;o.f=a?B:function getOwnPropertyDescriptor(s,o){if(s=x(s),o=C(o),L)try{return B(s,o)}catch(s){}if(j(s,o))return w(!u(_.f,s,o),s[o])}},13930:(s,o,i)=>{"use strict";var a=i(41505),u=Function.prototype.call;s.exports=a?u.bind(u):function(){return u.apply(u,arguments)}},14248:s=>{s.exports=function arraySome(s,o){for(var i=-1,a=null==s?0:s.length;++i{s.exports=function arrayPush(s,o){for(var i=-1,a=o.length,u=s.length;++i{const a=i(10316);s.exports=class RefElement extends a{constructor(s,o,i){super(s||[],o,i),this.element="ref",this.path||(this.path="element")}get path(){return this.attributes.get("path")}set path(s){this.attributes.set("path",s)}}},14744:s=>{"use strict";var o=function isMergeableObject(s){return function isNonNullObject(s){return!!s&&"object"==typeof s}(s)&&!function isSpecial(s){var o=Object.prototype.toString.call(s);return"[object RegExp]"===o||"[object Date]"===o||function isReactElement(s){return s.$$typeof===i}(s)}(s)};var i="function"==typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;function cloneUnlessOtherwiseSpecified(s,o){return!1!==o.clone&&o.isMergeableObject(s)?deepmerge(function emptyTarget(s){return Array.isArray(s)?[]:{}}(s),s,o):s}function defaultArrayMerge(s,o,i){return s.concat(o).map((function(s){return cloneUnlessOtherwiseSpecified(s,i)}))}function getKeys(s){return Object.keys(s).concat(function getEnumerableOwnPropertySymbols(s){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(s).filter((function(o){return Object.propertyIsEnumerable.call(s,o)})):[]}(s))}function propertyIsOnObject(s,o){try{return o in s}catch(s){return!1}}function mergeObject(s,o,i){var a={};return i.isMergeableObject(s)&&getKeys(s).forEach((function(o){a[o]=cloneUnlessOtherwiseSpecified(s[o],i)})),getKeys(o).forEach((function(u){(function propertyIsUnsafe(s,o){return propertyIsOnObject(s,o)&&!(Object.hasOwnProperty.call(s,o)&&Object.propertyIsEnumerable.call(s,o))})(s,u)||(propertyIsOnObject(s,u)&&i.isMergeableObject(o[u])?a[u]=function getMergeFunction(s,o){if(!o.customMerge)return deepmerge;var i=o.customMerge(s);return"function"==typeof i?i:deepmerge}(u,i)(s[u],o[u],i):a[u]=cloneUnlessOtherwiseSpecified(o[u],i))})),a}function deepmerge(s,i,a){(a=a||{}).arrayMerge=a.arrayMerge||defaultArrayMerge,a.isMergeableObject=a.isMergeableObject||o,a.cloneUnlessOtherwiseSpecified=cloneUnlessOtherwiseSpecified;var u=Array.isArray(i);return u===Array.isArray(s)?u?a.arrayMerge(s,i,a):mergeObject(s,i,a):cloneUnlessOtherwiseSpecified(i,a)}deepmerge.all=function deepmergeAll(s,o){if(!Array.isArray(s))throw new Error("first argument should be an array");return s.reduce((function(s,i){return deepmerge(s,i,o)}),{})};var a=deepmerge;s.exports=a},14792:(s,o,i)=>{var a=i(13222),u=i(55808);s.exports=function capitalize(s){return u(a(s).toLowerCase())}},14840:(s,o,i)=>{"use strict";var a=i(52623),u=i(74284).f,_=i(61626),w=i(49724),x=i(54878),C=i(76264)("toStringTag");s.exports=function(s,o,i,j){var L=i?s:s&&s.prototype;L&&(w(L,C)||u(L,C,{configurable:!0,value:o}),j&&!a&&_(L,"toString",x))}},14974:s=>{s.exports=function safeGet(s,o){if(("constructor"!==o||"function"!=typeof s[o])&&"__proto__"!=o)return s[o]}},15287:(s,o)=>{"use strict";var i=Symbol.for("react.element"),a=Symbol.for("react.portal"),u=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),x=Symbol.for("react.provider"),C=Symbol.for("react.context"),j=Symbol.for("react.forward_ref"),L=Symbol.for("react.suspense"),B=Symbol.for("react.memo"),$=Symbol.for("react.lazy"),V=Symbol.iterator;var U={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},z=Object.assign,Y={};function E(s,o,i){this.props=s,this.context=o,this.refs=Y,this.updater=i||U}function F(){}function G(s,o,i){this.props=s,this.context=o,this.refs=Y,this.updater=i||U}E.prototype.isReactComponent={},E.prototype.setState=function(s,o){if("object"!=typeof s&&"function"!=typeof s&&null!=s)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,s,o,"setState")},E.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")},F.prototype=E.prototype;var Z=G.prototype=new F;Z.constructor=G,z(Z,E.prototype),Z.isPureReactComponent=!0;var ee=Array.isArray,ie=Object.prototype.hasOwnProperty,ae={current:null},ce={key:!0,ref:!0,__self:!0,__source:!0};function M(s,o,a){var u,_={},w=null,x=null;if(null!=o)for(u in void 0!==o.ref&&(x=o.ref),void 0!==o.key&&(w=""+o.key),o)ie.call(o,u)&&!ce.hasOwnProperty(u)&&(_[u]=o[u]);var C=arguments.length-2;if(1===C)_.children=a;else if(1{var a=i(96131);s.exports=function arrayIncludes(s,o){return!!(null==s?0:s.length)&&a(s,o,0)>-1}},15340:()=>{},15389:(s,o,i)=>{var a=i(93663),u=i(87978),_=i(83488),w=i(56449),x=i(50583);s.exports=function baseIteratee(s){return"function"==typeof s?s:null==s?_:"object"==typeof s?w(s)?u(s[0],s[1]):a(s):x(s)}},15972:(s,o,i)=>{"use strict";var a=i(49724),u=i(62250),_=i(39298),w=i(92522),x=i(57382),C=w("IE_PROTO"),j=Object,L=j.prototype;s.exports=x?j.getPrototypeOf:function(s){var o=_(s);if(a(o,C))return o[C];var i=o.constructor;return u(i)&&o instanceof i?i.prototype:o instanceof j?L:null}},16038:(s,o,i)=>{var a=i(5861),u=i(40346);s.exports=function baseIsSet(s){return u(s)&&"[object Set]"==a(s)}},16426:s=>{s.exports=function(){var s=document.getSelection();if(!s.rangeCount)return function(){};for(var o=document.activeElement,i=[],a=0;a{var a=i(43360),u=i(75288),_=Object.prototype.hasOwnProperty;s.exports=function assignValue(s,o,i){var w=s[o];_.call(s,o)&&u(w,i)&&(void 0!==i||o in s)||a(s,o,i)}},16708:(s,o,i)=>{"use strict";var a,u=i(65606);function CorkedRequest(s){var o=this;this.next=null,this.entry=null,this.finish=function(){!function onCorkedFinish(s,o,i){var a=s.entry;s.entry=null;for(;a;){var u=a.callback;o.pendingcb--,u(i),a=a.next}o.corkedRequestsFree.next=s}(o,s)}}s.exports=Writable,Writable.WritableState=WritableState;var _={deprecate:i(94643)},w=i(40345),x=i(48287).Buffer,C=(void 0!==i.g?i.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){};var j,L=i(75896),B=i(65291).getHighWaterMark,$=i(86048).F,V=$.ERR_INVALID_ARG_TYPE,U=$.ERR_METHOD_NOT_IMPLEMENTED,z=$.ERR_MULTIPLE_CALLBACK,Y=$.ERR_STREAM_CANNOT_PIPE,Z=$.ERR_STREAM_DESTROYED,ee=$.ERR_STREAM_NULL_VALUES,ie=$.ERR_STREAM_WRITE_AFTER_END,ae=$.ERR_UNKNOWN_ENCODING,ce=L.errorOrDestroy;function nop(){}function WritableState(s,o,_){a=a||i(25382),s=s||{},"boolean"!=typeof _&&(_=o instanceof a),this.objectMode=!!s.objectMode,_&&(this.objectMode=this.objectMode||!!s.writableObjectMode),this.highWaterMark=B(this,s,"writableHighWaterMark",_),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var w=!1===s.decodeStrings;this.decodeStrings=!w,this.defaultEncoding=s.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(s){!function onwrite(s,o){var i=s._writableState,a=i.sync,_=i.writecb;if("function"!=typeof _)throw new z;if(function onwriteStateUpdate(s){s.writing=!1,s.writecb=null,s.length-=s.writelen,s.writelen=0}(i),o)!function onwriteError(s,o,i,a,_){--o.pendingcb,i?(u.nextTick(_,a),u.nextTick(finishMaybe,s,o),s._writableState.errorEmitted=!0,ce(s,a)):(_(a),s._writableState.errorEmitted=!0,ce(s,a),finishMaybe(s,o))}(s,i,a,o,_);else{var w=needFinish(i)||s.destroyed;w||i.corked||i.bufferProcessing||!i.bufferedRequest||clearBuffer(s,i),a?u.nextTick(afterWrite,s,i,w,_):afterWrite(s,i,w,_)}}(o,s)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==s.emitClose,this.autoDestroy=!!s.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new CorkedRequest(this)}function Writable(s){var o=this instanceof(a=a||i(25382));if(!o&&!j.call(Writable,this))return new Writable(s);this._writableState=new WritableState(s,this,o),this.writable=!0,s&&("function"==typeof s.write&&(this._write=s.write),"function"==typeof s.writev&&(this._writev=s.writev),"function"==typeof s.destroy&&(this._destroy=s.destroy),"function"==typeof s.final&&(this._final=s.final)),w.call(this)}function doWrite(s,o,i,a,u,_,w){o.writelen=a,o.writecb=w,o.writing=!0,o.sync=!0,o.destroyed?o.onwrite(new Z("write")):i?s._writev(u,o.onwrite):s._write(u,_,o.onwrite),o.sync=!1}function afterWrite(s,o,i,a){i||function onwriteDrain(s,o){0===o.length&&o.needDrain&&(o.needDrain=!1,s.emit("drain"))}(s,o),o.pendingcb--,a(),finishMaybe(s,o)}function clearBuffer(s,o){o.bufferProcessing=!0;var i=o.bufferedRequest;if(s._writev&&i&&i.next){var a=o.bufferedRequestCount,u=new Array(a),_=o.corkedRequestsFree;_.entry=i;for(var w=0,x=!0;i;)u[w]=i,i.isBuf||(x=!1),i=i.next,w+=1;u.allBuffers=x,doWrite(s,o,!0,o.length,u,"",_.finish),o.pendingcb++,o.lastBufferedRequest=null,_.next?(o.corkedRequestsFree=_.next,_.next=null):o.corkedRequestsFree=new CorkedRequest(o),o.bufferedRequestCount=0}else{for(;i;){var C=i.chunk,j=i.encoding,L=i.callback;if(doWrite(s,o,!1,o.objectMode?1:C.length,C,j,L),i=i.next,o.bufferedRequestCount--,o.writing)break}null===i&&(o.lastBufferedRequest=null)}o.bufferedRequest=i,o.bufferProcessing=!1}function needFinish(s){return s.ending&&0===s.length&&null===s.bufferedRequest&&!s.finished&&!s.writing}function callFinal(s,o){s._final((function(i){o.pendingcb--,i&&ce(s,i),o.prefinished=!0,s.emit("prefinish"),finishMaybe(s,o)}))}function finishMaybe(s,o){var i=needFinish(o);if(i&&(function prefinish(s,o){o.prefinished||o.finalCalled||("function"!=typeof s._final||o.destroyed?(o.prefinished=!0,s.emit("prefinish")):(o.pendingcb++,o.finalCalled=!0,u.nextTick(callFinal,s,o)))}(s,o),0===o.pendingcb&&(o.finished=!0,s.emit("finish"),o.autoDestroy))){var a=s._readableState;(!a||a.autoDestroy&&a.endEmitted)&&s.destroy()}return i}i(56698)(Writable,w),WritableState.prototype.getBuffer=function getBuffer(){for(var s=this.bufferedRequest,o=[];s;)o.push(s),s=s.next;return o},function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:_.deprecate((function writableStateBufferGetter(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(s){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(j=Function.prototype[Symbol.hasInstance],Object.defineProperty(Writable,Symbol.hasInstance,{value:function value(s){return!!j.call(this,s)||this===Writable&&(s&&s._writableState instanceof WritableState)}})):j=function realHasInstance(s){return s instanceof this},Writable.prototype.pipe=function(){ce(this,new Y)},Writable.prototype.write=function(s,o,i){var a=this._writableState,_=!1,w=!a.objectMode&&function _isUint8Array(s){return x.isBuffer(s)||s instanceof C}(s);return w&&!x.isBuffer(s)&&(s=function _uint8ArrayToBuffer(s){return x.from(s)}(s)),"function"==typeof o&&(i=o,o=null),w?o="buffer":o||(o=a.defaultEncoding),"function"!=typeof i&&(i=nop),a.ending?function writeAfterEnd(s,o){var i=new ie;ce(s,i),u.nextTick(o,i)}(this,i):(w||function validChunk(s,o,i,a){var _;return null===i?_=new ee:"string"==typeof i||o.objectMode||(_=new V("chunk",["string","Buffer"],i)),!_||(ce(s,_),u.nextTick(a,_),!1)}(this,a,s,i))&&(a.pendingcb++,_=function writeOrBuffer(s,o,i,a,u,_){if(!i){var w=function decodeChunk(s,o,i){s.objectMode||!1===s.decodeStrings||"string"!=typeof o||(o=x.from(o,i));return o}(o,a,u);a!==w&&(i=!0,u="buffer",a=w)}var C=o.objectMode?1:a.length;o.length+=C;var j=o.length-1))throw new ae(s);return this._writableState.defaultEncoding=s,this},Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:!1,get:function get(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:!1,get:function get(){return this._writableState.highWaterMark}}),Writable.prototype._write=function(s,o,i){i(new U("_write()"))},Writable.prototype._writev=null,Writable.prototype.end=function(s,o,i){var a=this._writableState;return"function"==typeof s?(i=s,s=null,o=null):"function"==typeof o&&(i=o,o=null),null!=s&&this.write(s,o),a.corked&&(a.corked=1,this.uncork()),a.ending||function endWritable(s,o,i){o.ending=!0,finishMaybe(s,o),i&&(o.finished?u.nextTick(i):s.once("finish",i));o.ended=!0,s.writable=!1}(this,a,i),this},Object.defineProperty(Writable.prototype,"writableLength",{enumerable:!1,get:function get(){return this._writableState.length}}),Object.defineProperty(Writable.prototype,"destroyed",{enumerable:!1,get:function get(){return void 0!==this._writableState&&this._writableState.destroyed},set:function set(s){this._writableState&&(this._writableState.destroyed=s)}}),Writable.prototype.destroy=L.destroy,Writable.prototype._undestroy=L.undestroy,Writable.prototype._destroy=function(s,o){o(s)}},16946:(s,o,i)=>{"use strict";var a=i(1907),u=i(98828),_=i(45807),w=Object,x=a("".split);s.exports=u((function(){return!w("z").propertyIsEnumerable(0)}))?function(s){return"String"===_(s)?x(s,""):w(s)}:w},16962:(s,o)=>{o.aliasToReal={each:"forEach",eachRight:"forEachRight",entries:"toPairs",entriesIn:"toPairsIn",extend:"assignIn",extendAll:"assignInAll",extendAllWith:"assignInAllWith",extendWith:"assignInWith",first:"head",conforms:"conformsTo",matches:"isMatch",property:"get",__:"placeholder",F:"stubFalse",T:"stubTrue",all:"every",allPass:"overEvery",always:"constant",any:"some",anyPass:"overSome",apply:"spread",assoc:"set",assocPath:"set",complement:"negate",compose:"flowRight",contains:"includes",dissoc:"unset",dissocPath:"unset",dropLast:"dropRight",dropLastWhile:"dropRightWhile",equals:"isEqual",identical:"eq",indexBy:"keyBy",init:"initial",invertObj:"invert",juxt:"over",omitAll:"omit",nAry:"ary",path:"get",pathEq:"matchesProperty",pathOr:"getOr",paths:"at",pickAll:"pick",pipe:"flow",pluck:"map",prop:"get",propEq:"matchesProperty",propOr:"getOr",props:"at",symmetricDifference:"xor",symmetricDifferenceBy:"xorBy",symmetricDifferenceWith:"xorWith",takeLast:"takeRight",takeLastWhile:"takeRightWhile",unapply:"rest",unnest:"flatten",useWith:"overArgs",where:"conformsTo",whereEq:"isMatch",zipObj:"zipObject"},o.aryMethod={1:["assignAll","assignInAll","attempt","castArray","ceil","create","curry","curryRight","defaultsAll","defaultsDeepAll","floor","flow","flowRight","fromPairs","invert","iteratee","memoize","method","mergeAll","methodOf","mixin","nthArg","over","overEvery","overSome","rest","reverse","round","runInContext","spread","template","trim","trimEnd","trimStart","uniqueId","words","zipAll"],2:["add","after","ary","assign","assignAllWith","assignIn","assignInAllWith","at","before","bind","bindAll","bindKey","chunk","cloneDeepWith","cloneWith","concat","conformsTo","countBy","curryN","curryRightN","debounce","defaults","defaultsDeep","defaultTo","delay","difference","divide","drop","dropRight","dropRightWhile","dropWhile","endsWith","eq","every","filter","find","findIndex","findKey","findLast","findLastIndex","findLastKey","flatMap","flatMapDeep","flattenDepth","forEach","forEachRight","forIn","forInRight","forOwn","forOwnRight","get","groupBy","gt","gte","has","hasIn","includes","indexOf","intersection","invertBy","invoke","invokeMap","isEqual","isMatch","join","keyBy","lastIndexOf","lt","lte","map","mapKeys","mapValues","matchesProperty","maxBy","meanBy","merge","mergeAllWith","minBy","multiply","nth","omit","omitBy","overArgs","pad","padEnd","padStart","parseInt","partial","partialRight","partition","pick","pickBy","propertyOf","pull","pullAll","pullAt","random","range","rangeRight","rearg","reject","remove","repeat","restFrom","result","sampleSize","some","sortBy","sortedIndex","sortedIndexOf","sortedLastIndex","sortedLastIndexOf","sortedUniqBy","split","spreadFrom","startsWith","subtract","sumBy","take","takeRight","takeRightWhile","takeWhile","tap","throttle","thru","times","trimChars","trimCharsEnd","trimCharsStart","truncate","union","uniqBy","uniqWith","unset","unzipWith","without","wrap","xor","zip","zipObject","zipObjectDeep"],3:["assignInWith","assignWith","clamp","differenceBy","differenceWith","findFrom","findIndexFrom","findLastFrom","findLastIndexFrom","getOr","includesFrom","indexOfFrom","inRange","intersectionBy","intersectionWith","invokeArgs","invokeArgsMap","isEqualWith","isMatchWith","flatMapDepth","lastIndexOfFrom","mergeWith","orderBy","padChars","padCharsEnd","padCharsStart","pullAllBy","pullAllWith","rangeStep","rangeStepRight","reduce","reduceRight","replace","set","slice","sortedIndexBy","sortedLastIndexBy","transform","unionBy","unionWith","update","xorBy","xorWith","zipWith"],4:["fill","setWith","updateWith"]},o.aryRearg={2:[1,0],3:[2,0,1],4:[3,2,0,1]},o.iterateeAry={dropRightWhile:1,dropWhile:1,every:1,filter:1,find:1,findFrom:1,findIndex:1,findIndexFrom:1,findKey:1,findLast:1,findLastFrom:1,findLastIndex:1,findLastIndexFrom:1,findLastKey:1,flatMap:1,flatMapDeep:1,flatMapDepth:1,forEach:1,forEachRight:1,forIn:1,forInRight:1,forOwn:1,forOwnRight:1,map:1,mapKeys:1,mapValues:1,partition:1,reduce:2,reduceRight:2,reject:1,remove:1,some:1,takeRightWhile:1,takeWhile:1,times:1,transform:2},o.iterateeRearg={mapKeys:[1],reduceRight:[1,0]},o.methodRearg={assignInAllWith:[1,0],assignInWith:[1,2,0],assignAllWith:[1,0],assignWith:[1,2,0],differenceBy:[1,2,0],differenceWith:[1,2,0],getOr:[2,1,0],intersectionBy:[1,2,0],intersectionWith:[1,2,0],isEqualWith:[1,2,0],isMatchWith:[2,1,0],mergeAllWith:[1,0],mergeWith:[1,2,0],padChars:[2,1,0],padCharsEnd:[2,1,0],padCharsStart:[2,1,0],pullAllBy:[2,1,0],pullAllWith:[2,1,0],rangeStep:[1,2,0],rangeStepRight:[1,2,0],setWith:[3,1,2,0],sortedIndexBy:[2,1,0],sortedLastIndexBy:[2,1,0],unionBy:[1,2,0],unionWith:[1,2,0],updateWith:[3,1,2,0],xorBy:[1,2,0],xorWith:[1,2,0],zipWith:[1,2,0]},o.methodSpread={assignAll:{start:0},assignAllWith:{start:0},assignInAll:{start:0},assignInAllWith:{start:0},defaultsAll:{start:0},defaultsDeepAll:{start:0},invokeArgs:{start:2},invokeArgsMap:{start:2},mergeAll:{start:0},mergeAllWith:{start:0},partial:{start:1},partialRight:{start:1},without:{start:1},zipAll:{start:0}},o.mutate={array:{fill:!0,pull:!0,pullAll:!0,pullAllBy:!0,pullAllWith:!0,pullAt:!0,remove:!0,reverse:!0},object:{assign:!0,assignAll:!0,assignAllWith:!0,assignIn:!0,assignInAll:!0,assignInAllWith:!0,assignInWith:!0,assignWith:!0,defaults:!0,defaultsAll:!0,defaultsDeep:!0,defaultsDeepAll:!0,merge:!0,mergeAll:!0,mergeAllWith:!0,mergeWith:!0},set:{set:!0,setWith:!0,unset:!0,update:!0,updateWith:!0}},o.realToAlias=function(){var s=Object.prototype.hasOwnProperty,i=o.aliasToReal,a={};for(var u in i){var _=i[u];s.call(a,_)?a[_].push(u):a[_]=[u]}return a}(),o.remap={assignAll:"assign",assignAllWith:"assignWith",assignInAll:"assignIn",assignInAllWith:"assignInWith",curryN:"curry",curryRightN:"curryRight",defaultsAll:"defaults",defaultsDeepAll:"defaultsDeep",findFrom:"find",findIndexFrom:"findIndex",findLastFrom:"findLast",findLastIndexFrom:"findLastIndex",getOr:"get",includesFrom:"includes",indexOfFrom:"indexOf",invokeArgs:"invoke",invokeArgsMap:"invokeMap",lastIndexOfFrom:"lastIndexOf",mergeAll:"merge",mergeAllWith:"mergeWith",padChars:"pad",padCharsEnd:"padEnd",padCharsStart:"padStart",propertyOf:"get",rangeStep:"range",rangeStepRight:"rangeRight",restFrom:"rest",spreadFrom:"spread",trimChars:"trim",trimCharsEnd:"trimEnd",trimCharsStart:"trimStart",zipAll:"zip"},o.skipFixed={castArray:!0,flow:!0,flowRight:!0,iteratee:!0,mixin:!0,rearg:!0,runInContext:!0},o.skipRearg={add:!0,assign:!0,assignIn:!0,bind:!0,bindKey:!0,concat:!0,difference:!0,divide:!0,eq:!0,gt:!0,gte:!0,isEqual:!0,lt:!0,lte:!0,matchesProperty:!0,merge:!0,multiply:!0,overArgs:!0,partial:!0,partialRight:!0,propertyOf:!0,random:!0,range:!0,rangeRight:!0,subtract:!0,zip:!0,zipObject:!0,zipObjectDeep:!0}},17255:(s,o,i)=>{var a=i(47422);s.exports=function basePropertyDeep(s){return function(o){return a(o,s)}}},17285:s=>{function source(s){return s?"string"==typeof s?s:s.source:null}function lookahead(s){return concat("(?=",s,")")}function concat(...s){return s.map((s=>source(s))).join("")}function either(...s){return"("+s.map((s=>source(s))).join("|")+")"}s.exports=function xml(s){const o=concat(/[A-Z_]/,function optional(s){return concat("(",s,")?")}(/[A-Z0-9_.-]*:/),/[A-Z0-9_.-]*/),i={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:"meta-keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},u=s.inherit(a,{begin:/\(/,end:/\)/}),_=s.inherit(s.APOS_STRING_MODE,{className:"meta-string"}),w=s.inherit(s.QUOTE_STRING_MODE,{className:"meta-string"}),x={endsWithParent:!0,illegal:/`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,contains:[{className:"meta",begin://,relevance:10,contains:[a,w,_,u,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin://,contains:[a,u,w,_]}]}]},s.COMMENT(//,{relevance:10}),{begin://,relevance:10},i,{className:"meta",begin:/<\?xml/,end:/\?>/,relevance:10},{className:"tag",begin:/)/,end:/>/,keywords:{name:"style"},contains:[x],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/)/,end:/>/,keywords:{name:"script"},contains:[x],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:concat(//,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:o,relevance:0,starts:x}]},{className:"tag",begin:concat(/<\//,lookahead(concat(o,/>/))),contains:[{className:"name",begin:o,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}},17400:(s,o,i)=>{var a=i(99374),u=1/0;s.exports=function toFinite(s){return s?(s=a(s))===u||s===-1/0?17976931348623157e292*(s<0?-1:1):s==s?s:0:0===s?s:0}},17533:s=>{s.exports=function yaml(s){var o="true false yes no null",i="[\\w#;/?:@&=+$,.~*'()[\\]]+",a={className:"string",relevance:0,variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/\S+/}],contains:[s.BACKSLASH_ESCAPE,{className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]}]},u=s.inherit(a,{variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),_={className:"number",begin:"\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b"},w={end:",",endsWithParent:!0,excludeEnd:!0,keywords:o,relevance:0},x={begin:/\{/,end:/\}/,contains:[w],illegal:"\\n",relevance:0},C={begin:"\\[",end:"\\]",contains:[w],illegal:"\\n",relevance:0},j=[{className:"attr",variants:[{begin:"\\w[\\w :\\/.-]*:(?=[ \t]|$)"},{begin:'"\\w[\\w :\\/.-]*":(?=[ \t]|$)'},{begin:"'\\w[\\w :\\/.-]*':(?=[ \t]|$)"}]},{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+i},{className:"type",begin:"!<"+i+">"},{className:"type",begin:"!"+i},{className:"type",begin:"!!"+i},{className:"meta",begin:"&"+s.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+s.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},s.HASH_COMMENT_MODE,{beginKeywords:o,keywords:{literal:o}},_,{className:"number",begin:s.C_NUMBER_RE+"\\b",relevance:0},x,C,a],L=[...j];return L.pop(),L.push(u),w.contains=L,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:j}}},17670:(s,o,i)=>{var a=i(12651);s.exports=function mapCacheDelete(s){var o=a(this,s).delete(s);return this.size-=o?1:0,o}},17965:(s,o,i)=>{"use strict";var a=i(16426),u={"text/plain":"Text","text/html":"Url",default:"Text"};s.exports=function copy(s,o){var i,_,w,x,C,j,L=!1;o||(o={}),i=o.debug||!1;try{if(w=a(),x=document.createRange(),C=document.getSelection(),(j=document.createElement("span")).textContent=s,j.ariaHidden="true",j.style.all="unset",j.style.position="fixed",j.style.top=0,j.style.clip="rect(0, 0, 0, 0)",j.style.whiteSpace="pre",j.style.webkitUserSelect="text",j.style.MozUserSelect="text",j.style.msUserSelect="text",j.style.userSelect="text",j.addEventListener("copy",(function(a){if(a.stopPropagation(),o.format)if(a.preventDefault(),void 0===a.clipboardData){i&&console.warn("unable to use e.clipboardData"),i&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var _=u[o.format]||u.default;window.clipboardData.setData(_,s)}else a.clipboardData.clearData(),a.clipboardData.setData(o.format,s);o.onCopy&&(a.preventDefault(),o.onCopy(a.clipboardData))})),document.body.appendChild(j),x.selectNodeContents(j),C.addRange(x),!document.execCommand("copy"))throw new Error("copy command was unsuccessful");L=!0}catch(a){i&&console.error("unable to copy using execCommand: ",a),i&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(o.format||"text",s),o.onCopy&&o.onCopy(window.clipboardData),L=!0}catch(a){i&&console.error("unable to copy using clipboardData: ",a),i&&console.error("falling back to prompt"),_=function format(s){var o=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return s.replace(/#{\s*key\s*}/g,o)}("message"in o?o.message:"Copy to clipboard: #{key}, Enter"),window.prompt(_,s)}}finally{C&&("function"==typeof C.removeRange?C.removeRange(x):C.removeAllRanges()),j&&document.body.removeChild(j),w()}return L}},18073:(s,o,i)=>{var a=i(85087),u=i(54641),_=i(70981);s.exports=function createRecurry(s,o,i,w,x,C,j,L,B,$){var V=8&o;o|=V?32:64,4&(o&=~(V?64:32))||(o&=-4);var U=[s,o,x,V?C:void 0,V?j:void 0,V?void 0:C,V?void 0:j,L,B,$],z=i.apply(void 0,U);return a(s)&&u(z,U),z.placeholder=w,_(z,s,o)}},19123:(s,o,i)=>{var a=i(65606),u=i(31499),_=i(88310).Stream;function resolve(s,o,i){var a,_=function create_indent(s,o){return new Array(o||0).join(s||"")}(o,i=i||0),w=s;if("object"==typeof s&&((w=s[a=Object.keys(s)[0]])&&w._elem))return w._elem.name=a,w._elem.icount=i,w._elem.indent=o,w._elem.indents=_,w._elem.interrupt=w,w._elem;var x,C=[],j=[];function get_attributes(s){Object.keys(s).forEach((function(o){C.push(function attribute(s,o){return s+'="'+u(o)+'"'}(o,s[o]))}))}switch(typeof w){case"object":if(null===w)break;w._attr&&get_attributes(w._attr),w._cdata&&j.push(("/g,"]]]]>")+"]]>"),w.forEach&&(x=!1,j.push(""),w.forEach((function(s){"object"==typeof s?"_attr"==Object.keys(s)[0]?get_attributes(s._attr):j.push(resolve(s,o,i+1)):(j.pop(),x=!0,j.push(u(s)))})),x||j.push(""));break;default:j.push(u(w))}return{name:a,interrupt:!1,attributes:C,content:j,icount:i,indents:_,indent:o}}function format(s,o,i){if("object"!=typeof o)return s(!1,o);var a=o.interrupt?1:o.content.length;function proceed(){for(;o.content.length;){var u=o.content.shift();if(void 0!==u){if(interrupt(u))return;format(s,u)}}s(!1,(a>1?o.indents:"")+(o.name?"":"")+(o.indent&&!i?"\n":"")),i&&i()}function interrupt(o){return!!o.interrupt&&(o.interrupt.append=s,o.interrupt.end=proceed,o.interrupt=!1,s(!0),!0)}if(s(!1,o.indents+(o.name?"<"+o.name:"")+(o.attributes.length?" "+o.attributes.join(" "):"")+(a?o.name?">":"":o.name?"/>":"")+(o.indent&&a>1?"\n":"")),!a)return s(!1,o.indent?"\n":"");interrupt(o)||proceed()}s.exports=function xml(s,o){"object"!=typeof o&&(o={indent:o});var i=o.stream?new _:null,u="",w=!1,x=o.indent?!0===o.indent?" ":o.indent:"",C=!0;function delay(s){C?a.nextTick(s):s()}function append(s,o){if(void 0!==o&&(u+=o),s&&!w&&(i=i||new _,w=!0),s&&w){var a=u;delay((function(){i.emit("data",a)})),u=""}}function add(s,o){format(append,resolve(s,x,x?1:0),o)}function end(){if(i){var s=u;delay((function(){i.emit("data",s),i.emit("end"),i.readable=!1,i.emit("close")}))}}return delay((function(){C=!1})),o.declaration&&function addXmlDeclaration(s){var o={version:"1.0",encoding:s.encoding||"UTF-8"};s.standalone&&(o.standalone=s.standalone),add({"?xml":{_attr:o}}),u=u.replace("/>","?>")}(o.declaration),s&&s.forEach?s.forEach((function(o,i){var a;i+1===s.length&&(a=end),add(o,a)})):add(s,end),i?(i.readable=!0,i):u},s.exports.element=s.exports.Element=function element(){var s={_elem:resolve(Array.prototype.slice.call(arguments)),push:function(s){if(!this.append)throw new Error("not assigned to a parent!");var o=this,i=this._elem.indent;format(this.append,resolve(s,i,this._elem.icount+(i?1:0)),(function(){o.append(!0)}))},close:function(s){void 0!==s&&this.push(s),this.end&&this.end()}};return s}},19219:s=>{s.exports=function cacheHas(s,o){return s.has(o)}},19287:s=>{"use strict";s.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},19358:(s,o,i)=>{"use strict";var a=i(85582),u=i(49724),_=i(61626),w=i(88280),x=i(79192),C=i(19595),j=i(54829),L=i(34084),B=i(32096),$=i(39259),V=i(85884),U=i(39447),z=i(7376);s.exports=function(s,o,i,Y){var Z="stackTraceLimit",ee=Y?2:1,ie=s.split("."),ae=ie[ie.length-1],ce=a.apply(null,ie);if(ce){var le=ce.prototype;if(!z&&u(le,"cause")&&delete le.cause,!i)return ce;var pe=a("Error"),de=o((function(s,o){var i=B(Y?o:s,void 0),a=Y?new ce(s):new ce;return void 0!==i&&_(a,"message",i),V(a,de,a.stack,2),this&&w(le,this)&&L(a,this,de),arguments.length>ee&&$(a,arguments[ee]),a}));if(de.prototype=le,"Error"!==ae?x?x(de,pe):C(de,pe,{name:!0}):U&&Z in ce&&(j(de,ce,Z),j(de,ce,"prepareStackTrace")),C(de,ce),!z)try{le.name!==ae&&_(le,"name",ae),le.constructor=de}catch(s){}return de}}},19570:(s,o,i)=>{var a=i(37334),u=i(93243),_=i(83488),w=u?function(s,o){return u(s,"toString",{configurable:!0,enumerable:!1,value:a(o),writable:!0})}:_;s.exports=w},19595:(s,o,i)=>{"use strict";var a=i(49724),u=i(11042),_=i(13846),w=i(74284);s.exports=function(s,o,i){for(var x=u(o),C=w.f,j=_.f,L=0;L{"use strict";var a=i(23034);s.exports=a},19846:(s,o,i)=>{"use strict";var a=i(20798),u=i(98828),_=i(45951).String;s.exports=!!Object.getOwnPropertySymbols&&!u((function(){var s=Symbol("symbol detection");return!_(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&a&&a<41}))},19931:(s,o,i)=>{var a=i(31769),u=i(68090),_=i(68969),w=i(77797);s.exports=function baseUnset(s,o){return o=a(o,s),null==(s=_(s,o))||delete s[w(u(o))]}},20181:(s,o,i)=>{var a=/^\s+|\s+$/g,u=/^[-+]0x[0-9a-f]+$/i,_=/^0b[01]+$/i,w=/^0o[0-7]+$/i,x=parseInt,C="object"==typeof i.g&&i.g&&i.g.Object===Object&&i.g,j="object"==typeof self&&self&&self.Object===Object&&self,L=C||j||Function("return this")(),B=Object.prototype.toString,$=Math.max,V=Math.min,now=function(){return L.Date.now()};function isObject(s){var o=typeof s;return!!s&&("object"==o||"function"==o)}function toNumber(s){if("number"==typeof s)return s;if(function isSymbol(s){return"symbol"==typeof s||function isObjectLike(s){return!!s&&"object"==typeof s}(s)&&"[object Symbol]"==B.call(s)}(s))return NaN;if(isObject(s)){var o="function"==typeof s.valueOf?s.valueOf():s;s=isObject(o)?o+"":o}if("string"!=typeof s)return 0===s?s:+s;s=s.replace(a,"");var i=_.test(s);return i||w.test(s)?x(s.slice(2),i?2:8):u.test(s)?NaN:+s}s.exports=function debounce(s,o,i){var a,u,_,w,x,C,j=0,L=!1,B=!1,U=!0;if("function"!=typeof s)throw new TypeError("Expected a function");function invokeFunc(o){var i=a,_=u;return a=u=void 0,j=o,w=s.apply(_,i)}function shouldInvoke(s){var i=s-C;return void 0===C||i>=o||i<0||B&&s-j>=_}function timerExpired(){var s=now();if(shouldInvoke(s))return trailingEdge(s);x=setTimeout(timerExpired,function remainingWait(s){var i=o-(s-C);return B?V(i,_-(s-j)):i}(s))}function trailingEdge(s){return x=void 0,U&&a?invokeFunc(s):(a=u=void 0,w)}function debounced(){var s=now(),i=shouldInvoke(s);if(a=arguments,u=this,C=s,i){if(void 0===x)return function leadingEdge(s){return j=s,x=setTimeout(timerExpired,o),L?invokeFunc(s):w}(C);if(B)return x=setTimeout(timerExpired,o),invokeFunc(C)}return void 0===x&&(x=setTimeout(timerExpired,o)),w}return o=toNumber(o)||0,isObject(i)&&(L=!!i.leading,_=(B="maxWait"in i)?$(toNumber(i.maxWait)||0,o):_,U="trailing"in i?!!i.trailing:U),debounced.cancel=function cancel(){void 0!==x&&clearTimeout(x),j=0,a=C=u=x=void 0},debounced.flush=function flush(){return void 0===x?w:trailingEdge(now())},debounced}},20317:s=>{s.exports=function mapToArray(s){var o=-1,i=Array(s.size);return s.forEach((function(s,a){i[++o]=[a,s]})),i}},20334:(s,o,i)=>{"use strict";var a=i(48287).Buffer;class NonError extends Error{constructor(s){super(NonError._prepareSuperMessage(s)),Object.defineProperty(this,"name",{value:"NonError",configurable:!0,writable:!0}),Error.captureStackTrace&&Error.captureStackTrace(this,NonError)}static _prepareSuperMessage(s){try{return JSON.stringify(s)}catch{return String(s)}}}const u=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0}],_=Symbol(".toJSON called"),destroyCircular=({from:s,seen:o,to_:i,forceEnumerable:w,maxDepth:x,depth:C})=>{const j=i||(Array.isArray(s)?[]:{});if(o.push(s),C>=x)return j;if("function"==typeof s.toJSON&&!0!==s[_])return(s=>{s[_]=!0;const o=s.toJSON();return delete s[_],o})(s);for(const[i,u]of Object.entries(s))"function"==typeof a&&a.isBuffer(u)?j[i]="[object Buffer]":"function"!=typeof u&&(u&&"object"==typeof u?o.includes(s[i])?j[i]="[Circular]":(C++,j[i]=destroyCircular({from:s[i],seen:o.slice(),forceEnumerable:w,maxDepth:x,depth:C})):j[i]=u);for(const{property:o,enumerable:i}of u)"string"==typeof s[o]&&Object.defineProperty(j,o,{value:s[o],enumerable:!!w||i,configurable:!0,writable:!0});return j};s.exports={serializeError:(s,o={})=>{const{maxDepth:i=Number.POSITIVE_INFINITY}=o;return"object"==typeof s&&null!==s?destroyCircular({from:s,seen:[],forceEnumerable:!0,maxDepth:i,depth:0}):"function"==typeof s?`[Function: ${s.name||"anonymous"}]`:s},deserializeError:(s,o={})=>{const{maxDepth:i=Number.POSITIVE_INFINITY}=o;if(s instanceof Error)return s;if("object"==typeof s&&null!==s&&!Array.isArray(s)){const o=new Error;return destroyCircular({from:s,seen:[],to_:o,maxDepth:i,depth:0}),o}return new NonError(s)}}},20426:s=>{var o=Object.prototype.hasOwnProperty;s.exports=function baseHas(s,i){return null!=s&&o.call(s,i)}},20575:(s,o,i)=>{"use strict";var a=i(3121);s.exports=function(s){return a(s.length)}},20798:(s,o,i)=>{"use strict";var a,u,_=i(45951),w=i(96794),x=_.process,C=_.Deno,j=x&&x.versions||C&&C.version,L=j&&j.v8;L&&(u=(a=L.split("."))[0]>0&&a[0]<4?1:+(a[0]+a[1])),!u&&w&&(!(a=w.match(/Edge\/(\d+)/))||a[1]>=74)&&(a=w.match(/Chrome\/(\d+)/))&&(u=+a[1]),s.exports=u},20850:(s,o,i)=>{"use strict";s.exports=i(46076)},20999:(s,o,i)=>{var a=i(69302),u=i(36800);s.exports=function createAssigner(s){return a((function(o,i){var a=-1,_=i.length,w=_>1?i[_-1]:void 0,x=_>2?i[2]:void 0;for(w=s.length>3&&"function"==typeof w?(_--,w):void 0,x&&u(i[0],i[1],x)&&(w=_<3?void 0:w,_=1),o=Object(o);++a<_;){var C=i[a];C&&s(o,C,a,w)}return o}))}},21549:(s,o,i)=>{var a=i(22032),u=i(63862),_=i(66721),w=i(12749),x=i(35749);function Hash(s){var o=-1,i=null==s?0:s.length;for(this.clear();++o{var a=i(16547),u=i(43360);s.exports=function copyObject(s,o,i,_){var w=!i;i||(i={});for(var x=-1,C=o.length;++x{var a=i(51873),u=i(37828),_=i(75288),w=i(25911),x=i(20317),C=i(84247),j=a?a.prototype:void 0,L=j?j.valueOf:void 0;s.exports=function equalByTag(s,o,i,a,j,B,$){switch(i){case"[object DataView]":if(s.byteLength!=o.byteLength||s.byteOffset!=o.byteOffset)return!1;s=s.buffer,o=o.buffer;case"[object ArrayBuffer]":return!(s.byteLength!=o.byteLength||!B(new u(s),new u(o)));case"[object Boolean]":case"[object Date]":case"[object Number]":return _(+s,+o);case"[object Error]":return s.name==o.name&&s.message==o.message;case"[object RegExp]":case"[object String]":return s==o+"";case"[object Map]":var V=x;case"[object Set]":var U=1&a;if(V||(V=C),s.size!=o.size&&!U)return!1;var z=$.get(s);if(z)return z==o;a|=2,$.set(s,o);var Y=w(V(s),V(o),a,j,B,$);return $.delete(s),Y;case"[object Symbol]":if(L)return L.call(s)==L.call(o)}return!1}},22032:(s,o,i)=>{var a=i(81042);s.exports=function hashClear(){this.__data__=a?a(null):{},this.size=0}},22225:s=>{var o="\\ud800-\\udfff",i="\\u2700-\\u27bf",a="a-z\\xdf-\\xf6\\xf8-\\xff",u="A-Z\\xc0-\\xd6\\xd8-\\xde",_="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",w="["+_+"]",x="\\d+",C="["+i+"]",j="["+a+"]",L="[^"+o+_+x+i+a+u+"]",B="(?:\\ud83c[\\udde6-\\uddff]){2}",$="[\\ud800-\\udbff][\\udc00-\\udfff]",V="["+u+"]",U="(?:"+j+"|"+L+")",z="(?:"+V+"|"+L+")",Y="(?:['’](?:d|ll|m|re|s|t|ve))?",Z="(?:['’](?:D|LL|M|RE|S|T|VE))?",ee="(?:[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]|\\ud83c[\\udffb-\\udfff])?",ie="[\\ufe0e\\ufe0f]?",ae=ie+ee+("(?:\\u200d(?:"+["[^"+o+"]",B,$].join("|")+")"+ie+ee+")*"),ce="(?:"+[C,B,$].join("|")+")"+ae,le=RegExp([V+"?"+j+"+"+Y+"(?="+[w,V,"$"].join("|")+")",z+"+"+Z+"(?="+[w,V+U,"$"].join("|")+")",V+"?"+U+"+"+Y,V+"+"+Z,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",x,ce].join("|"),"g");s.exports=function unicodeWords(s){return s.match(le)||[]}},22551:(s,o,i)=>{"use strict";var a=i(96540),u=i(69982);function p(s){for(var o="https://reactjs.org/docs/error-decoder.html?invariant="+s,i=1;i