From: Christopher Lott (cl778h) Date: Wed, 23 Aug 2017 22:27:19 +0000 (-0400) Subject: Deliver centralized role management feature X-Git-Tag: v1.3.0~39 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=portal.git;a=commitdiff_plain;h=978dbcf0a196acbafad72fe1e2478ec0e384f02f Deliver centralized role management feature Repair multiple defects also. Revise deployment to use docker-compose. Remove all zip archives. Issue: PORTAL-21, PORTAL-25, PORTAL-28, PORTAL-52, PORTAL-69, PORTAL-74, PORTAL-76, PORTAL-80, PORTAL-82 Change-Id: Ie72fec7d35ba78beb162bba6ed27b2caee340c61 Signed-off-by: Christopher Lott (cl778h) --- diff --git a/deliveries/.env b/deliveries/.env new file mode 100644 index 00000000..fa307685 --- /dev/null +++ b/deliveries/.env @@ -0,0 +1,17 @@ +# Environment settings +# used by docker-compose AND by other shell scripts + +# Host directory with config files +PROJECT_DIR=/PROJECT/OpenSource/UbuntuEP + +# Directory within containers +WEBAPPS_DIR=/opt/apache-tomcat-8.0.37/webapps + +# Following are ALSO used in demo/boot/portal_vm_init.sh +EP_IMG_NAME=portal-apps +DB_IMG_NAME=portal-db +WMS_IMG_NAME=portal-wms +# Tag all images with this +PORTAL_TAG=1.1.0 + +NEXUS_REPO=nexus3.onap.org:10003 diff --git a/deliveries/.gitignore b/deliveries/.gitignore index f12ac3a0..796b96d1 100644 --- a/deliveries/.gitignore +++ b/deliveries/.gitignore @@ -1 +1 @@ -/PROJECT +/build diff --git a/deliveries/Apps_Users_OnBoarding_Script.sql b/deliveries/Apps_Users_OnBoarding_Script.sql index ff3d3e96..2d1adfb5 100644 --- a/deliveries/Apps_Users_OnBoarding_Script.sql +++ b/deliveries/Apps_Users_OnBoarding_Script.sql @@ -345,14 +345,14 @@ select * from fn_role where app_id = (select app_id from fn_app where app_name = ) b ); -- end new -INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (6,'NEWS','http://about.att.com/innovationblog/next_att_labs','What\s Next at AT&T Labs? AI Set to Revolutionize the Network',NULL,NULL,10); -INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (7,'NEWS','http://about.att.com/innovationblog/ecomp_code','Code, Community and Commitment – the 3 Cs of Open Source',NULL,NULL,20); +INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (6,'NEWS','http://about.att.com/innovationblog/next_att_labs','What\'s Next at AT&T Labs? AI Set to Revolutionize the Network',NULL,NULL,10); +INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (7,'NEWS','http://about.att.com/innovationblog/ecomp_code','Code, Community and Commitment - the 3 Cs of Open Source',NULL,NULL,20); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (8,'NEWS','http://about.att.com/story/orange_testing_att_open_source_ecomp_platform.html','Orange Testing AT&Ts Open Source ECOMP Platform for Building Software-Defined Network Capabilities',NULL,NULL,30); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (9,'NEWS', 'http://about.att.com/innovationblog/linux_foundation','Opening up ECOMP: Our Network Operating System for SDN',NULL,NULL,40); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (10,'EVENTS',NULL,'OpenECOMP Launches into Open Source',NULL,'2017-02-14',1); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (11,'IMPORTANTRESOURCES','http://about.att.com/content/dam/snrdocs/ecomp.pdf','ECOMP White Paper',NULL,NULL,1); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (12,'IMPORTANTRESOURCES','https://wiki.onap.org/','ONAP Wiki',NULL,NULL,2); -INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (13,'IMPORTANTRESOURCES','https://wiki.onap.org/display/DW/Portal','ONAP Wiki, Portal',NULL,NULL,3); +INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (13,'IMPORTANTRESOURCES','https://wiki.onap.org/display/DW/Portal','ONAP Wiki for Portal',NULL,NULL,3); INSERT INTO `fn_common_widget_data` (`id`,`CATEGORY`,`HREF`,`TITLE`,`content`,`event_date`,`SORT_ORDER`) VALUES (14,'IMPORTANTRESOURCES','https://wiki.onap.org/display/DW/Development+Guides','ONAP User Guide',NULL,NULL,4); diff --git a/deliveries/Dockerfile.mariadb b/deliveries/Dockerfile.mariadb index 004e7af8..5b0abd51 100644 --- a/deliveries/Dockerfile.mariadb +++ b/deliveries/Dockerfile.mariadb @@ -1,34 +1,28 @@ FROM mariadb:latest -#Author -MAINTAINER Manoop talasila@research.att.com - -ARG SCRIPT_DIR=${SCRIPT_DIR} -ARG SCRIPT_COMMON_DIR=${SCRIPT_COMMON_DIR} +ARG PORTAL_SCRIPT_DIR=${PORTAL_SCRIPT_DIR} ARG SDK_SCRIPT_DIR=${SDK_SCRIPT_DIR} -ARG SDK_COMMON_SCRIPT_DIR=${SDK_COMMON_SCRIPT_DIR} -ARG DBC_COMMON_SCRIPT_DIR=${DBC_COMMON_SCRIPT_DIR} ARG DBC_SCRIPT_DIR=${DBC_SCRIPT_DIR} # constant #Add config file -ADD my.cnf /etc/mysql/my.cnf +COPY my.cnf /etc/mysql/my.cnf #ADD cluster.cnf /etc/mysql/conf.d # Scripts are executed in alphabetical order -# Portal DDL and DML -ADD ${SCRIPT_COMMON_DIR}/EcompPortalDDLMySql_1707_Common.sql docker-entrypoint-initdb.d -ADD ${SCRIPT_DIR}/EcompPortalDDLMySql_1707_OS.sql docker-entrypoint-initdb.d -ADD ${SCRIPT_COMMON_DIR}/EcompPortalDMLMySql_1707_Common.sql docker-entrypoint-initdb.d -ADD ${SCRIPT_DIR}/EcompPortalDMLMySql_1707_OS.sql docker-entrypoint-initdb.d -ADD Apps_Users_OnBoarding_Script.sql docker-entrypoint-initdb.d/EcompPortalDMLMySql_1707_z_apps_users.sql +# Portal DDL and DML at 1710 +COPY ${PORTAL_SCRIPT_DIR}/EcompPortalDDLMySql_1710_Common.sql /docker-entrypoint-initdb.d/ +COPY ${PORTAL_SCRIPT_DIR}/EcompPortalDDLMySql_1710_OS.sql /docker-entrypoint-initdb.d/ +COPY ${PORTAL_SCRIPT_DIR}/EcompPortalDMLMySql_1710_Common.sql /docker-entrypoint-initdb.d/ +COPY ${PORTAL_SCRIPT_DIR}/EcompPortalDMLMySql_1710_OS.sql /docker-entrypoint-initdb.d/ +COPY Apps_Users_OnBoarding_Script.sql /docker-entrypoint-initdb.d/EcompPortalDMLMySql_1710_z_apps_users.sql -# SDK App DDL and DML -ADD ${SDK_COMMON_SCRIPT_DIR}/EcompSdkDDLMySql_1707_Common.sql docker-entrypoint-initdb.d -ADD ${SDK_SCRIPT_DIR}/EcompSdkDDLMySql_1707_OS.sql docker-entrypoint-initdb.d -ADD ${SDK_COMMON_SCRIPT_DIR}/EcompSdkDMLMySql_1707_Common.sql docker-entrypoint-initdb.d -ADD ${SDK_SCRIPT_DIR}/EcompSdkDMLMySql_1707_OS.sql docker-entrypoint-initdb.d +# SDK App DDL and DML unchanged since 1707 +COPY ${SDK_SCRIPT_DIR}/EcompSdkDDLMySql_1707_Common.sql /docker-entrypoint-initdb.d/ +COPY ${SDK_SCRIPT_DIR}/EcompSdkDDLMySql_1707_OS.sql /docker-entrypoint-initdb.d/ +COPY ${SDK_SCRIPT_DIR}/EcompSdkDMLMySql_1707_Common.sql /docker-entrypoint-initdb.d/ +COPY ${SDK_SCRIPT_DIR}/EcompSdkDMLMySql_1707_OS.sql /docker-entrypoint-initdb.d/ -# DBC App combined DDL/DML, built by os_build_febe.sh -ADD ${DBC_SCRIPT_DIR}/dbca-complete-mysql-1707-os.sql docker-entrypoint-initdb.d +# DBC App combined DDL/DML, built by script +COPY ${DBC_SCRIPT_DIR}/dbca-complete-mysql-1707-os.sql /docker-entrypoint-initdb.d/ diff --git a/deliveries/Dockerfile.portalapps b/deliveries/Dockerfile.portalapps index 3e295e8f..c9fab4db 100644 --- a/deliveries/Dockerfile.portalapps +++ b/deliveries/Dockerfile.portalapps @@ -1,7 +1,10 @@ # Dockerfile for image with ONAP applications: # Portal app, Portal-SDK app, Portal-DBC app. -FROM openjdk:8-jdk +# Yields an image 823 MB +FROM frolvlad/alpine-oraclejdk8:slim +# Yields an image 1.4 GB +# FROM openjdk:8-jdk # Arguments are supplied by build.sh script # the defaults below only support testing @@ -12,21 +15,28 @@ ARG DBC_WAR=build/dmaap-bc-app-os.war ARG HTTP_PROXY ARG HTTPS_PROXY -# This is just a variable, never passed in -ARG TOMCATHOME=/opt/apache-tomcat-8.0.37 +# Just variables, never passed in +ARG TOMCAT=apache-tomcat-8.0.37 +ARG TOMCATTAR=${TOMCAT}.tar.gz +ARG TOMCATHOME=/opt/${TOMCAT} ENV http_proxy $HTTP_PROXY ENV https_proxy $HTTPS_PROXY RUN if [ ! -z ${HTTP_PROXY} ]; then echo "Acquire::http::proxy \"${HTTP_PROXY}\";" >> /etc/apt/apt.conf; fi && \ if [ ! -z ${HTTPS_PROXY} ]; then echo "Acquire::https::proxy \"${HTTPS_PROXY}\";" >> /etc/apt/apt.conf; fi -# Install Tomcat; curl is already part of this image +# Install the wait script +COPY wait-for.sh / + +# Install Tomcat. This image already has curl. WORKDIR /tmp -RUN curl -s -O https://archive.apache.org/dist/tomcat/tomcat-8/v8.0.37/bin/apache-tomcat-8.0.37.tar.gz -RUN tar -xzf apache-tomcat-8.0.37.tar.gz +RUN wget -q http://archive.apache.org/dist/tomcat/tomcat-8/v8.0.37/bin/apache-tomcat-8.0.37.tar.gz +RUN tar -xzf ${TOMCATTAR} +RUN rm ${TOMCATTAR} # Remove manager and sample apps -RUN rm -fr apache-tomcat-8.0.37/webapps/[a-z]* -RUN mv apache-tomcat-8.0.37 /opt +RUN rm -fr ${TOMCAT}/webapps/[a-z]* +RUN mkdir -p /opt +RUN mv ${TOMCAT} /opt WORKDIR ${TOMCATHOME}/webapps RUN mkdir ECOMPPORTAL && mkdir ECOMPSDKAPP && mkdir ECOMPDBCAPP @@ -46,9 +56,12 @@ RUN cd ECOMPDBCAPP && unzip -q *.war && rm *.war VOLUME ${TOMCATHOME}/logs +# Switch back to root +WORKDIR / + # Define commonly used ENV variables ENV PATH $PATH:$JAVA_HOME/bin:${TOMCATHOME}/bin -COPY configure-and-run.sh / +COPY start-apps-cmd.sh / # Define default command. -CMD ["/configure-and-run.sh"] +CMD /start-apps-cmd.sh diff --git a/deliveries/Dockerfile.widgetms b/deliveries/Dockerfile.widgetms new file mode 100644 index 00000000..16bf60b1 --- /dev/null +++ b/deliveries/Dockerfile.widgetms @@ -0,0 +1,18 @@ +# Large image +# FROM openjdk:8-jdk +# Very small image +FROM frolvlad/alpine-oraclejdk8:slim + +# Arguments are supplied by build script; +# the defaults below only support testing +ARG WMS_JAR=build/widget-ms.jar +# Launch script +COPY start-wms-cmd.sh / +# Wait script, which depends on nc +COPY wait-for.sh / +# Onejar +COPY ${WMS_JAR} /app.jar +RUN sh -c 'touch /app.jar' +VOLUME /tmp +ENV JAVA_OPTS="" +CMD /start-wms-cmd.sh diff --git a/deliveries/README.md b/deliveries/README.md index bc9bc3fe..99832c8e 100644 --- a/deliveries/README.md +++ b/deliveries/README.md @@ -1 +1,6 @@ - "moved insert statement to fn_common_widget_data table from EcompPortalDMLMySql_1707_OS.sql to Apps_Users_OnBoarding_Script.sql, the Onboard script in deliveries folder". +This directory has configuration files for building docker images, +and management files for starting and stopping docker containers. + +The Apps_Users_OnBoarding_Script.sql file has data for ONAP demo deployments: +it adds users and applications so the Portal app has meaningful content on +startup. These were moved from script EcompPortalDMLMySql_1707_OS.sql. diff --git a/deliveries/build_portalapps_dockers.sh b/deliveries/build_portalapps_dockers.sh index a45e55cc..ead31e82 100755 --- a/deliveries/build_portalapps_dockers.sh +++ b/deliveries/build_portalapps_dockers.sh @@ -8,16 +8,9 @@ # Stop on error; show output set -e -x -# For debugging only bcox the FE build takes a long time -SKIPFE=N -if [ $# -gt 0 -a "$1" == "skipfe" ] ; then - echo "Skipping Portal-FE build step" - SKIPFE=Y -fi - -# Establish environment variables -echo "Set variables" -source $(dirname $0)/os_settings.sh +# This reuses the docker-compose file +echo "Set image tag name variables" +source $(dirname $0)/.env # Work standalone AND in the ONAP Jenkins. # Pick up Jenkins settings for this script. @@ -25,70 +18,91 @@ source $(dirname $0)/os_settings.sh if [ -n "$MVN" ]; then export MVN="${MVN} -B -gs ${GLOBAL_SETTINGS_FILE} -s ${SETTINGS_FILE}" else - MVN=mvn + # Force refresh of snapshots + MVN="mvn -B -U" fi # This expects to start in the deliveries folder; make sure -DOCKERFILE=Dockerfile.portalapps -if [ ! -f $DOCKERFILE ] ; then - echo "Failed to find expected file; must start in deliveries folder" +PORTAL_DOCKERFILE=Dockerfile.portalapps +if [ ! -f $PORTAL_DOCKERFILE ] ; then + echo "Failed to find file ${PORTAL_DOCKERFILE}; must start in deliveries folder; exiting" exit 1 fi -# Establish directories and variables +# Store directory names as variables +# This is the Docker Project area. DELIV="$(pwd)" -# Relative path of temp directory -BUILD="build" -# Absolute path of temp directory -OUT=$DELIV/$BUILD -if [ $SKIPFE == "Y" ]; then - echo "Skipping clean/recreate of $OUT" -else - rm -fr $OUT - mkdir $OUT -fi -# parent directory +# parent directory, for finding source projects cd .. BASE="$(pwd)" - -# Copy DDL/DML to required directories (old scripts use long path /PROJECT/...) cd $DELIV -rm -fr PROJECT + +# Relative path of temp directory +BUILD_REL="build" +# Absolute path of temp directory +BUILD_ABS=$DELIV/$BUILD_REL +rm -fr $BUILD_REL +mkdir $BUILD_REL + +# Copy DDL/DML to required directories + +# RELATIVE PATHS to local directories with database scripts +# bcos Docker looks within this build area only +SCR_BASE=$BUILD_REL/scripts +PORTAL_SCRIPT_DIR=$SCR_BASE/ecomp-portal-DB-os +SDK_SCRIPT_DIR=$SCR_BASE/epsdk-app-os +DBC_SCRIPT_DIR=$SCR_BASE/dbca-os +mkdir -p ${PORTAL_SCRIPT_DIR} ${SDK_SCRIPT_DIR} ${DBC_SCRIPT_DIR} + # copy over DB scripts for the dockerfiles -# forgive the ugly trick with the .. at end. -mkdir -p ${SCRIPT_COMMON_DIR} && cp -r $BASE/ecomp-portal-DB-common ${SCRIPT_COMMON_DIR}/.. -mkdir -p ${SCRIPT_DIR} && cp -r $BASE/ecomp-portal-DB-os ${SCRIPT_DIR}/.. -mkdir -p ${SDK_COMMON_SCRIPT_DIR} && cp -r $BASE/sdk/ecomp-sdk/epsdk-app-common/db-scripts ${SDK_COMMON_SCRIPT_DIR}/.. -mkdir -p ${SDK_SCRIPT_DIR} && cp -r $BASE/sdk/ecomp-sdk/epsdk-app-os/db-scripts ${SDK_SCRIPT_DIR}/.. -# Build complete database script for DBC -DBCA_OPEN_SD=$BASE/dmaapbc/dcae_dmaapbc_webapp/dbca-os/db-scripts -DBCA_COMM_SD=$BASE/dmaapbc/dcae_dmaapbc_webapp/dbca-common/db-scripts -# Old scripts expect this path -mkdir -p $DBC_SCRIPT_DIR -cat $DBCA_OPEN_SD/dbca-create-mysql-1707-os.sql $DBCA_COMM_SD/dbca-ddl-mysql-1707-common.sql $DBCA_OPEN_SD/dbca-dml-mysql-1707-os.sql > $DBC_SCRIPT_DIR/dbca-complete-mysql-1707-os.sql - -cd $BASE/ecomp-portal-BE-common +# Portal +cp $BASE/ecomp-portal-DB-common/*.sql ${PORTAL_SCRIPT_DIR} +cp $BASE/ecomp-portal-DB-os/*.sql ${PORTAL_SCRIPT_DIR} +# SDK app +cp $BASE/sdk/ecomp-sdk/epsdk-app-common/db-scripts/*.sql ${SDK_SCRIPT_DIR} +cp $BASE/sdk/ecomp-sdk/epsdk-app-os/db-scripts/*.sql ${SDK_SCRIPT_DIR} +# DBC app +cp $BASE/dmaapbc/dcae_dmaapbc_webapp/dbca-common/db-scripts/*.sql ${DBC_SCRIPT_DIR} +cp $BASE/dmaapbc/dcae_dmaapbc_webapp/dbca-os/db-scripts/*.sql ${DBC_SCRIPT_DIR} +# Assemble a script with "use" at the top. +cat $DBC_SCRIPT_DIR/dbca-create-mysql-1707-os.sql $DBC_SCRIPT_DIR/dbca-ddl-mysql-1707-common.sql $DBC_SCRIPT_DIR/dbca-dml-mysql-1707-os.sql > $DBC_SCRIPT_DIR/dbca-complete-mysql-1707-os.sql + +# build database docker +DB_DOCKER_CMD=" + docker build -t ${DB_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS} + --build-arg PORTAL_SCRIPT_DIR=${PORTAL_SCRIPT_DIR} + --build-arg SDK_SCRIPT_DIR=${SDK_SCRIPT_DIR} + --build-arg DBC_SCRIPT_DIR=${DBC_SCRIPT_DIR} + -f Dockerfile.mariadb . +" +echo "Build mariadb docker image" +$DB_DOCKER_CMD + +echo "Build all jar and war files in Portal" +cd $BASE ${MVN} clean install +echo "Copy Portal app BE" cd $BASE/ecomp-portal-BE-os -${MVN} clean package -cp target/ecompportal-be-os.war $OUT +cp target/ecompportal-be-os.war $BUILD_ABS +echo "Copy Portal app FE" cd $BASE/ecomp-portal-FE-os/ -if [ $SKIPFE == "Y" ]; then - echo "Skipping MVN in $(pwd)" -else - ${MVN} clean package - cp -r dist/public $OUT -fi +cp -r dist/public $BUILD_ABS + +echo "Copy Portal widget-ms" +cd $BASE/ecomp-portal-widget-ms +cp widget-ms/target/widget-ms.jar $BUILD_ABS +echo "Build and copy Portal-SDK app" cd $BASE/sdk/ecomp-sdk/epsdk-app-os ${MVN} clean package -cp target/epsdk-app-os.war $OUT +cp target/epsdk-app-os.war $BUILD_ABS +echo "Build and copy Portal-DBC app" cd $BASE/dmaapbc/dcae_dmaapbc_webapp ${MVN} clean package -cp dbca-os/target/dmaap-bc-app-os.war $OUT +cp dbca-os/target/dmaap-bc-app-os.war $BUILD_ABS PROXY_ARGS="" if [ $HTTP_PROXY ]; then @@ -98,19 +112,26 @@ if [ $HTTPS_PROXY ]; then PROXY_ARGS+=" --build-arg HTTPS_PROXY=${HTTPS_PROXY}" fi -# build portal docker +echo "Build portal docker image" cd $DELIV PORTAL_DOCKER_CMD=" - docker build -t ${EP_IMG_NAME} ${PROXY_ARGS} - --build-arg FE_DIR=$BUILD/public - --build-arg PORTAL_WAR=$BUILD/ecompportal-be-os.war - --build-arg SDK_WAR=$BUILD/epsdk-app-os.war - --build-arg DBC_WAR=$BUILD/dmaap-bc-app-os.war - -f $DOCKERFILE . + docker build -t ${EP_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS} + --build-arg FE_DIR=$BUILD_REL/public + --build-arg PORTAL_WAR=$BUILD_REL/ecompportal-be-os.war + --build-arg SDK_WAR=$BUILD_REL/epsdk-app-os.war + --build-arg DBC_WAR=$BUILD_REL/dmaap-bc-app-os.war + -f $PORTAL_DOCKERFILE . " -echo "Invoking portal docker build" $PORTAL_DOCKER_CMD -# Build widget-ms docker -cd $BASE/ecomp-portal-widget-ms -${MVN} package docker:build +echo "Bbuild widget-ms docker image" +WMS_DOCKER_CMD=" + docker build -t ${WMS_IMG_NAME}:${PORTAL_TAG} ${PROXY_ARGS} + --build-arg WMS_JAR=$BUILD_REL/widget-ms.jar + -f Dockerfile.widgetms . +" +$WMS_DOCKER_CMD + +# For ease of debugging, leave the build dir +# echo "Cleaning up" +# rm -fr $BUILD_REL diff --git a/deliveries/createMaria.sh b/deliveries/createMaria.sh deleted file mode 100755 index 84e6bb38..00000000 --- a/deliveries/createMaria.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -# Stop on errors; show output -set -e -x - -source $(dirname $0)/os_settings.sh - -echo ${SCRIPT_DIR} - -docker build -t ${DB_IMG_NAME} --build-arg SCRIPT_DIR="${SCRIPT_DIR}" --build-arg SDK_SCRIPT_DIR="${SDK_SCRIPT_DIR}" --build-arg DBC_SCRIPT_DIR="${DBC_SCRIPT_DIR}" --build-arg SCRIPT_COMMON_DIR="${SCRIPT_COMMON_DIR}" --build-arg SDK_COMMON_SCRIPT_DIR="${SDK_COMMON_SCRIPT_DIR}" --build-arg DBC_COMMON_SCRIPT_DIR="${DBC_COMMON_SCRIPT_DIR}" -f ./Dockerfile.mariadb . diff --git a/deliveries/dbstart.sh b/deliveries/dbstart.sh deleted file mode 100755 index c76cb391..00000000 --- a/deliveries/dbstart.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -#docker create --name ${DB_VOL_NAME} -v /var/lib/mysql mariadb; - -echo "Running docker image ${DB_IMG_NAME} as name ${DB_CONT_NAME} with volume ${DB_VOL_NAME}" -docker run -d --volumes-from ${DB_VOL_NAME} -p 3306:3306 -e MYSQL_ROOT_PASSWORD=Aa123456 --net=host --name ${DB_CONT_NAME} ${DB_IMG_NAME}; diff --git a/deliveries/dbstop.sh b/deliveries/dbstop.sh deleted file mode 100755 index 9c5b73a7..00000000 --- a/deliveries/dbstop.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -echo "Stopping docker container named ${DB_CONT_NAME}" -docker stop ${DB_CONT_NAME} -echo "Removing docker container named ${DB_CONT_NAME}" -docker rm ${DB_CONT_NAME} diff --git a/deliveries/docker-compose.yml b/deliveries/docker-compose.yml new file mode 100644 index 00000000..1ea2bb67 --- /dev/null +++ b/deliveries/docker-compose.yml @@ -0,0 +1,83 @@ +# docker-compose for ONAP portal containers: database, microservice, portal apps. +# Only exposes the portal apps on host network, not the database or WMS. +# Works in multiple environments; does not pull from a Nexus repository. +# Relies on .env file in current directory. + +version: '2.0' + +services: + + # Config files may use hostname "portal-db" + portal-db: + image: ${DB_IMG_NAME}:${PORTAL_TAG} + environment: + MYSQL_ROOT_PASSWORD: 'Aa123456' + expose: + - 3306 + volumes: + # Just specify a path and let the Engine create a volume + - /var/lib/mysql + logging: + driver: json-file + + # An environment variable here CAN override the database URL; + # instead the value in the config file uses hostname from above + portal-wms: + image: ${WMS_IMG_NAME}:${PORTAL_TAG} + expose: + - 8082 + links: + - portal-db + depends_on: + - portal-db + volumes: + - ${PROJECT_DIR}/etc/ECOMPWIDGETMS/application.properties:/application.properties + command: + - /wait-for.sh + - -t + - "60" + - portal-db:3306 + - -- + - /start-wms-cmd.sh + logging: + driver: json-file + + # Environment variables here CANNOT override the database URL because + # two apps use identical configuration keys with different values + portal-apps: + image: ${EP_IMG_NAME}:${PORTAL_TAG} + expose: + - 8989 + ports: + - 8989:8080 + - 8010:8009 + - 8006:8005 + links: + - portal-db + - portal-wms + depends_on: + - portal-db + - portal-wms + volumes: + - ${PROJECT_DIR}/etc/ECOMPPORTALAPP/system.properties:${WEBAPPS_DIR}/ECOMPPORTAL/WEB-INF/conf/system.properties + - ${PROJECT_DIR}/etc/ECOMPPORTALAPP/fusion.properties:${WEBAPPS_DIR}/ECOMPPORTAL/WEB-INF/fusion/conf/fusion.properties + - ${PROJECT_DIR}/etc/ECOMPPORTALAPP/portal.properties:${WEBAPPS_DIR}/ECOMPPORTAL/WEB-INF/classes/portal.properties + - ${PROJECT_DIR}/etc/ECOMPPORTALAPP/openid-connect.properties:${WEBAPPS_DIR}/ECOMPPORTAL/WEB-INF/classes/openid-connect.properties + - ${PROJECT_DIR}/etc/ECOMPPORTALAPP/logback.xml:${WEBAPPS_DIR}/ECOMPPORTAL/WEB-INF/classes/logback.xml + - ${PROJECT_DIR}/etc/ECOMPSDKAPP/fusion.properties:${WEBAPPS_DIR}/ECOMPSDKAPP/WEB-INF/fusion/conf/fusion.properties + - ${PROJECT_DIR}/etc/ECOMPSDKAPP/system.properties:${WEBAPPS_DIR}/ECOMPSDKAPP/WEB-INF/conf/system.properties + - ${PROJECT_DIR}/etc/ECOMPSDKAPP/portal.properties:${WEBAPPS_DIR}/ECOMPSDKAPP/WEB-INF/classes/portal.properties + - ${PROJECT_DIR}/etc/ECOMPDBCAPP/system.properties:${WEBAPPS_DIR}/ECOMPDBCAPP/WEB-INF/conf/system.properties + - ${PROJECT_DIR}/etc/ECOMPDBCAPP/portal.properties:${WEBAPPS_DIR}/ECOMPDBCAPP/WEB-INF/classes/portal.properties + - ${PROJECT_DIR}/etc/ECOMPDBCAPP/dbcapp.properties:${WEBAPPS_DIR}/ECOMPDBCAPP/WEB-INF/dbcapp/dbcapp.properties + - ${PROJECT_DIR}/etc/ECOMPDBCAPP/fusion.properties:${WEBAPPS_DIR}/ECOMPDBCAPP/WEB-INF/fusion/conf/fusion.properties + - ${PROJECT_DIR}/portal-apps-logs:/opt/apache-tomcat-8.0.37/logs + command: + - /wait-for.sh + - -t + - "60" + - portal-db:3306 + - -- + - /start-apps-cmd.sh + logging: + driver: json-file diff --git a/deliveries/etc.zip b/deliveries/etc.zip deleted file mode 100644 index 67a65b27..00000000 Binary files a/deliveries/etc.zip and /dev/null differ diff --git a/deliveries/new_start.sh b/deliveries/new_start.sh deleted file mode 100755 index cffcda9b..00000000 --- a/deliveries/new_start.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -BASEDIR=/PROJECT/OpenSource/UbuntuEP -PORTALDIR=/opt/apache-tomcat-8.0.37/webapps/ECOMPPORTAL -SDKAPPDIR=/opt/apache-tomcat-8.0.37/webapps/ECOMPSDKAPP -DBCAPPDIR=/opt/apache-tomcat-8.0.37/webapps/ECOMPDBCAPP -PORTALPROPDIR=ECOMPPORTALAPP -SDKAPPPROPDIR=ECOMPSDKAPP -DBCAPPPROPDIR=ECOMPDBCAPP -#docker rm ep_1610 -echo "Running docker image ${EP_IMG_NAME} as name ${EP_CONT_NAME}" -docker run -d --name ${EP_CONT_NAME} \ --p 8989:8080 -p 8010:8009 -p 8006:8005 \ --v ${BASEDIR}/etc/${PORTALPROPDIR}/system.properties:${PORTALDIR}/WEB-INF/conf/system.properties \ --v ${BASEDIR}/etc/${PORTALPROPDIR}/fusion.properties:${PORTALDIR}/WEB-INF/fusion/conf/fusion.properties \ --v ${BASEDIR}/etc/${PORTALPROPDIR}/portal.properties:${PORTALDIR}/WEB-INF/classes/portal.properties \ --v ${BASEDIR}/etc/${PORTALPROPDIR}/openid-connect.properties:${PORTALDIR}/WEB-INF/classes/openid-connect.properties \ --v ${BASEDIR}/etc/${SDKAPPPROPDIR}/fusion.properties:${SDKAPPDIR}/WEB-INF/fusion/conf/fusion.properties \ --v ${BASEDIR}/etc/${SDKAPPPROPDIR}/system.properties:${SDKAPPDIR}/WEB-INF/conf/system.properties \ --v ${BASEDIR}/etc/${SDKAPPPROPDIR}/portal.properties:${SDKAPPDIR}/WEB-INF/classes/portal.properties \ --v ${BASEDIR}/etc/${DBCAPPPROPDIR}/system.properties:${DBCAPPDIR}/WEB-INF/conf/system.properties \ --v ${BASEDIR}/etc/${DBCAPPPROPDIR}/portal.properties:${DBCAPPDIR}/WEB-INF/classes/portal.properties \ --v ${BASEDIR}/etc/${DBCAPPPROPDIR}/dbcapp.properties:${DBCAPPDIR}/WEB-INF/dbcapp/dbcapp.properties \ --v ${BASEDIR}/etc/${DBCAPPPROPDIR}/fusion.properties:${DBCAPPDIR}/WEB-INF/fusion/conf/fusion.properties \ --v ${BASEDIR}/log:/opt/apache-tomcat-8.0.37/logs \ -${EP_IMG_NAME} diff --git a/deliveries/new_stop.sh b/deliveries/new_stop.sh deleted file mode 100755 index 9193e285..00000000 --- a/deliveries/new_stop.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -echo "Stopping docker container named ${EP_CONT_NAME}" -docker stop ${EP_CONT_NAME} -echo "Removing docker container named ${EP_CONT_NAME}" -docker rm ${EP_CONT_NAME} diff --git a/deliveries/os_Dockerfile b/deliveries/os_Dockerfile deleted file mode 100644 index 130244da..00000000 --- a/deliveries/os_Dockerfile +++ /dev/null @@ -1,84 +0,0 @@ -# Pull base image. -#FROM ubuntu-openjdk-8-jdk - -FROM ubuntu:14.04 - -ARG HTTP_PROXY=${HTTP_PROXY} -ARG HTTPS_PROXY=${HTTPS_PROXY} - -ENV http_proxy $HTTP_PROXY -ENV https_proxy $HTTPS_PROXY - -RUN if [ ! -z ${HTTP_PROXY} ]; then echo "Acquire::http::proxy \"${HTTP_PROXY}\";" >> /etc/apt/apt.conf; fi && \ - if [ ! -z ${HTTPS_PROXY} ]; then echo "Acquire::https::proxy \"${HTTPS_PROXY}\";" >> /etc/apt/apt.conf; fi - -# Install the python script required for "add-apt-repository" -RUN apt-get update && apt-get install -y software-properties-common - -# Sets language to UTF8 : this works in pretty much all cases -ENV LANG en_US.UTF-8 -RUN locale-gen $LANG - -# Setup the openjdk 8 repo -RUN add-apt-repository ppa:openjdk-r/ppa - -# Install java8 -RUN apt-get update && apt-get install -y --force-yes openjdk-8-jdk - -# Setup JAVA_HOME, this is useful for docker commandline -ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/ -RUN export JAVA_HOME - -# Show java version (for debugging) -# RUN java -version - -RUN apt-get update -RUN apt-get install -y curl -# Install Tomcat -RUN cd /tmp && curl -O https://archive.apache.org/dist/tomcat/tomcat-8/v8.0.37/bin/apache-tomcat-8.0.37.tar.gz -RUN tar -xzf /tmp/apache-tomcat-8.0.37.tar.gz -RUN mv apache-tomcat-8.0.37 /opt - -# Define working directory. -WORKDIR /opt/apache-tomcat-8.0.37/bin - -# Define commonly used ENV variables -ENV PATH $PATH:$JAVA_HOME/bin:/opt/apache-tomcat-8.0.37/bin - -VOLUME /opt/apache-tomcat-8.0.37/logs - -ARG VERSION=${VERSION:-1.1.0} -#LABEL Version=${VERSION} -ARG SDK_DIR=${SDK_DIR} -ARG FE_DIR=${FE_DIR} -ARG PORTAL_SDK_DIR=${PORTAL_SDK_DIR} -ARG PORTAL_DBC_DIR=${PORTAL_DBC_DIR} -# Set up variables: -ENV TOMCATHOME /opt/apache-tomcat-8.0.37 -ENV PORTALHOME /PROJECT/APPS/ECOMPPORTAL/ECOMPPORTALAPP -ENV PORTALSDKHOME /PROJECT/APPS/ECOMPPORTAL/ECOMPSDKAPP -ENV PORTALDBCHOME /PROJECT/APPS/ECOMPPORTAL/ECOMPDBCAPP -# Install Common Software,Git,Apache -RUN mkdir -p $PORTALHOME && mkdir -p $PORTALSDKHOME && mkdir -p $PORTALDBCHOME - -COPY ${SDK_DIR} ${PORTALHOME}/ -# step 33 -COPY ${PORTAL_SDK_DIR} ${PORTALSDKHOME}/ -COPY ${PORTAL_DBC_DIR} ${PORTALDBCHOME}/ - -RUN ln -s ${PORTALHOME} ${TOMCATHOME}/webapps/ECOMPPORTAL && ln -s ${PORTALSDKHOME} ${TOMCATHOME}/webapps/ECOMPSDKAPP && ln -s ${PORTALDBCHOME} ${TOMCATHOME}/webapps/ECOMPDBCAPP - - -# Define working directory. -WORKDIR ${TOMCATHOME}/bin -VOLUME ${TOMCATHOME}/logs -# Define commonly used ENV variables -ENV PATH $PATH:$JAVA_HOME/bin:${TOMCATHOME}/bin -COPY configure-and-run.sh /PROJECT/OpenSource/UbuntuEP/ - -#RUN cp -r ${FE_DIR}/dist/public ${PORTALHOME}/public - -COPY ${FE_DIR}/dist/public ${PORTALHOME}/public -# Define default command. -#CMD ["bash"] -CMD ["/PROJECT/OpenSource/UbuntuEP/configure-and-run.sh"] diff --git a/deliveries/os_build_febe.sh b/deliveries/os_build_febe.sh deleted file mode 100755 index d9a59bf1..00000000 --- a/deliveries/os_build_febe.sh +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash -# Builds docker with three webapps: portal app, portal-sdk app, dbc app -# Stop on error; show output -set -e -x - -source $(dirname $0)/os_settings.sh - -# Work standalone and in Jenkins. -# Pick up Jenkins settings for this script. -# Use -B for batch operation to skip download progress output -if [ -n "$MVN" ]; then - export MVN="${MVN} -gs ${GLOBAL_SETTINGS_FILE} -s ${SETTINGS_FILE} -B" -else - MVN=mvn -fi - -CURRENTDIR="$(pwd)" - -# install ecomp portal -rm -rf $CURRENTDIR/$WORKINGDIR -mkdir $CURRENTDIR/$WORKINGDIR -cd $CURRENTDIR/$WORKINGDIR -SOURCEDIR=$CURRENTDIR/$WORKINGDIR/Source -mkdir $SOURCEDIR -cd $SOURCEDIR -PROJECTDIR=$SOURCEDIR/ecomp-portal-core -mkdir $PROJECTDIR - -#create project dir -#copy FE and BE -cd $CURRENTDIR -cd .. - -cp -r ecomp-portal-FE-common $PROJECTDIR/ecomp-portal-FE-common -cp -r ecomp-portal-FE-os $PROJECTDIR/ecomp-portal-FE-os -cp -r ecomp-portal-BE-common $PROJECTDIR/ecomp-portal-BE-common -cp -r ecomp-portal-BE-os $PROJECTDIR/ecomp-portal-BE-os -cp -r ecomp-portal-DB-common $PROJECTDIR/ecomp-portal-DB-common -cp -r ecomp-portal-DB-os $PROJECTDIR/ecomp-portal-DB-os -cp -r sdk/ecomp-sdk $PROJECTDIR/ecomp-sdk - -cd $PROJECTDIR/ecomp-portal-BE-common -${MVN} install - -cd $PROJECTDIR/ecomp-portal-BE-os -${MVN} install - -cd $PROJECTDIR/ecomp-portal-FE-os/ -${MVN} install - -cd $PROJECTDIR/ecomp-sdk/epsdk-app-os -${MVN} install - -# now install DBC app -cd $SOURCEDIR -DBCDIR=$SOURCEDIR/ST_DBPA -mkdir $DBCDIR -#copy DBC project -cd $CURRENTDIR -cd .. -cp -r dmaapbc/dcae_dmaapbc_webapp $DBCDIR/dcae_dmaapbc_webapp -cd $DBCDIR/dcae_dmaapbc_webapp -${MVN} install -cd dbca-os/target -mv dmaap-bc-app-os ep-dbc-app - -# Build complete database script in the "OS" script area -cd ../db-scripts -cat dbca-create-mysql-1707-os.sql ../../dbca-common/db-scripts/dbca-ddl-mysql-1707-common.sql dbca-dml-mysql-1707-os.sql > dbca-complete-mysql-1707-os.sql - -# install into docker -cd $CURRENTDIR - -PROXY_ARGS="" -if [ $HTTP_PROXY ]; then - PROXY_ARGS+="--build-arg HTTP_PROXY=${HTTP_PROXY}" -fi -if [ $HTTPS_PROXY ]; then - PROXY_ARGS+=" --build-arg HTTPS_PROXY=${HTTPS_PROXY}" -fi - -EXEC_CMD="docker build -t ${IMGNAME} ${PROXY_ARGS} --build-arg VERSION=${VERSION} --build-arg PORTAL_SDK_DIR=${PORTAL_SDK_DIR} --build-arg SDK_DIR=${SDK_DIR} --build-arg FE_DIR=${FE_DIR} --build-arg PORTAL_DBC_DIR=${PORTAL_DBC_DIR} -f ./os_Dockerfile ." -echo $EXEC_CMD -$EXEC_CMD diff --git a/deliveries/os_docker_base.sh b/deliveries/os_docker_base.sh new file mode 100755 index 00000000..2bdfea68 --- /dev/null +++ b/deliveries/os_docker_base.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Builds and pushes versions of Portal images +# Invoked by scripts that set VERSION and LATEST + +# be verbose +set -x + +if [ -z "$VERSION" ]; then + echo "VERSION not set" + exit 1 +fi +if [ -z "$LATEST" ]; then + echo "LATEST not set" + exit 1 +fi + +# Establish environment variables +source $(dirname $0)/.env + +# Build the containers +./build_portalapps_dockers.sh + +APPS_VERSION="${NEXUS_REPO}/openecomp/${EP_IMG_NAME}:${VERSION}" +DB_VERSION="${NEXUS_REPO}/openecomp/${DB_IMG_NAME}:${VERSION}" +WMS_VERSION="${NEXUS_REPO}/openecomp/${WMS_IMG_NAME}:${VERSION}" + +APPS_LATEST="${NEXUS_REPO}/openecomp/${EP_IMG_NAME}:${LATEST}" +DB_LATEST="${NEXUS_REPO}/openecomp/${DB_IMG_NAME}:${LATEST}" +WMS_LATEST="${NEXUS_REPO}/openecomp/${WMS_IMG_NAME}:${LATEST}" + +# tag versions +docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APPS_VERSION} +docker tag ${EP_IMG_NAME}:${PORTAL_TAG} ${APPS_LATEST} + +docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_VERSION} +docker tag ${DB_IMG_NAME}:${PORTAL_TAG} ${DB_LATEST} + +docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_VERSION} +docker tag ${WMS_IMG_NAME}:${PORTAL_TAG} ${WMS_LATEST} + +# push +docker push ${APPS_VERSION} +docker push ${APPS_LATEST} + +docker push ${DB_VERSION} +docker push ${DB_LATEST} + +docker push ${WMS_VERSION} +docker push ${WMS_LATEST} diff --git a/deliveries/os_docker_push.sh b/deliveries/os_docker_push.sh index 2ec6de42..eb663b83 100755 --- a/deliveries/os_docker_push.sh +++ b/deliveries/os_docker_push.sh @@ -1,40 +1,11 @@ #!/bin/bash +# Builds and pushes SNAPSHOT versions of Portal images -# Establish environment variables -source $(dirname $0)/os_settings.sh - -./run.sh - -REPO="nexus3.onap.org:10003" +# be verbose +set -x TIMESTAMP=$(date +%C%y%m%dT%H%M%S) -VERSION="1.1.0-SNAPSHOT-${TIMESTAMP}" -LATEST="latest" - -APPS_VERSION="${REPO}/openecomp/${EP_TAG_NAME}:${VERSION}" -DB_VERSION="${REPO}/openecomp/${DB_TAG_NAME}:${VERSION}" -WMS_VERSION="${REPO}/openecomp/${WMS_TAG_NAME}:${VERSION}" - -APPS_LATEST="${REPO}/openecomp/${EP_TAG_NAME}:${LATEST}" -DB_LATEST="${REPO}/openecomp/${DB_TAG_NAME}:${LATEST}" -WMS_LATEST="${REPO}/openecomp/${WMS_TAG_NAME}:${LATEST}" - -# tag versions -docker tag ${EP_IMG_NAME} ${APPS_VERSION} -docker tag ${EP_IMG_NAME} ${APPS_LATEST} - -docker tag ${DB_IMG_NAME} ${DB_VERSION} -docker tag ${DB_IMG_NAME} ${DB_LATEST} - -docker tag ${WMS_IMG_NAME} ${WMS_VERSION} -docker tag ${WMS_IMG_NAME} ${WMS_LATEST} - -# push -docker push ${APPS_VERSION} -docker push ${APPS_LATEST} - -docker push ${DB_VERSION} -docker push ${DB_LATEST} +export VERSION="1.1.0-SNAPSHOT-${TIMESTAMP}" +export LATEST="latest" -docker push ${WMS_VERSION} -docker push ${WMS_LATEST} +exec ./os_docker_base.sh diff --git a/deliveries/os_docker_release.sh b/deliveries/os_docker_release.sh index 2bd2e20d..42825534 100755 --- a/deliveries/os_docker_release.sh +++ b/deliveries/os_docker_release.sh @@ -1,40 +1,11 @@ #!/bin/bash +# Builds and pushes STAGING versions of Portal images -# Establish environment variables -source $(dirname $0)/os_settings.sh - -./run.sh - -REPO="nexus3.onap.org:10003" +# be verbose +set -x TIMESTAMP=$(date +%C%y%m%dT%H%M%S) -VERSION="1.1.0-STAGING-${TIMESTAMP}" -LATEST="1.1-STAGING-latest" - -APPS_VERSION="${REPO}/openecomp/${EP_TAG_NAME}:${VERSION}" -DB_VERSION="${REPO}/openecomp/${DB_TAG_NAME}:${VERSION}" -WMS_VERSION="${REPO}/openecomp/${WMS_TAG_NAME}:${VERSION}" - -APPS_LATEST="${REPO}/openecomp/${EP_TAG_NAME}:${LATEST}" -DB_LATEST="${REPO}/openecomp/${DB_TAG_NAME}:${LATEST}" -WMS_LATEST="${REPO}/openecomp/${WMS_TAG_NAME}:${LATEST}" - -# tag version -docker tag ${EP_IMG_NAME} ${APPS_VERSION} -docker tag ${EP_IMG_NAME} ${APPS_LATEST} - -docker tag ${DB_IMG_NAME} ${DB_VERSION} -docker tag ${DB_IMG_NAME} ${DB_LATEST} - -docker tag ${WMS_IMG_NAME} ${WMS_VERSION} -docker tag ${WMS_IMG_NAME} ${WMS_LATEST} - -# push -docker push ${APPS_VERSION} -docker push ${APPS_LATEST} - -docker push ${DB_VERSION} -docker push ${DB_LATEST} +export VERSION="1.1.0-STAGING-${TIMESTAMP}" +export LATEST="1.1-STAGING-latest" -docker push ${WMS_VERSION} -docker push ${WMS_LATEST} +exec ./os_docker_base.sh diff --git a/deliveries/os_settings.sh b/deliveries/os_settings.sh deleted file mode 100755 index 19a1e0ef..00000000 --- a/deliveries/os_settings.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# Establish constants for the management shell scripts. -# These variables are ALSO used in demo/boot/portal_vm_init.sh - -EP_TAG_NAME=portalapps -EP_IMG_NAME=portalapps:latest -EP_CONT_NAME=onap_portal - -DB_TAG_NAME=portaldb -DB_IMG_NAME=portaldb:latest -DB_CONT_NAME=onap_portal_db -DB_VOL_NAME=data_vol_portal - -WMS_TAG_NAME=portalwms -WMS_IMG_NAME=widget-ms -WMS_CONT_NAME=onap_portal_widget_ms - -VERSION=1.1.0 -ETCDIR=etc -WORKINGDIR=PROJECT -SDK_DIR=PROJECT/Source/ecomp-portal-core/ecomp-portal-BE-os/target/ecompportal-be-os -FE_DIR=PROJECT/Source/ecomp-portal-core/ecomp-portal-FE-os -SCRIPT_COMMON_DIR="PROJECT/Source/ecomp-portal-core/ecomp-portal-DB-common/" -SCRIPT_DIR="PROJECT/Source/ecomp-portal-core/ecomp-portal-DB-os/" -SDK_COMMON_SCRIPT_DIR=PROJECT/Source/ecomp-portal-core/ecomp-sdk/epsdk-app-common/db-scripts -SDK_SCRIPT_DIR=PROJECT/Source/ecomp-portal-core/ecomp-sdk/epsdk-app-os/db-scripts -DBC_COMMON_SCRIPT_DIR=PROJECT/Source/ST_DBPA/dcae_dmaapbc_webapp/dbca-common/db-scripts -DBC_SCRIPT_DIR=PROJECT/Source/ST_DBPA/dcae_dmaapbc_webapp/dbca-os/db-scripts -PORTAL_SDK_DIR=PROJECT/Source/ecomp-portal-core/ecomp-sdk/epsdk-app-os/target/epsdk-app-os -PORTAL_DBC_DIR=PROJECT/Source/ST_DBPA/dcae_dmaapbc_webapp/dbca-os/target/ep-dbc-app diff --git a/deliveries/portal_vm_init.sh b/deliveries/portal_vm_init.sh index 5f34aae8..5f4716ec 100755 --- a/deliveries/portal_vm_init.sh +++ b/deliveries/portal_vm_init.sh @@ -1,71 +1,42 @@ #!/bin/bash # Starts docker containers for ONAP Portal +# This version for Amsterdam/R1 of Portal, uses docker-compose. +# Temporarily maintained in portal/deliveries area; +# replicated from the ONAP demo/boot area due to release concerns. # be verbose set -x -# Refresh source area with start scripts -cd /opt/portal -git pull -cd /opt - # Establish environment variables NEXUS_USERNAME=$(cat /opt/config/nexus_username.txt) NEXUS_PASSWD=$(cat /opt/config/nexus_password.txt) NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt) DOCKER_IMAGE_VERSION=$(cat /opt/config/docker_version.txt) -# Get container, image and tag names used below -source portal/deliveries/os_settings.sh +# Refresh configuration and scripts +cd /opt/portal +git pull +cd deliveries + +# Get image names used below from docker-compose environment file +source .env -# Unpack property files -unzip -o portal/deliveries/etc.zip -d /PROJECT/OpenSource/UbuntuEP/ +# Copy property files +ETC=/PROJECT/OpenSource/UbuntuEP/etc +mkdir -p $ETC +cp -r properties_rackspace/* $ETC # Refresh images docker login -u $NEXUS_USERNAME -p $NEXUS_PASSWD $NEXUS_DOCKER_REPO -docker pull $NEXUS_DOCKER_REPO/openecomp/${DB_TAG_NAME}:$DOCKER_IMAGE_VERSION -docker pull $NEXUS_DOCKER_REPO/openecomp/${EP_TAG_NAME}:$DOCKER_IMAGE_VERSION -docker pull $NEXUS_DOCKER_REPO/openecomp/${WMS_TAG_NAME}:$DOCKER_IMAGE_VERSION - -# Remove lingering containers; order matters. -docker rm -f $DB_CONT_NAME -docker rm -f $DB_VOL_NAME -docker rm -f $EP_CONT_NAME -docker rm -f $WMS_CONT_NAME - -docker create --name $DB_VOL_NAME -v /var/lib/mysql mariadb -docker tag $NEXUS_DOCKER_REPO/openecomp/${DB_TAG_NAME}:$DOCKER_IMAGE_VERSION $DB_IMG_NAME -docker tag $NEXUS_DOCKER_REPO/openecomp/${EP_TAG_NAME}:$DOCKER_IMAGE_VERSION $EP_IMG_NAME -# WMS image has no version in the registry -docker tag $NEXUS_DOCKER_REPO/openecomp/${WMS_TAG_NAME}:$DOCKER_IMAGE_VERSION ${WMS_IMG_NAME}:latest - -# Recreate the named containers -cd portal/deliveries -echo "Starting database" -./dbstart.sh -echo "Delaying for database" -sleep 10 -echo "Starting apps" -./new_start.sh -echo "Starting widget-ms" -./widget_ms_start.sh - -sleep 180 - -if [ ! -e /opt/config/boot.txt ] -then - if [ -e /opt/config/public_ip.txt ] - then - IP_ADDRESS=$(cat /opt/config/public_ip.txt) - else - IP_ADDRESS=$(ifconfig eth0 | grep "inet addr" | tr -s ' ' | cut -d' ' -f3 | cut -d':' -f2) - fi - # Wait until MySQL is running... - while [[ $(netstat -vulntp |grep -i mysql | awk '{print $4}') != ":::3306" ]] - do - sleep 1 - done - # no longer necessary; done at docker build time - # mysql -u root -p'Aa123456' -h $IP_ADDRESS < /opt/portal/deliveries/Apps_Users_OnBoarding_Script.sql - echo "yes" > /opt/config/boot.txt -fi +docker pull $NEXUS_DOCKER_REPO/openecomp/${DB_IMG_NAME}:$DOCKER_IMAGE_VERSION +docker pull $NEXUS_DOCKER_REPO/openecomp/${EP_IMG_NAME}:$DOCKER_IMAGE_VERSION +docker pull $NEXUS_DOCKER_REPO/openecomp/${WMS_IMG_NAME}:$DOCKER_IMAGE_VERSION + +# Tag them as expected by docker-compose file +docker tag $NEXUS_DOCKER_REPO/openecomp/${DB_IMG_NAME}:$DOCKER_IMAGE_VERSION $DB_IMG_NAME:$PORTAL_TAG +docker tag $NEXUS_DOCKER_REPO/openecomp/${EP_IMG_NAME}:$DOCKER_IMAGE_VERSION $EP_IMG_NAME:$PORTAL_TAG +docker tag $NEXUS_DOCKER_REPO/openecomp/${WMS_IMG_NAME}:$DOCKER_IMAGE_VERSION $WMS_IMG_NAME:$PORTAL_TAG + +# compose is not in /usr/bin +/opt/docker/docker-compose down +/opt/docker/docker-compose up -d diff --git a/deliveries/properties_rackspace/ECOMPDBCAPP/dbcapp.properties b/deliveries/properties_rackspace/ECOMPDBCAPP/dbcapp.properties new file mode 100644 index 00000000..1c13384d --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPDBCAPP/dbcapp.properties @@ -0,0 +1,8 @@ +# Properties for the Data Bus Controller webapp +dmaap.rest.url.list = http://10.0.4.102:18080/webapi +# webapp's mechid is sent to DCAE for authorization +dmaap.mechid.name = m06672@dbcapp.dmaap.dcae.att.com +# encrypted with CipherUtil +dmaap.mechid.password = /F1vRhga1Ijw7yRFFj6R5A== +# Valid access methods are "dao" and "rest" +profile.access.method = dao diff --git a/deliveries/properties_rackspace/ECOMPDBCAPP/fusion.properties b/deliveries/properties_rackspace/ECOMPDBCAPP/fusion.properties new file mode 100644 index 00000000..4d4e17e9 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPDBCAPP/fusion.properties @@ -0,0 +1,33 @@ +# login settings +login_method_backdoor = backdoor +login_method_attribute_name = login_method +login_method_csp = csp +login_method_web_junction = web_junction + +#login message +login.error.hrid.empty = Login failed, please contact system administrator. +login.error.hrid.not-found = User not found, please contact system administrator. +login.error.user.inactive = Account is disabled, please contact system administrator. + +authentication_mechanism = DBAUTH + +# User Session settings +user_attribute_name = user +roles_attribute_name = roles +role_functions_attribute_name = role_functions + +# POST settings +post_initial_context_factory = com.sun.jndi.ldap.LdapCtxFactory +post_provider_url = todo_ldap +post_security_principal = ou=people,o=org,c=us +post_max_result_size = 499 + +# menu settings +menu_query_name = menuData +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +business_direct_menu_set_name = BD +business_direct_menu_attribute_name = businessDirectMenuData + +# Role settings +sys_admin_role_id = 1 diff --git a/deliveries/properties_rackspace/ECOMPDBCAPP/portal.properties b/deliveries/properties_rackspace/ECOMPDBCAPP/portal.properties new file mode 100644 index 00000000..6dbbee84 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPDBCAPP/portal.properties @@ -0,0 +1,25 @@ +# Properties read by ECOMP Framework library, ecompFW.jar + +portal.api.impl.class = org.openecomp.portalapp.service.OnBoardingApiServiceImpl +portal.api.prefix = /api +max.idle.time = 5 +user.attribute.name = user_attribute + +# Legacy property TODO +ecomp_redirect_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm + +# URL of the ECOMP Portal REST API +ecomp_rest_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/auxapi + +#Use REST API instead of UEB to fetch the functional menu data +use_rest_for_functional_menu=true + +# Don't fetch functional menu via UEB in 1610. +ueb_listeners_enable = false + +# Application key is used by session management +ueb_app_key = MtRwsF16RdpHZ7eM + +# The inbox name property should not be required when the REST API is used, +# but in 1610 FuncMenuController logs ALARM if it cannot find this key. +ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-TEST diff --git a/deliveries/properties_rackspace/ECOMPDBCAPP/system.properties b/deliveries/properties_rackspace/ECOMPDBCAPP/system.properties new file mode 100644 index 00000000..019268b7 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPDBCAPP/system.properties @@ -0,0 +1,63 @@ +#Local +app_display_name = DMaaP Bus Ctlr + +db.driver = com.mysql.jdbc.Driver +db.connectionURL = jdbc:mysql://portal-db:3306/dbca_os +db.userName = root +db.password = Aa123456 +db.encrypt_flag = false +db.hib.dialect = org.hibernate.dialect.MySQLDialect +db.min_pool_size = 5 +db.max_pool_size = 10 +hb.dialect = org.hibernate.dialect.MySQLDialect +hb.show_sql = false +hb.db_reconnect = true +hb.idle_connection_test_period = 3600 + +# Directory with the Quantum.lic file +files_path = /opt/app/tomcat/webapps/dmaap-bc-app/WEB-INF/dbcapp + +application_user_id = 30000 +post_default_role_id = 16 +clustered = true + +#Enable Fusion Mobile capabilities for the application +mobile_enable = false + +# Cache config file is needed on the classpath +cache_config_file_path = /WEB-INF/classes/cache.ccf +cache_switch = 199 +cache_load_on_startup = false + +user_name = fullName +decryption_key = AGLDdG4D04BKm2IxIWEr8o== + +#element map files +element_map_file_path = /tmp +element_map_icon_path = app/fusionapp/icons/ + +# Quartz is not used by the DBC application +# log_cron = +# mylogins_feed_cron = +# sessiontimeout_feed_cron = +# my_login_feed_output_dir = + +# ECOMP Portal Shared Context REST API URL is not used by the DBC application +# ecomp_shared_context_rest_url = + +contact_us_link = https://todo_contact_us_link + +# An Unique 128-bit value defined to identify a specific version +# of an application deployed on a specific virtual machine. +# This value must be generated and updated by the application +# which is using the ECOMP SDK at the time of its deployment. +# Online Unique UUID generator - https://www.uuidgenerator.net/ +# ID generated for DBC to supply to EELF +# A bogus value is cached in SCM: 12345678-.. +instance_uuid = 12345678-90ab-cdef-1234-567890abcdef + +# R Cloud feature +guard_notebook_url=https://todo_rcloud_link + +# Application base URL is a proper prefix of the on-boarded URL. +app_base_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPDBCAPP/ diff --git a/deliveries/properties_rackspace/ECOMPPORTALAPP/fusion.properties b/deliveries/properties_rackspace/ECOMPPORTALAPP/fusion.properties new file mode 100644 index 00000000..c92a5739 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPPORTALAPP/fusion.properties @@ -0,0 +1,46 @@ +# domain settings +#domain_class_location = + +# validator settings +#default_error_message = Default error message + +login_url_no_ret_val = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm + +user_attribute_name = user + +# User Session settings +roles_attribute_name = roles +role_functions_attribute_name = role_functions + +# menu settings +menu_query_name = menuData +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +business_direct_menu_set_name = BD +business_direct_menu_attribute_name = businessDirectMenuData + +# ECOMP settings +ecomp_app_id = 1 +# Role settings +sys_admin_role_id = 1 +account_admin_role_id = 999 +restricted_app_role_id = 900 + +# Home Page index html +home_page = /index.html + +authentication_mechanism =DBAUTH + +login.error.hrid.empty = Login failed, please contact system administrator. +login.error.hrid.not-found = User not found, please contact system administrator. +login.error.user.inactive = Account is disabled, please contact system administrator. + +# +# Number of seconds to poll health (database operational, etc.) +# +health_poll_interval_seconds = 5 +# +# If a component is down a log entry will be written that triggers an alert. This parameter specifies how often this alert should be triggered +# if the component remains down. For example a value of 30, would translate to 30 * 60 seconds = 1800 seconds, or every 30 minutes +# +health_fail_alert_every_x_intervals = 30 diff --git a/deliveries/properties_rackspace/ECOMPPORTALAPP/logback.xml b/deliveries/properties_rackspace/ECOMPPORTALAPP/logback.xml new file mode 100644 index 00000000..0c0d7647 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPPORTALAPP/logback.xml @@ -0,0 +1,285 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${applicationLoggerPattern} + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${applicationLoggerPattern} + + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + + ${logDirectory}/${auditLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + + ${logDirectory}/${metricsLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + + ${logDirectory}/${errorLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + + ${logDirectory}/${debugLogName}.log.%d{yyyy-MM-dd}.zip + + 30 + + + ${defaultLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/deliveries/properties_rackspace/ECOMPPORTALAPP/openid-connect.properties b/deliveries/properties_rackspace/ECOMPPORTALAPP/openid-connect.properties new file mode 100644 index 00000000..33c919b2 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPPORTALAPP/openid-connect.properties @@ -0,0 +1,3 @@ +authentication_server_url = http://portal.api.simpledemo.openecomp.org:8383/openid-connect-server-webapp/ +ecomp_openid_connect_client = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/openid_connect_login +ecomp_redirect_uri = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/welcome.htm diff --git a/deliveries/properties_rackspace/ECOMPPORTALAPP/portal.properties b/deliveries/properties_rackspace/ECOMPPORTALAPP/portal.properties new file mode 100644 index 00000000..f7fba31a --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPPORTALAPP/portal.properties @@ -0,0 +1,23 @@ +portal.api.impl.class = org.openecomp.portalsdk.core.onboarding.client.OnBoardingApiServiceImpl +portal.api.prefix = /api +max.idle.time = 5 +user.attribute.name = user_attribute + +# for single sign on +ecomp_redirect_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm + +# URL of the ECOMP Portal REST API +ecomp_rest_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/auxapi + +ueb_listeners_enable = true + +ueb_app_key = 7GkVcrO6sIDb3ngW +ueb_app_secret = uCYgKjWKK5IxPGNNZzYSSWo9 +ueb_app_mailbox_name = ECOMP-PORTAL-INBOX + +ueb_url_list = ueb.api.simpledemo.openecomp.org +ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX + +# Consumer group name for UEB topic. +# Use the special tag to generate a unique one for each sdk-app server. +ueb_app_consumer_group_name = {UUID} diff --git a/deliveries/properties_rackspace/ECOMPPORTALAPP/system.properties b/deliveries/properties_rackspace/ECOMPPORTALAPP/system.properties new file mode 100644 index 00000000..10842953 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPPORTALAPP/system.properties @@ -0,0 +1,97 @@ +#mysql +db.driver = com.mysql.jdbc.Driver +db.connectionURL = jdbc:mysql://portal-db:3306/portal +db.userName =root +db.password =Aa123456 +db.hib.dialect = org.hibernate.dialect.MySQLDialect +db.min_pool_size = 5 +db.max_pool_size = 10 +hb.dialect = org.hibernate.dialect.MySQLDialect +hb.show_sql = false +hb.db_reconnect = true +hb.idle_connection_test_period = 3600 + +app_display_name = Portal +files_path = /tmp +context_root = ECOMPPORTAL +# menu settings +menu_query_name = menuData +menu_properties_file_location = /WEB-INF/fusion/menu/ +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +application_menu_properties_name = menu.properties +business_direct_menu_set_name = BD +business_direct_menu_properties_name = bd.menu.properties +business_direct_menu_attribute_name = businessDirectMenuData + +application_user_id = 30000 +post_default_role_id = 1 + +#Enable Fusion Mobile capabilities for the application +mobile_enable = false + +cache_config_file_path = /WEB-INF/conf/cache.ccf +cache_switch = 1 +cache_load_on_startup = false + +user_name = fullName +decryption_key = AGLDdG4D04BKm2IxIWEr8o== + + +#Cron Schedules +cron_site_name = one +log_cron = 0 * * * * ? * +sessiontimeout_feed_cron = 0 0/5 * * * ? * + +#Front end URL +frontend_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/applicationsHome + +#cookie domain +cookie_domain = openecomp.org + +# An Unqiue 128-bit value defined to indentify a specific version of +# ECOMP Portal deployed on a specific virtual machine. +# This value must be generated and updated at the time of +# the deployment. +# Online Unique UUID generator - https://www.uuidgenerator.net/ +instance_uuid = 90bc9497-10e6-49fe-916b-dcdfaa972383 + +elastic_search_url = http:// +contact_us_link = http:// +user_guide_link = http:// + +# Contact Us page properties +ush_ticket_url = http:// +feedback_email_address = portal@lists.openecomp.org +portal_info_url = https:// + +#Online user bar refresh interval, in seconds +online_user_update_rate = 30 + +#Online user bar refresh total duration, in seconds +online_user_update_duration = 300 + +#authenticate user server +authenticate_user_server=http://portal.api.simpledemo.openecomp.org:8383/openid-connect-server-webapp/allUsers + +#window width threshold to collapse left/right menu when page onload +window_width_threshold_left_menu = 1400 +window_width_threshold_right_menu = 1350 + +# User notification refresh interval and duration, in seconds +notification_update_rate = 90 +notification_update_duration = 900 + +#Microservices Related Properties for Portal +microservices.widget.protocol = http +microservices.widget.hostname = portal-wms +microservices.widget.username = widget_user +microservices.widget.password = KpuqIB08YHg+btG+pjX+sA== +#This property won't be needed after consul is functional on VMs - +microservices.widget.local.port = 8082 +microservices.m-learn.local.port = 8083 +#HALO API enable flag +external_access_enable = false + +#delete auditlog from number of days ago +auditlog_del_day_from = 365 diff --git a/deliveries/properties_rackspace/ECOMPSDKAPP/fusion.properties b/deliveries/properties_rackspace/ECOMPSDKAPP/fusion.properties new file mode 100644 index 00000000..8ce8cc95 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPSDKAPP/fusion.properties @@ -0,0 +1,35 @@ +# login settings +login_method_backdoor = backdoor +login_method_attribute_name = login_method + +# These properties will be removed after SingleSignOnController is cleaned +authentication_mechanism = BOTH +login_method_csp = csp +login_method_web_junction = web_junction + +#login message +login.error.hrid.empty = Login failed, please contact system administrator. +login.error.hrid.not-found = User not found, please contact system administrator. +login.error.user.inactive = Account is disabled, please contact system administrator. + +# User Session settings +user_attribute_name = user +roles_attribute_name = roles +role_function_list = role_function_list +role_functions_attribute_name = role_functions + +# Import-user LDAP settings +post_initial_context_factory = com.sun.jndi.ldap.LdapCtxFactory +post_provider_url = ldap://ldap.mycompany.com:389 +post_security_principal = ou=people,o=mycompany,c=us +post_max_result_size = 499 + +# menu settings +menu_query_name = menuData +application_menu_set_name = APP +application_menu_attribute_name = applicationMenuData +business_direct_menu_set_name = BD +business_direct_menu_attribute_name = businessDirectMenuData + +# Role settings +sys_admin_role_id = 1 diff --git a/deliveries/properties_rackspace/ECOMPSDKAPP/portal.properties b/deliveries/properties_rackspace/ECOMPSDKAPP/portal.properties new file mode 100644 index 00000000..b569e4fc --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPSDKAPP/portal.properties @@ -0,0 +1,44 @@ +# Properties read by ECOMP Framework library, ecompFW.jar + +########################################################################## +# The following properties should NOT be changed by partner applications. +########################################################################## + +portal.api.prefix = /api +max.idle.time = 5 +user.attribute.name = user_attribute + +#Use REST API instead of UEB to fetch the functional menu data +use_rest_for_functional_menu=true + +########################################################################## +# The following properties MUST be changed by partner applications. +########################################################################## + +# Name of java class that implements the OnBoardingApiService interface. +portal.api.impl.class = org.openecomp.portalapp.service.OnBoardingApiServiceImpl + +# CSP Global Log On for single sign on +ecomp_redirect_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/login.htm + +# URL of the ECOMP Portal REST API + +ecomp_rest_url = http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/auxapi + +# Applications do not need to run a UEB listener in 1610. +ueb_listeners_enable = false + +# UEB Configuration +ueb_url_list = ueb.api.simpledemo.openecomp.org +# ECOMP Portal listens on this UEB topic +ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX +# Replace these 3 default values with the ones for your specific App, +# as shown on the on-boarding page on the ECOMP Portal web application. +ueb_app_key = jQd4a9zVNi4ePyBp +ueb_app_secret = P0HpqEBhKJvxjRYdw2sCTUll +ueb_app_mailbox_name = ECOMP-PORTAL-OUTBOX-APP1 +# Consumer group name for UEB topic. +# Use the special tag '{UUID}' to generate a unique one for each sdk-app server. +ueb_app_consumer_group_name = {UUID} + +decryption_key = AGLDdG4D04BKm2IxIWEr8o== diff --git a/deliveries/properties_rackspace/ECOMPSDKAPP/system.properties b/deliveries/properties_rackspace/ECOMPSDKAPP/system.properties new file mode 100644 index 00000000..105502f1 --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPSDKAPP/system.properties @@ -0,0 +1,65 @@ +# Properties read by ECOMP Core library, ecompSDK-core.jar + +########################################################################## +# The following properties should NOT be changed by partner applications. +########################################################################## + +application_user_id = 30000 +post_default_role_id = 16 +clustered = true + +#Enable Fusion Mobile capabilities for the application +mobile_enable = false + +# Cache config file is needed on the classpath +cache_config_file_path = /WEB-INF/classes/cache.ccf +cache_switch = 199 +cache_load_on_startup = false + +user_name = fullName +decryption_key = AGLDdG4D04BKm2IxIWEr8o== + +########################################################################## +# The following properties MAY require changes by partner applications. +########################################################################## + +#Mysql +db.driver = com.mysql.jdbc.Driver +db.connectionURL = jdbc:mysql://portal-db:3306/ecomp_sdk +db.userName = root +db.password = Aa123456 +db.min_pool_size = 5 +db.max_pool_size = 10 +hb.dialect = org.hibernate.dialect.MySQLDialect +# SQL statements are logged to stdout +hb.show_sql = true +hb.idle_connection_test_period = 3600 + +app_display_name = Demo App +files_path = /tmp + +#element map files +element_map_file_path = /tmp +element_map_icon_path = app/fusionapp/icons/ + +#Cron Schedules +log_cron = 0 0/1 * * * ?; +mylogins_feed_cron = 0 0/60 * * * ?; +#sessiontimeout_feed_cron = 0 * * * * ? * +my_login_feed_output_dir = /tmp/MyLogins + +# Link shown in Help menu +contact_us_link = https://todo_contact_us_link.com + +# An Unique 128-bit value defined to identify a specific version +# of an application deployed on a specific virtual machine. +# This value must be generated and updated by the application +# which is using the ECOMP SDK at the time of its deployment. +# Online Unique UUID generator - https://www.uuidgenerator.net/ +instance_uuid=8da691c9-987d-43ed-a358-00ac2f35685d + +# R Cloud feature - configure this property to enable notebook feature - for more details on RCloud please visit https://rcloud.social/index.html +guard_notebook_url= + +#authenticate user server +authenticate_user_server=http://portal.openecomp.org:8383/openid-connect-server-webapp/allUsers diff --git a/deliveries/properties_rackspace/ECOMPWIDGETMS/application.properties b/deliveries/properties_rackspace/ECOMPWIDGETMS/application.properties new file mode 100644 index 00000000..7c95923f --- /dev/null +++ b/deliveries/properties_rackspace/ECOMPWIDGETMS/application.properties @@ -0,0 +1,35 @@ +## General App Properties +server.contextPath=/widget +server.port=8082 +spring.http.multipart.max-file-size=128MB +spring.http.multipart.max-request-size=128MB +microservice.widget.location=/tmp + +## App DB Properties +spring.datasource.url=jdbc:mysql://portal-db:3306/portal +spring.datasource.username=root +spring.datasource.password=Aa123456 +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect +spring.database.driver.classname=org.mariadb.jdbc.Driver +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.format_sql=false + +## Basic Authentication Properties +security.user.name=widget_user +security.user.password=ENC(IjywcRnI9+nuVEh9+OFFiRWAjBT1n718) + +initialization.default.widgets=true +initialization.widgetData.url=http://portal.api.simpledemo.openecomp.org:8989/ECOMPPORTAL/commonWidgets + +## Account Basic Authentication Properties +account.user.name=portal +account.user.password=6APqvG4AU2rfLgCvMdySwQ== + +## Certificate Properties +#server.ssl.key-store=classpath:widget-keystore.p12 +#server.ssl.key-store-password=ENC(DiIYnAMab4u7rEW2yKhF9zBL00uU55q8) +#server.ssl.keyStoreType=PKCS12 +#server.ssl.keyAlias=widget-microservice + +## Jasypt Properties +jasypt.encryptor.password=EncryptionKey diff --git a/deliveries/run.sh b/deliveries/run.sh deleted file mode 100755 index bd2a5dd1..00000000 --- a/deliveries/run.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# Stop on errors; show output -set -e -x -# 1610 builder -# ./os_build_febe.sh -# 1707 builder -./build_portalapps_dockers.sh -./createMaria.sh -docker images diff --git a/deliveries/configure-and-run.sh b/deliveries/start-apps-cmd.sh similarity index 94% rename from deliveries/configure-and-run.sh rename to deliveries/start-apps-cmd.sh index 5c2b2f46..bbe2a7cb 100755 --- a/deliveries/configure-and-run.sh +++ b/deliveries/start-apps-cmd.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/sh LOGFILE=/opt/apache-tomcat-8.0.37/logs/catalina.out echo "`date`:<-------------------- Starting -------------------->" >> $LOGFILE diff --git a/deliveries/start-wms-cmd.sh b/deliveries/start-wms-cmd.sh new file mode 100755 index 00000000..dc8336e7 --- /dev/null +++ b/deliveries/start-wms-cmd.sh @@ -0,0 +1,2 @@ +#!/bin/sh +java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar diff --git a/deliveries/wait-for.sh b/deliveries/wait-for.sh new file mode 100755 index 00000000..be9a443f --- /dev/null +++ b/deliveries/wait-for.sh @@ -0,0 +1,82 @@ +#!/bin/sh +# https://github.com/Eficode/wait-for.git +# MIT License + +TIMEOUT=15 +QUIET=0 + +echoerr() { + if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi +} + +usage() { + exitcode="$1" + cat << USAGE >&2 +Usage: + $cmdname host:port [-t timeout] [-- command args] + -q | --quiet Do not output any status messages + -t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout + -- COMMAND ARGS Execute command with args after the test finishes +USAGE + exit "$exitcode" +} + +wait_for() { + command="$*" + for i in `seq $TIMEOUT` ; do + nc -z "$HOST" "$PORT" > /dev/null 2>&1 + result=$? + if [ $result -eq 0 ] ; then + if [ "$QUIET" -ne 1 ]; then echo "Operation succeeded on try $i"; fi + if [ -n "$command" ] ; then + exec $command + fi + exit 0 + fi + sleep 1 + done + echo "Operation timed out" >&2 + exit 1 +} + +while [ $# -gt 0 ] +do + case "$1" in + *:* ) + HOST=$(printf "%s\n" "$1"| cut -d : -f 1) + PORT=$(printf "%s\n" "$1"| cut -d : -f 2) + shift 1 + ;; + -q | --quiet) + QUIET=1 + shift 1 + ;; + -t) + TIMEOUT="$2" + if [ "$TIMEOUT" = "" ]; then break; fi + shift 2 + ;; + --timeout=*) + TIMEOUT="${1#*=}" + shift 1 + ;; + --) + shift + break + ;; + --help) + usage 0 + ;; + *) + echoerr "Unknown argument: $1" + usage 1 + ;; + esac +done + +if [ "$HOST" = "" -o "$PORT" = "" ]; then + echoerr "Error: you need to provide a host and port to test." + usage 2 +fi + +wait_for "$@" diff --git a/deliveries/widget_ms_start.sh b/deliveries/widget_ms_start.sh deleted file mode 100755 index b5fbdc25..00000000 --- a/deliveries/widget_ms_start.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -BASEDIR=/PROJECT/OpenSource/UbuntuEP -WIDGETMSAPPPROPDIR=ECOMPWIDGETMS - -echo "Running docker image ${WMS_IMG_NAME} as container ${WMS_CONT_NAME}" -docker run -d --name ${WMS_CONT_NAME} -p 8082:8082 -v ${BASEDIR}/etc/${WIDGETMSAPPPROPDIR}/application.properties:/application.properties ${WMS_IMG_NAME} diff --git a/deliveries/widget_ms_stop.sh b/deliveries/widget_ms_stop.sh deleted file mode 100755 index dd5c9645..00000000 --- a/deliveries/widget_ms_stop.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -# Establish environment variables -source $(dirname $0)/os_settings.sh - -echo "Stopping docker container ${WMS_CONT_NAME}" -docker stop ${WMS_CONT_NAME} -echo "Removing docker image ${WMS_CONT_NAME}" -docker rm ${WMS_CONT_NAME} diff --git a/ecomp-portal-BE-common-test/pom.xml b/ecomp-portal-BE-common-test/pom.xml index 2e47388b..afdf35ac 100644 --- a/ecomp-portal-BE-common-test/pom.xml +++ b/ecomp-portal-BE-common-test/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.openecomp.portal + org.onap.portal ecomp-portal-BE-common-test - 1.1.0 + 1.3.0-SNAPSHOT jar ecompportal-be-common-test @@ -105,7 +105,7 @@ 1.8.5 - org.openecomp.portal + org.onap.portal ecompportal-be-common ${project.version} jar diff --git a/ecomp-portal-BE-common/pom.xml b/ecomp-portal-BE-common/pom.xml index f5f925b8..af828cf2 100644 --- a/ecomp-portal-BE-common/pom.xml +++ b/ecomp-portal-BE-common/pom.xml @@ -1,18 +1,18 @@ 4.0.0 - org.openecomp.portal + org.onap.portal ecompportal-be-common war - 1.1.0 + 1.3.0-SNAPSHOT 4.2.0.RELEASE 4.3.11.Final 1.0.0 2.7.4 - 1.1.0 + 1.3.0-SNAPSHOT UTF-8 true @@ -503,7 +503,7 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-fw ${epsdk.version} @@ -526,7 +526,7 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-core ${epsdk.version} @@ -537,12 +537,12 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-app-common ${epsdk.version} - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-workflow ${epsdk.version} @@ -550,7 +550,7 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-analytics ${epsdk.version} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/PortalCentralAccessConfiguration.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/PortalCentralAccessConfiguration.java new file mode 100644 index 00000000..4ee4be20 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/config/PortalCentralAccessConfiguration.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.config; + +import org.openecomp.portalapp.portal.service.EPRoleFunctionService; +import org.openecomp.portalapp.portal.service.EPRoleFunctionServiceCentralizedImpl; +import org.openecomp.portalapp.portal.service.EPRoleFunctionServiceImpl; +import org.openecomp.portalsdk.core.service.CentralAccessCondition; +import org.openecomp.portalsdk.core.service.LocalAccessCondition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class PortalCentralAccessConfiguration { + + + @Bean + @Conditional(LocalAccessCondition.class) + public EPRoleFunctionService ePRoleFunctionServiceImpl() { + return new EPRoleFunctionServiceImpl(); + } + + + @Bean + @Conditional(CentralAccessCondition.class) + public EPRoleFunctionService ePRoleFunctionServiceCentralizedImpl() { + return new EPRoleFunctionServiceCentralizedImpl(); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java index 774eb3ee..00cf627e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/AppsControllerExternalRequest.java @@ -209,7 +209,7 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl "myLoginsAppOwner" : "abc123", "name": "dashboard", "url": "http://k8s/something", - "restUrl" : "http://aic.att.com", + "restUrl" : "http://targeturl.com", "restrictedApp" : true, "isOpen" : true, "isEnabled": false @@ -295,7 +295,7 @@ public class AppsControllerExternalRequest implements BasicAuthenticationControl "myLoginsAppOwner" : "abc123", "name": "dashboard", "url": "http://k8s/something", - "restUrl" : "http://aic.att.com", + "restUrl" : "http://targeturl.com", "restrictedApp" : true, "isOpen" : true, "isEnabled": false diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java new file mode 100644 index 00000000..43e07af3 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/ExternalAccessRolesController.java @@ -0,0 +1,330 @@ +package org.openecomp.portalapp.portal.controller; + + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; +import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; +import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesService; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping("/auxapi") +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +@EPAuditLog +public class ExternalAccessRolesController implements BasicAuthenticationController { + + private static final String UEBKEY = "uebkey"; + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class); + + @Autowired + private ExternalAccessRolesService externalAccessRolesService; + + @ApiOperation(value = "Gets user role for an application.", response = String.class, responseContainer="List") + @RequestMapping(value = { + "/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + public String getUser(HttpServletRequest request, HttpServletResponse response, @PathVariable("loginId") String loginId) throws Exception { + + String answer = null; + try { + answer = externalAccessRolesService.getUser(loginId, request.getHeader(UEBKEY)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUser failed", e); + } + return answer; + } + + @ApiOperation(value = "Gets roles for an application.", response = CentralRole.class, responseContainer="Json") + @RequestMapping(value = { + "/roles" }, method = RequestMethod.GET, produces = "application/json") + public List getRolesForApp(HttpServletRequest request, HttpServletResponse response) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRolesForApp"); + List applicationList=new ArrayList<>(); + applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY)); + EPApp app = applicationList.get(0); + externalAccessRolesService.SyncApplicationRolesWithEcompDB(app); + List answer = null; + try { + answer = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + if("Application not found".equalsIgnoreCase(e.getMessage())){ + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp failed", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRolesForApp"); + return answer; + } + + @ApiOperation(value = "Gets all role functions for an application.", response = CentralRoleFunction.class, responseContainer="Json") + @RequestMapping(value = { + "/functions" }, method = RequestMethod.GET, produces = "application/json") + public List getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response) throws Exception { + List answer = null; + logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleFunctionsList"); + try { + answer = externalAccessRolesService.getRoleFuncList(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionsList failed", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleFunctionsList"); + return answer; + } + + @ApiOperation(value = "Gets role information for an application.", response = CentralRole.class, responseContainer="Json") + @RequestMapping(value = { + "/role/{role_id}" }, method = RequestMethod.GET, produces = "application/json") + public CentralRole getRoleInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable("role_id") Long roleId) throws Exception { + CentralRole answer = null; + logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleInfo"); + + try { + answer = externalAccessRolesService.getRoleInfo(roleId, request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleInfo"); + return answer; + } + + @ApiOperation(value = "Gets role information for an application provided by function code.", response = CentralRoleFunction.class, responseContainer = "Json") + @RequestMapping(value = { "/function/{code}" }, method = RequestMethod.GET, produces = "application/json") + public CentralRoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response, + @PathVariable("code") String code) throws Exception { + CentralRoleFunction centralRoleFunction = null; + try { + centralRoleFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + } + return centralRoleFunction; + } + + @ApiOperation(value = "Saves role function for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/roleFunction" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveRoleFunction(HttpServletRequest request, HttpServletResponse response, + @RequestBody String roleFunc) throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + List applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY)); + EPApp requestedApp = applicationList.get(0); + Long appId = requestedApp.getId(); + try { + String data = roleFunc; + CentralRoleFunction availableRoleFunction = mapper.readValue(data, CentralRoleFunction.class); + availableRoleFunction.setAppId(appId); + externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction, requestedApp); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Saved", "Success"); + } + + @ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/roleFunction/{code}" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteRoleFunction(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception { + try { + externalAccessRolesService.deleteCentralRoleFunction(code, request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to deleteRoleFunction", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); + + } + + @ApiOperation(value = "Saves role for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/role" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse saveRole(HttpServletRequest request, HttpServletResponse response, + @RequestBody Role role) throws Exception { + try { + externalAccessRolesService.saveRoleForApplication(role,request.getHeader(UEBKEY)); + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to saveRole", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Saved", "Success"); + } + + @ApiOperation(value = "Deletes role for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/deleteRole/{code}" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteRole(HttpServletRequest request, HttpServletResponse response, + @PathVariable String code) throws Exception { + try { + externalAccessRolesService.deleteRoleForApplication(code, request.getHeader(UEBKEY)); + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to deleteRole", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); + + } + + @ApiOperation(value = "Gets active roles for an application.", response = CentralRole.class, responseContainer = "Json") + @RequestMapping(value = { "/activeRoles" }, method = RequestMethod.GET, produces = "application/json") + public List getActiveRoles(HttpServletRequest request, HttpServletResponse response) throws Exception { + List cenRole = null; + try { + cenRole = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e); + } + return cenRole; + + } + + @ApiOperation(value = "deletes user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/deleteDependcyRoleRecord/{roleId}" }, method = RequestMethod.DELETE, produces = "application/json") + public PortalRestResponse deleteDependcyRoleRecord(HttpServletRequest request, HttpServletResponse response, @PathVariable("roleId") Long roleId) throws Exception { + try { + externalAccessRolesService.deleteDependcyRoleRecord(roleId,request.getHeader(UEBKEY), request.getHeader("LoginId")); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "deleteDependcyRoleRecord failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to deleteDependcyRoleRecord", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully Deleted", "Success"); + } + + @ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/portal/functions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer result = 0; + try { + result = externalAccessRolesService.bulkUploadFunctions(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success"); + } + + @ApiOperation(value = "Bulk upload roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/portal/roles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer result = 0; + try { + result = externalAccessRolesService.bulkUploadRoles(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success"); + } + + @ApiOperation(value = "Bulk upload role functions for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/portal/roleFunctions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer result = 0; + try { + result = externalAccessRolesService.bulkUploadRolesFunctions(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success"); + } + + @ApiOperation(value = "Bulk upload user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/portal/userRoles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) throws Exception { + Integer result = 0; + try { + result = externalAccessRolesService.bulkUploadUserRoles(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added: "+result, "Success"); + } + + @ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/partner/functions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody List upload) throws Exception { + try { + externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY), upload); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added", "Success"); + } + + @ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/partner/roles" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response, @RequestBody List upload) throws Exception { + try { + externalAccessRolesService.bulkUploadPartnerRoles(request.getHeader(UEBKEY), upload); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added", "Success"); + } + + @ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json") + @RequestMapping(value = { "/upload/partner/roleFunctions" }, method = RequestMethod.POST, produces = "application/json") + public PortalRestResponse bulkUploadPartnerRoleFunctions(HttpServletRequest request, HttpServletResponse response, @RequestBody List upload) throws Exception { + try { + externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY), upload); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions", "Failed"); + } + return new PortalRestResponse(PortalRestStatusEnum.OK, "Successfully added", "Success"); + } + + @ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json") + @RequestMapping(value = { "/menuFunctions" }, method = RequestMethod.GET, produces = "application/json") + public List getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception { + List functionsList = null; + try { + functionsList = externalAccessRolesService.getMenuFunctionsList(request.getHeader(UEBKEY)); + } catch (HttpClientErrorException e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctions failed", e); + } + return functionsList; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java index 2d0fe279..eefd5004 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RoleManageController.java @@ -26,9 +26,13 @@ import org.openecomp.portalapp.controller.EPRestrictedBaseController; import org.openecomp.portalapp.controller.core.RoleController; import org.openecomp.portalapp.controller.core.RoleFunctionListController; import org.openecomp.portalapp.controller.core.RoleListController; +import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.ecomp.model.PortalRestResponse; import org.openecomp.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesService; +import org.openecomp.portalapp.portal.service.ExternalAccessRolesServiceImpl; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.web.bind.annotation.RequestBody; @@ -47,6 +51,7 @@ import org.springframework.web.servlet.ModelAndView; @EnableAspectJAutoProxy @EPAuditLog public class RoleManageController extends EPRestrictedBaseController { + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class); @Autowired private RoleController roleController; @@ -57,6 +62,9 @@ public class RoleManageController extends EPRestrictedBaseController { @Autowired private RoleFunctionListController roleFunctionListController; + + @Autowired + ExternalAccessRolesService externalAccessRolesService; /** * Calls an SDK-Core library method that gets the available roles and writes * them to the request object. Portal specifies a Hibernate mappings from @@ -120,7 +128,7 @@ public class RoleManageController extends EPRestrictedBaseController { } @RequestMapping(value = { "/portalApi/get_role" }, method = RequestMethod.GET) - public void getRole(HttpServletRequest request, HttpServletResponse response) { + public void getRole(HttpServletRequest request, HttpServletResponse response) throws Exception{ getRoleController().getRole(request, response); } @@ -163,4 +171,13 @@ public class RoleManageController extends EPRestrictedBaseController { this.roleFunctionListController = roleFunctionListController; } + @RequestMapping(value = { "/portalApi/syncRoles" }, method = RequestMethod.GET) + public void syncRoles(EPApp app) + { + try { + externalAccessRolesService.SyncApplicationRolesWithEcompDB(app); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.debugLogger, "failed syncRoles"); + } + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java index c150528e..3dba301a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/RolesApprovalSystemController.java @@ -78,7 +78,7 @@ public class RolesApprovalSystemController implements BasicAuthenticationControl } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile: failed for app {}, user {}", extSysUser.getApplicationName(), extSysUser.getLoginId(), e); - if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){ + if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404") && !e.getMessage().contains("405"))){ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed"); @@ -86,10 +86,14 @@ public class RolesApprovalSystemController implements BasicAuthenticationControl response.setStatus(HttpServletResponse.SC_NOT_FOUND); return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed"); - } else{ + } else if (e.getMessage().contains("405")) { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), + "save user profile failed"); + } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return new PortalRestResponse(PortalRestStatusEnum.ERROR, - e.getMessage(), "save user profile failed"); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), + "save user profile failed"); } } return new PortalRestResponse(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success"); @@ -117,7 +121,7 @@ public class RolesApprovalSystemController implements BasicAuthenticationControl } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile: failed for app {}, user {}", extSysUser.getApplicationName(), extSysUser.getLoginId(), e); - if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))){ + if(reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404") && !e.getMessage().contains("405"))){ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed"); @@ -125,6 +129,9 @@ public class RolesApprovalSystemController implements BasicAuthenticationControl response.setStatus(HttpServletResponse.SC_NOT_FOUND); return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed"); + } else if (e.getMessage().contains("405")) { + response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + return new PortalRestResponse(PortalRestStatusEnum.ERROR, e.getMessage(), "save user profile failed"); } else{ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return new PortalRestResponse(PortalRestStatusEnum.ERROR, diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java index 984bbf75..08a0d49b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/SharedContextRestController.java @@ -151,7 +151,7 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll SharedContext lastNameContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_LAST_NAME); SharedContext emailContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_EMAIL); - SharedContext attuidContext = contextService.getSharedContext(context_id, + SharedContext orgUserIdContext = contextService.getSharedContext(context_id, EPCommonSystemProperties.USER_ORG_USERID); if (firstNameContext != null) listSharedContext.add(firstNameContext); @@ -159,8 +159,8 @@ public class SharedContextRestController extends EPRestrictedRESTfulBaseControll listSharedContext.add(lastNameContext); if (emailContext != null) listSharedContext.add(emailContext); - if (attuidContext != null) - listSharedContext.add(attuidContext); + if (orgUserIdContext != null) + listSharedContext.add(orgUserIdContext); String jsonResponse = convertResponseToJSON(listSharedContext); return jsonResponse; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java index e0a9e587..102f7709 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/controller/TicketEventController.java @@ -36,8 +36,10 @@ import org.openecomp.portalapp.portal.logging.aop.EPAuditLog; import org.openecomp.portalapp.portal.service.UserNotificationService; import org.openecomp.portalapp.portal.transport.EpNotificationItem; import org.openecomp.portalapp.portal.transport.EpRoleNotificationItem; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @@ -62,6 +64,7 @@ import io.swagger.annotations.ApiOperation; @EPAuditLog public class TicketEventController implements BasicAuthenticationController { + @Autowired private UserNotificationService userNotificationService; @@ -73,6 +76,8 @@ public class TicketEventController implements BasicAuthenticationController { private final ObjectMapper mapper = new ObjectMapper(); + + @ApiOperation(value = "Accepts messages from external ticketing systems and creates notifications for Portal users.", response = PortalRestResponse.class) @RequestMapping(value = { "/ticketevent" }, method = RequestMethod.POST) public PortalRestResponse handleRequest(HttpServletRequest request, HttpServletResponse response, @@ -108,6 +113,12 @@ public class TicketEventController implements BasicAuthenticationController { } String eventSource = header.get("eventSource").asText(); epItem.setMsgSource(eventSource); + String ticket = body.get("ticketNum").asText(); + String hyperlink = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_SYSTEM_NOTIFICATION_URL)+eventSource+"num="+ticket; + if(body.get("notificationHyperlink")!=null){ + hyperlink=body.get("notificationHyperlink").asText(); + } + epItem.setNotificationHyperlink(hyperlink); epItem.setStartTime(new Date(eventDate)); Calendar calendar = Calendar.getInstance(); calendar.setTime(epItem.getStartTime()); @@ -171,14 +182,26 @@ public class TicketEventController implements BasicAuthenticationController { JsonNode header = event.get("header"); JsonNode body = event.get("body"); JsonNode SubscriberInfo = ticketEventNotif.get("SubscriberInfo"); + JsonNode userList = SubscriberInfo.get("UserList"); + if (application == null) - return "application is mandatory"; + return "Application is mandatory"; if (body == null) return "body is mandatory"; if (header.get("eventSource") == null) return "Message Source is mandatory"; - if (SubscriberInfo.get("UserList") == null) + if (userList == null) return "At least one user Id is mandatory"; + JsonNode eventDate=body.get("eventDate"); + + if(eventDate!=null&&eventDate.asText().length()==8) + return "EventDate is invalid"; + String UserIds[] = userList.toString().replace("[", "").replace("]", "").trim().replace("\"", "") + .split(","); + List users = userNotificationService.getUsersByOrgIds(Arrays.asList(UserIds)); + if(users==null||users.size()==0) + return "Invalid Attuid"; return null; } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/CentralRoleFunction.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/CentralRoleFunction.java new file mode 100644 index 00000000..2d659e9c --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/CentralRoleFunction.java @@ -0,0 +1,100 @@ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +@SuppressWarnings("rawtypes") +public class CentralRoleFunction extends DomainVo implements java.io.Serializable, Comparable{ + + /** + * + */ + private static final long serialVersionUID = -4018975640065252688L; + private String code; + private String name; + @JsonIgnore + private Long appId; + @JsonIgnore + private Long roleId; + private String editUrl; + + + public CentralRoleFunction() { + + } + + + public CentralRoleFunction(Long id, String code, String name, Long appId, String editUrl) { + super(); + this.id = id; + this.code = code; + this.name = name; + this.appId = appId; + this.editUrl = editUrl; + } + + public CentralRoleFunction(String code, String name) { + super(); + this.code = code; + this.name = name; + } + + /** + * @return the code + */ + public String getCode() { + return code; + } + /** + * @param code the code to set + */ + public void setCode(String code) { + this.code = code; + } + /** + * @return the name + */ + public String getName() { + return name; + } + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + /** + * @return the appId + */ + public Long getAppId() { + return appId; + } + /** + * @param appId the appId to set + */ + public void setAppId(Long appId) { + this.appId = appId; + } + /** + * @return the editUrl + */ + public String getEditUrl() { + return editUrl; + } + /** + * @param editUrl the editUrl to set + */ + public void setEditUrl(String editUrl) { + this.editUrl = editUrl; + } + public int compareTo(Object obj){ + String c1 = getName(); + String c2 = ((CentralRoleFunction)obj).getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java index b0cd13b2..edb3c905 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPApp.java @@ -51,8 +51,9 @@ public class EPApp extends DomainVo { private String uebKey; private String uebSecret; private Integer appType; - private AppContactUs contactUs; + private Boolean centralAuth; + private String nameSpace; public EPApp() { // Attention!!! @@ -282,6 +283,28 @@ public class EPApp extends DomainVo { public void setContactUs(AppContactUs contactUs) { this.contactUs = contactUs; } + + public Boolean getCentralAuth() { + return centralAuth; + } + + public void setCentralAuth(Boolean centralAuth) { + if (centralAuth == null) { + centralAuth = new Boolean(false); + } + this.centralAuth = centralAuth; + } + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + if (StringUtils.isEmpty(nameSpace)) { + nameSpace = null; + } + this.nameSpace = nameSpace; + } @Override public String toString() { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunction.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunction.java new file mode 100644 index 00000000..7665fd36 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPAppRoleFunction.java @@ -0,0 +1,50 @@ +package org.openecomp.portalapp.portal.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; + +public class EPAppRoleFunction extends DomainVo implements java.io.Serializable{ + + private static final long serialVersionUID = 7752385247460299630L; + + private Long roleId; + private Long appId; + private String code; + + /** + * @return the roleId + */ + public Long getRoleId() { + return roleId; + } + /** + * @param roleId the roleId to set + */ + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + /** + * @return the appId + */ + public Long getAppId() { + return appId; + } + /** + * @param appId the appId to set + */ + public void setAppId(Long appId) { + this.appId = appId; + } + /** + * @return the code + */ + public String getCode() { + return code; + } + /** + * @param code the code to set + */ + public void setCode(String code) { + this.code = code; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRoles.java similarity index 97% rename from ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java rename to ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRoles.java index 2649cfd0..574645e3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EpUserAppRoles.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EPUserAppRoles.java @@ -30,7 +30,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; @Entity @JsonInclude(JsonInclude.Include.NON_NULL) -public class EpUserAppRoles extends DomainVo { +public class EPUserAppRoles extends DomainVo { private static final long serialVersionUID = -1484592641766545668L; diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java index 6df37e82..24564aaa 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/EcompApp.java @@ -143,4 +143,26 @@ public class EcompApp { public void setRestrictedApp(Boolean restrictedApp) { this.restrictedApp = restrictedApp; } + + private Boolean centralAuth; + + public Boolean getCentralAuth() { + return centralAuth; + } + + public void setCentralAuth(Boolean centralAuth) { + this.centralAuth = centralAuth; + } + + private String nameSpace; + + public String getNameSpace() { + return nameSpace; + } + + public void setNameSpace(String nameSpace) { + this.nameSpace = nameSpace; + } + + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetails.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetails.java new file mode 100644 index 00000000..e30b5d36 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/domain/ExternalRoleDetails.java @@ -0,0 +1,78 @@ +package org.openecomp.portalapp.portal.domain; + +import java.util.List; + +public class ExternalRoleDetails implements Comparable { + + + private String name; + private boolean active; + private Integer priority; + + private Long appId; // used by ECOMP only + private Long appRoleId; // used by ECOMP only + + private List perms; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public Long getAppId() { + return appId; + } + + public void setAppId(Long appId) { + this.appId = appId; + } + + public Long getAppRoleId() { + return appRoleId; + } + + public void setAppRoleId(Long appRoleId) { + this.appRoleId = appRoleId; + } + + + + public List getPerms() { + return perms; + } + + public void setPerms(List perms) { + this.perms = perms; + } + + @Override + public int compareTo(Object obj) { + EPRole other = (EPRole)obj; + + String c1 = getName(); + String c2 = other.getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java index 89f1b92f..1db63fe8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java @@ -170,6 +170,8 @@ public class EPEELFLoggerAdvice { EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className); logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#after: finished {}", methodName); + // add the metrics log + logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed."); // Log security message, if necessary if (securityEventType != null) { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java index 82c3ad37..62519530 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPAppMessagesEnum.java @@ -25,7 +25,6 @@ import org.openecomp.portalsdk.core.logging.format.ErrorTypeEnum; /** * - * @author rc580q * Add ECOMP Portal Specific Error Code Enums here, for generic * ones (ones you think are useful not only Portal but also SDK), add it * to the enum class AppMessagesEnum defined in SDK. diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java index 498bfcfe..99a6c34a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/logging/format/EPErrorCodesEnum.java @@ -24,7 +24,6 @@ import com.att.eelf.i18n.EELFResourceManager; /** * - * @author rc580q * Add ECOMP Portal Specific Error Code Enums here, for generic * ones (ones you think are useful not only Portal but also SDK), add it * to the enum class AppMessagesEnum defined in SDK. diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java index 20daa4fc..b5bccfe3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/AdminRolesServiceImpl.java @@ -22,6 +22,7 @@ package org.openecomp.portalapp.portal.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.annotation.PostConstruct; @@ -29,14 +30,8 @@ import org.apache.cxf.common.util.StringUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.SystemProperties; +import org.json.JSONArray; +import org.json.JSONObject; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; @@ -48,8 +43,24 @@ import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; @Service("adminRolesService") @Transactional @@ -72,7 +83,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { SearchService searchService; @Autowired EPAppService appsService; - + + RestTemplate template = new RestTemplate(); + @PostConstruct private void init() { try { @@ -208,7 +221,9 @@ public class AdminRolesServiceImpl implements AdminRolesService { localSession.save(EPUserApp.class.getName(), newUserApp); } transaction.commit(); - result = true; + + // Add user admin role for list of centralized applications in external system + result = addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin); } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); logger.error(EELFLoggerDelegate.errorLogger, "setAppsWithAdminRoleStateForUser: exception in point 2", e); @@ -233,6 +248,129 @@ public class AdminRolesServiceImpl implements AdminRolesService { return result; } + @SuppressWarnings("unchecked") + private boolean addAdminRoleInExternalSystem(EPUser user, Session localSession, List newAppsWhereUserIsAdmin) { + boolean result = false; + try { + // Reset All admin role for centralized applications + List appList = dataAccessService.executeNamedQuery("getCentralizedApps", null, null); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (EPApp app : appList) { + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + try { + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/" + extRole, HttpMethod.GET, entity, String.class); + + if (getResponse.getBody().equals("{}")) { + String addDesc = "{\"name\":\"" + extRole + "\"}"; + HttpEntity roleEntity = new HttpEntity<>(addDesc, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role", + HttpMethod.POST, roleEntity, String.class); + } else { + try { + HttpEntity deleteUserRole = new HttpEntity<>(headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + extRole, + HttpMethod.DELETE, deleteUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, + " Role not found for this user may be it gets deleted before", e); + } + } + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Application Not found for app {}", + app.getNameSpace(), e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Application Not found for app {}", + app.getNameSpace(), e); + } + } + } + // Add admin role in external application + // application + for (AppNameIdIsAdmin appNameIdIsAdmin : newAppsWhereUserIsAdmin) { + EPApp app = (EPApp) localSession.get(EPApp.class, appNameIdIsAdmin.id); + try { + if (app.getCentralAuth()) { + String extRole = app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + HttpEntity entity = new HttpEntity<>(headers); + String name = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = user.getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity getUserRolesResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRoles/user/" + name, + HttpMethod.GET, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + if (!getUserRolesResponse.getBody().equals("{}")) { + JSONObject jsonObj = new JSONObject(getUserRolesResponse.getBody()); + JSONArray extRoles = jsonObj.getJSONArray("userRole"); + final Map extUserRoles = new HashMap<>(); + for (int i = 0; i < extRoles.length(); i++) { + String userRole = extRoles.getJSONObject(i).getString("role"); + if (userRole.startsWith(app.getNameSpace() + ".") + && !userRole.equals(app.getNameSpace() + ".admin") + && !userRole.equals(app.getNameSpace() + ".owner")) { + + extUserRoles.put(userRole, extRoles.getJSONObject(i)); + } + } + if (!extUserRoles.containsKey(extRole)) { + // Assign with new apps user admin + try { + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + // Assign user role for an application in external access system + ObjectMapper addUserRoleMapper = new ObjectMapper(); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpEntity addUserRole = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, addUserRole, String.class); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user admin role", e); + } + + } + } + } + result = true; + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.errorLogger, + "Application name space not found in External system for app {} due to bad rquest name space ", app.getNameSpace(), + e.getMessage()); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin role for application {}", + app.getNameSpace(), e); + result = false; + } + } + } + } catch (Exception e) { + result = false; + logger.error(EELFLoggerDelegate.errorLogger, "Failed to assign admin roles operation", e); + } + return result; + } + @SuppressWarnings("unchecked") @Override public boolean isSuperAdmin(EPUser user) { @@ -318,7 +456,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { @EPMetricsLog public List getRolesByApp(EPUser user, Long appId) { List list = new ArrayList<>(); - String sql = "SELECT * FROM FN_ROLE WHERE APP_ID = " + appId; + String sql = "SELECT * FROM FN_ROLE WHERE UPPER(ACTIVE_YN) = 'Y' AND APP_ID = " + appId; @SuppressWarnings("unchecked") List roles = dataAccessService.executeSQLQuery(sql, EPRole.class, null); for (EPRole role: roles) { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java index f38b921a..6a0da9ba 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -44,6 +44,8 @@ import org.openecomp.portalapp.portal.domain.AppIdAndNameTransportModel; import org.openecomp.portalapp.portal.domain.AppsResponse; import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; +import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; import org.openecomp.portalapp.portal.domain.EPUserAppsManualSortPreference; import org.openecomp.portalapp.portal.domain.EPUserAppsSortPreference; import org.openecomp.portalapp.portal.domain.EPWidgetsManualSortPreference; @@ -180,6 +182,8 @@ public class EPAppCommonServiceImpl implements EPAppService { ecompApp.setUebKey(app.getUebKey()); ecompApp.setUebSecret(app.getUebSecret()); ecompApp.setEnabled(app.getEnabled()); + ecompApp.setCentralAuth(app.getCentralAuth()); + ecompApp.setNameSpace(app.getNameSpace()); ecompApp.setRestrictedApp(app.isRestrictedApp()); ecompAppList.add(ecompApp); } @@ -322,15 +326,10 @@ public class EPAppCommonServiceImpl implements EPAppService { @Override public UserRoles getUserProfile(String loginId) { - String format = "SELECT DISTINCT user.USER_ID, role.ROLE_ID, user.org_user_id, user.FIRST_NAME, user.LAST_NAME, role.ROLE_NAME FROM fn_user_role userrole " - + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " - + "INNER JOIN fn_role role ON role.ROLE_ID = userrole.ROLE_ID " - + "WHERE user.org_user_id = \"%s\" and (userrole.app_id = 1 or role.role_id = " + ACCOUNT_ADMIN_ROLE_ID - + ") "; - String sql = String.format(format, loginId); - logQuery(sql); + final Map params = new HashMap<>(); + params.put("org_user_id", loginId); @SuppressWarnings("unchecked") - List userRoleList = dataAccessService.executeSQLQuery(sql, UserRole.class, null); + List userRoleList = dataAccessService.executeNamedQuery( "getUserRoles", params, null); ArrayList usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList); if (usersRolesList == null || usersRolesList.size() < 1) return null; @@ -382,9 +381,11 @@ public class EPAppCommonServiceImpl implements EPAppService { public List getAppRoles(Long appId) { String sql = ""; if (isRestrictedApp(appId)) { - sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'"; - } else { - sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where APP_ID = '" + appId + "'"; + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + RESTRICTED_APP_ROLE_ID + "'"; + }else if(appId == 1){ + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL"; + }else{ + sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + appId + "'"; } logQuery(sql); @SuppressWarnings("unchecked") @@ -475,8 +476,8 @@ public class EPAppCommonServiceImpl implements EPAppService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog(com.att - * .fusionapp.ecomp.portal.domain.EPUser) + * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog( + * org.openecomp.portalapp.portal.domain.EPUser) */ @Override public List getUserAppCatalog(EPUser user) { @@ -721,6 +722,7 @@ public class EPAppCommonServiceImpl implements EPAppService { return fieldsValidator; } + @SuppressWarnings("unchecked") @Override public FieldsValidator deleteOnboardingApp(EPUser user, Long appid) { FieldsValidator fieldsValidator = new FieldsValidator(); @@ -728,6 +730,16 @@ public class EPAppCommonServiceImpl implements EPAppService { fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_FORBIDDEN); return fieldsValidator; } + final Map params = new HashMap<>(); + params.put("app_id", appid); + List EPUserAppRolesRequestList= new ArrayList<>(); + EPUserAppRolesRequestList = dataAccessService.executeNamedQuery( "getRequestIdsForApp", params, null); + for(int i=0;i getUserRemoteApps(String id) { throw new RuntimeException(" Cannot be called from parent class"); } + + @Override + public UserRoles getUserProfileForLeftMenu(String loginId) { + final Map params = new HashMap<>(); + params.put("org_user_id", loginId); + @SuppressWarnings("unchecked") + List userRoleList = dataAccessService.executeNamedQuery( "getUserRolesForLeftMenu", params, null); + ArrayList usersRolesList = aggregateUserProfileRowsResultsByRole(userRoleList); + if (usersRolesList == null || usersRolesList.size() < 1) + return null; + + return usersRolesList.get(0); + } + + + @Override + public UserRoles getUserProfileNormalizedForLeftMenu(EPUser user) { + // Check database. + UserRoles userAndRoles = getUserProfileForLeftMenu(user.getLoginId()); + // If no roles are defined, treat this user as a guest. + if (user.isGuest() || userAndRoles == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "getUserProfileForLeftMenu: treating user {} as guest", + user.getLoginId()); + UserRole userRole = new UserRole(); + userRole.setUser_Id(user.getId()); + userRole.setOrgUserId(user.getLoginId()); + userRole.setFirstName(user.getFirstName()); + userRole.setLastName(user.getLastName()); + userRole.setRoleId(-1L); + userRole.setRoleName("Guest"); + userRole.setUser_Id(-1L); + userAndRoles = new UserRoles(userRole); + } + + return userAndRoles; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java index 1e12dd52..3ab12983 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPAppService.java @@ -97,7 +97,7 @@ public interface EPAppService { * the user has a defined role for that app. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's list of applications, which may be empty. */ List getUserApps(EPUser user); @@ -109,7 +109,7 @@ public interface EPAppService { * applications which the user has chosen to show. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's personalized list of applications, which may be empty. */ List getPersAdminApps(EPUser user); @@ -122,7 +122,7 @@ public interface EPAppService { * result. * * @param user - * EPUser object with the user's ATT UID + * EPUser object with the user's Org User ID * @return the user's personalized list of applications, which may be empty. */ List getPersUserApps(EPUser user); @@ -210,4 +210,8 @@ public interface EPAppService { void createOnboardingFromApp(EPApp app, OnboardingApp onboardingApp); + UserRoles getUserProfileNormalizedForLeftMenu(EPUser user); + + UserRoles getUserProfileForLeftMenu(String loginId); + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java index 9158e990..f24ab87f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPLeftMenuServiceImpl.java @@ -73,7 +73,7 @@ public class EPLeftMenuServiceImpl implements EPLeftMenuService { // be revised as Account Administrator may become obsolete try { if (user != null) { - UserRoles uRoles = appService.getUserProfileNormalized(user); + UserRoles uRoles = appService.getUserProfileNormalizedForLeftMenu(user); if (uRoles.getRoles().contains("Account Administrator")) loadAccAdminNavMap(defaultNavMap); } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java new file mode 100644 index 00000000..66a9ccc2 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionService.java @@ -0,0 +1,31 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +public interface EPRoleFunctionService { + /** + * Builds a set of role functions and sets a session attribute with it. + * + * @param request + * HttpServletRequest + * @return Set of role functions that was built. + */ + public List getRoleFunctions(); + + + /** + * Builds a set of role functions of user + * + * @param request + * HttpServletRequest + * @return Set of role functions that was built. + */ + public Set getRoleFunctions(HttpServletRequest request, EPUser user); + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java new file mode 100644 index 00000000..d41100ff --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceCentralizedImpl.java @@ -0,0 +1,70 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.hibernate.SessionFactory; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + + +@Transactional +public class EPRoleFunctionServiceCentralizedImpl implements EPRoleFunctionService{ + + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings({ "unchecked"}) + @Override + public List getRoleFunctions() { + List getRoleFuncList = null; + List getRoleFuncListOfPortal = new ArrayList<>(); + final Map params = new HashMap<>(); + params.put("appId", (long) 1); + //Sync all functions from external system into Ecomp portal DB + getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); + for(CentralRoleFunction roleFunction : getRoleFuncList) + { + RoleFunction roleFun = new RoleFunction(); + roleFun.setCode(roleFunction.getCode()); + roleFun.setName(roleFunction.getName()); + getRoleFuncListOfPortal.add(roleFun); + } + return getRoleFuncListOfPortal; + } + + @SuppressWarnings("unchecked") + @Override + public Set getRoleFunctions(HttpServletRequest request, EPUser user) { + HttpSession session = request.getSession(); + String userId = user.getId().toString(); + final Map params = new HashMap<>(); + params.put("userId", userId); + @SuppressWarnings("unchecked") + List getRoleFuncListOfPortal = dataAccessService.executeNamedQuery("getRoleFunctionsOfUser", params, null); + Set getRoleFuncListOfPortalSet = new HashSet<>(getRoleFuncListOfPortal); + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + getRoleFuncListOfPortalSet); + return getRoleFuncListOfPortalSet; + + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java new file mode 100644 index 00000000..f36aa544 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/EPRoleFunctionServiceImpl.java @@ -0,0 +1,79 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.util.EPUserUtils; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class EPRoleFunctionServiceImpl implements EPRoleFunctionService { + @Autowired + private DataAccessService dataAccessService; + + + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + @SuppressWarnings("unchecked") + @Override + public List getRoleFunctions() { + return getDataAccessService().getList(RoleFunction.class, null); + } + + @SuppressWarnings("unchecked") + @Override + public Set getRoleFunctions(HttpServletRequest request, EPUser user) { + HashSet roleFunctions = null; + + HttpSession session = request.getSession(); + roleFunctions = (HashSet) session + .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); + + if (roleFunctions == null) { + HashMap roles = EPUserUtils.getRoles(request); + roleFunctions = new HashSet(); + + Iterator i = roles.keySet().iterator(); + + while (i.hasNext()) { + Long roleKey = (Long) i.next(); + EPRole role = (EPRole) roles.get(roleKey); + + Iterator j = role.getRoleFunctions().iterator(); + + while (j.hasNext()) { + RoleFunction function = (RoleFunction) j.next(); + roleFunctions.add(function.getCode()); + } + } + + session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), + roleFunctions); + } + + return roleFunctions; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java new file mode 100644 index 00000000..e57d4fa5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesService.java @@ -0,0 +1,190 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.List; + +import org.hibernate.Session; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; + +public interface ExternalAccessRolesService { + + /** + * It gets all application roles + * + * @param appId + * @param extRequestValue + * @return List + * @throws Exception + */ + public List getAppRoles(Long appId, Boolean extRequestValue) throws Exception; + + /** + * It returns application details + * + * @param uebkey + * @return List + * @throws Exception + */ + public List getApp(String uebkey) throws Exception; + + /** + * Adds role in the external access system if fails throws exception + * + * @param addRoles + * @param UE + * @return boolean + * @throws Exception + */ + public boolean addRole(Role addRoles, String uebkey) throws Exception; + + /** + * Updates role in the external access system otherwise throws exception + * + * @param updateRole + * @param uebkey + * @return boolean + * @throws Exception + */ + void updateRole(Role updateRole, EPApp app) throws Exception; + + /** + * It returns complete user information including application roles permissions + * + * @param loginId + * @param uebkey + * @return String + * @throws Exception + */ + String getUser(String loginId, String uebkey) throws Exception; + + /** + * It returns list of all role functions + * @param string + * @return List + * @throws Exception + */ + List getRoleFuncList(String string) throws Exception; + + /** + * It return list of role provided by the app uebkey and roleId + * + * @param roleId + * @param uebkey + * @return CentralRole + * @throws Exception + */ + CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception; + + /** + * It returns the CentralRoleFunction object + * + * @param functionCode + * @param uebkey + * @return CentralRoleFunction + * @throws Exception + */ + public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception; + + /** + * It saves role function in the DB + * + * @param domainCentralRoleFunction + * @param requestedApp + * @throws Exception + */ + public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp requestedApp) throws Exception; + + /** + * It deletes role function in the DB + * + * @param code + * @param string + */ + public void deleteCentralRoleFunction(String code, String string); + + /** + * It gets all roles the applications + * + * @param uebkey + * @return List + * @throws Exception + */ + public List getRolesForApp(String uebkey) throws Exception; + + /** + * It saves role function in the DB + * + * @param saveRole + * @param uebkey + * @throws Exception + */ + void saveRoleForApplication(Role saveRole, String uebkey) throws Exception; + + /** + * It deletes role in the DB + * + * @param code + * @param uebkey + * @throws Exception + */ + void deleteRoleForApplication(String code, String uebkey) throws Exception; + + /** + * It gets all active roles for single application + * + * @param uebkey + * @return List + * @throws Exception + */ + List getActiveRoles(String uebkey) throws Exception; + + /** + * It deletes user related roles for an application in the table + * @param roleId + * @param uebkey + * @param LoginId + * @return + * @throws Exception + */ + public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception; + + /** + * It sync new functions codes and names from and updates role functions from external access system + * + * @param app + * @throws Exception + */ + public void syncRoleFunctionFromExternalAccessSystem(EPApp app) throws Exception; + + public Integer bulkUploadFunctions(String uebkey) throws Exception; + + public Integer bulkUploadRoles(String uebkey) throws Exception; + + public void bulkUploadPartnerFunctions(String header, List upload) throws Exception; + + public void bulkUploadPartnerRoles(String header, List upload) throws Exception; + + Integer bulkUploadRolesFunctions(String uebkey) throws Exception; + + /** + * SyncApplicationRolesWithEcompDB sync the roles and rolefunctions to the ecomp DB from AAF + * @param app + * @throws Exception + */ + + void SyncApplicationRolesWithEcompDB(EPApp app) throws Exception; + + public Integer bulkUploadUserRoles(String uebkey) throws Exception; + + void bulkUploadPartnerRoleFunctions(String uebkey, List roleList) throws Exception; + + public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception; + + List getMenuFunctionsList(String uebkey) throws Exception; + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java new file mode 100644 index 00000000..17d9ceb0 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -0,0 +1,1678 @@ +package org.openecomp.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPApp; +import org.openecomp.portalapp.portal.domain.EPAppRoleFunction; +import org.openecomp.portalapp.portal.domain.EPRole; +import org.openecomp.portalapp.portal.domain.EPUser; +import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.domain.ExternalRoleDetails; +import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.BulkUploadRoleFunction; +import org.openecomp.portalapp.portal.transport.BulkUploadUserRoles; +import org.openecomp.portalapp.portal.transport.CentralApp; +import org.openecomp.portalapp.portal.transport.CentralRole; +import org.openecomp.portalapp.portal.transport.CentralUser; +import org.openecomp.portalapp.portal.transport.CentralUserApp; +import org.openecomp.portalapp.portal.transport.ExternalAccessPerms; +import org.openecomp.portalapp.portal.transport.ExternalAccessPermsDetail; +import org.openecomp.portalapp.portal.transport.ExternalAccessRole; +import org.openecomp.portalapp.portal.transport.ExternalAccessRolePerms; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; +import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; +import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.RoleFunction; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; + +@Service("externalAccessRolesService") +@EnableAspectJAutoProxy +@EPMetricsLog +public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesService { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesServiceImpl.class); + + @Autowired + private DataAccessService dataAccessService; + + @Autowired + private SessionFactory sessionFactory; + + + RestTemplate template = new RestTemplate(); + + @SuppressWarnings("unchecked") + public List getAppRoles(Long appId, Boolean extRequestValue) throws Exception { + List applicationRoles = null; + String filter = null; + try { + if (appId == 1) { + filter = " where app_id is null"; + } else { + filter = " where app_id = " + appId; + } + applicationRoles = dataAccessService.getList(EPRole.class, filter, null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles is failed", e); + throw new Exception(e.getMessage()); + } + return applicationRoles; + } + + @SuppressWarnings("unchecked") + @Override + public List getApp(String uebkey) throws Exception { + List app = null; + try { + app = (List) dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebkey + "'", null, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getApp is failed", e); + throw new Exception(e.getMessage()); + } + return app; + } + + public String getSingleAppRole(String addRole, EPApp app) throws Exception { + String response = ""; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/" + + app.getNameSpace() + "." + addRole.replaceAll(" ", "_"), + HttpMethod.GET, entity, String.class) + .getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + + return response; + } + + @Override + public boolean addRole(Role addRole, String uebkey) throws Exception { + boolean response = false; + ResponseEntity addResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + EPApp app = getApp(uebkey).get(0); + String newRole = createNewRoleInExternalSystem(addRole, app); + HttpEntity entity = new HttpEntity<>(newRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() == 201) { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + if (addResponse.getStatusCode().value() == 406) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system but something went wrong!"); + throw new Exception("Failed to create role"); + } + return response; + } + + @Override + public void updateRole(Role addRole, EPApp app) throws Exception { + boolean addResponse = updateRoleInExternalSystem(addRole, app); + if (!addResponse) { + throw new Exception("Failed to update a role"); + } + } + + private ResponseEntity deleteRoleInExternalSystem(String delRole) throws Exception { + ResponseEntity delResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(delRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + delResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true", + HttpMethod.DELETE, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + return delResponse; + } + + @SuppressWarnings("unchecked") + private boolean updateRoleInExternalSystem(Role updateExtRole, EPApp app) throws Exception { + boolean response = false; + ObjectMapper mapper = new ObjectMapper(); + ResponseEntity deleteResponse = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + List epRoleList = null; + epRoleList = dataAccessService.getList(EPRole.class, + " where role_id = " + updateExtRole.getId(), null, null); + String appRole = getSingleAppRole(epRoleList.get(0).getName(), app); + if (!appRole.equals("{}")) { + JSONObject jsonObj = new JSONObject(appRole); + JSONArray extRole = jsonObj.getJSONArray("role"); + if (!extRole.getJSONObject(0).has("description")) { + String roleName = extRole.getJSONObject(0).getString("name"); + String delRoleKey = "{\"name\":\"" + roleName + "\"}"; + deleteResponse = deleteRoleInExternalSystem(delRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + addRole(updateExtRole, app.getUebKey()); + } else { + String desc = extRole.getJSONObject(0).getString("description"); + String name = extRole.getJSONObject(0).getString("name"); + List list = null; + if (extRole.getJSONObject(0).has("perms")) { + JSONArray perms = extRole.getJSONObject(0).getJSONArray("perms"); + ObjectMapper permsMapper = new ObjectMapper(); + list = permsMapper.readValue(perms.toString(), TypeFactory.defaultInstance() + .constructCollectionType(List.class, ExternalAccessPerms.class)); + } + ObjectMapper roleMapper = new ObjectMapper(); + ExternalRoleDescription sysRoleList = roleMapper.readValue(desc, ExternalRoleDescription.class); + // If role name or role functions are updated then delete record in External System and add new record to avoid conflicts + Boolean existingRoleActive; + boolean res; + // check role active status + existingRoleActive = new Boolean(sysRoleList.getActive()); + res = existingRoleActive.equals(updateExtRole.getActive()); + if (!sysRoleList.getName().equals(updateExtRole.getName())) { + String deleteRoleKey = "{\"name\":\"" + name + "\"}"; + deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + response = addRole(updateExtRole, app.getUebKey()); + ObjectMapper addPermsMapper = new ObjectMapper(); + response = addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + } + ExternalAccessRole updateRole = new ExternalAccessRole(); + if (!res || !sysRoleList.getPriority().equals(String.valueOf(updateExtRole.getPriority())) || + sysRoleList.getId().equals("null")) { + String updateDesc = ""; + List getRole = dataAccessService.getList(EPRole.class, + " where role_name = '" + updateExtRole.getName() + "'", null, null); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() + + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" + + updateExtRole.getPriority() + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; + + } else { + updateDesc = "{\"id\":\"" + getRole.get(0).getId() + "\",\"name\":\"" + updateExtRole.getName() + + "\",\"active\":\"" + updateExtRole.getActive() + "\",\"priority\":\"" + + updateExtRole.getPriority() + "\",\"appId\":\"" + app.getId() + "\",\"appRoleId\":\"" + + getRole.get(0).getAppRoleId() + "\"}"; + + } + updateRole.setName(app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + updateRole.setDescription(updateDesc); + String updateRoleDesc = mapper.writeValueAsString(updateRole); + HttpEntity entity = new HttpEntity<>(updateRoleDesc, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + List roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole); + Map updateRoleFunc = new HashMap<>(); + for (RoleFunction addPerm : roleFunctionListNew) { + updateRoleFunc.put(addPerm.getCode(), addPerm); + } + final Map extRolePermMap = new HashMap<>(); + // Update permissions in the ExternalAccess System + ObjectMapper permMapper = new ObjectMapper(); + if (list != null) { + for (ExternalAccessPerms perm : list) { + if (!updateRoleFunc.containsKey(perm.getInstance())) { + removePermForRole(perm, permMapper, name, headers); + } + extRolePermMap.put(perm.getInstance(), perm); + } + } + response = true; + if (!roleFunctionListNew.isEmpty() || roleFunctionListNew.size() > 0) { + for (RoleFunction roleFunc : roleFunctionListNew) { + if (!extRolePermMap.containsKey(roleFunc.getCode())) { + String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), + "*"); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + response = false; + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + } + } + } + } else { + // It seems like role exists in local DB but not in External Access system + addRole(updateExtRole, app.getUebKey()); + List roleFunctionListUpdate = convertSetToListOfRoleFunctions(updateExtRole); + response = true; + if (!roleFunctionListUpdate.isEmpty() || roleFunctionListUpdate.size() > 0) { + ObjectMapper addPermsMapper = new ObjectMapper(); + addRoleFunctionsInExternalSystem(updateExtRole, addPermsMapper, app); + } + } + return response; + } + + private boolean addRoleFunctionsInExternalSystem(Role updateExtRole, ObjectMapper addPermsMapper, EPApp app) throws Exception { + boolean response = false; + ExternalAccessRolePerms extAddRolePerms = null; + ExternalAccessPerms extAddPerms = null; + List roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (RoleFunction roleFunc : roleFunctionListAdd) { + String checkType = roleFunc.getCode().contains("menu") ? "menu" : "url"; + extAddPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunc.getCode(), + "*"); + extAddRolePerms = new ExternalAccessRolePerms(extAddPerms, + app.getNameSpace() + "." + updateExtRole.getName().replaceAll(" ", "_")); + String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", + HttpMethod.POST, entity, String.class); + if (addResponse.getStatusCode().value() != 201) { + response = false; + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to External Access system but something went wrong! due to {} and statuscode: {}", addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value()); + } else { + response = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + return response; + } + + @SuppressWarnings("unchecked") + private List convertSetToListOfRoleFunctions(Role updateExtRole){ + Set roleFunctionSetList = updateExtRole.getRoleFunctions(); + List roleFunctionList = new ArrayList<>(); + ObjectMapper roleFuncMapper = new ObjectMapper(); + Iterator itetaror = roleFunctionSetList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, RoleFunction.class); + roleFunctionList.add(roleFunction); + } + return roleFunctionList.stream().distinct().collect(Collectors.toList()); + } + + private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper,String name, HttpHeaders headers) throws Exception { + ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name); + String permDetails = permMapper.writeValueAsString(extAccessRolePerms); + HttpEntity deleteEntity = new HttpEntity<>(permDetails, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity deletePermResponse = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/"+name+"/perm", HttpMethod.DELETE, deleteEntity, String.class); + if (deletePermResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role function"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + + private boolean addNewRoleInExternalSystem(List newRole, EPApp app) throws Exception { + boolean response = false; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + String addDesc = null; + addDesc = "{\"id\":\"" + newRole.get(0).getId() + "\",\"name\":\"" + newRole.get(0).getName() + "\",\"active\":\"" + + newRole.get(0).getActive() + "\",\"priority\":\"" +newRole.get(0).getPriority() + "\",\"appId\":\"" + + newRole.get(0).getAppId() + "\",\"appRoleId\":\"" + newRole.get(0).getAppRoleId() + "\"}"; + + extRole.setName(app.getNameSpace() + "." + newRole.get(0).getName().replaceAll(" ", "_")); + extRole.setDescription(addDesc); + addNewRole = mapper.writeValueAsString(extRole); + HttpEntity deleteEntity = new HttpEntity<>(addNewRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity addNewRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role", HttpMethod.POST, deleteEntity, String.class); + if (addNewRoleInExternalSystem.getStatusCode().value() != 201) { + throw new Exception("Failed to add Role in External System"); + } else{ + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + response = true; + } + return response; + } + + @SuppressWarnings("unchecked") + private String createNewRoleInExternalSystem(Role addRole, EPApp app) throws JsonProcessingException { + ObjectMapper mapper = new ObjectMapper(); + String addNewRole = ""; + ExternalAccessRole extRole = new ExternalAccessRole(); + List role = null; + String addDesc = null; + if(app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + role = dataAccessService.getList(EPRole.class, + " where role_id = " + addRole.getId(), null, null); + addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" + + role.get(0).getActive() + "\",\"priority\":\"" + role.get(0).getPriority() + + "\",\"appId\":\"null\",\"appRoleId\":\"null\"}"; + } else{ + role = dataAccessService.getList(EPRole.class, + " where app_role_id = " + addRole.getId(), null, null); + addDesc = "{\"id\":\"" + role.get(0).getId() + "\",\"name\":\"" + addRole.getName() + "\",\"active\":\"" + + role.get(0).getActive() + "\",\"priority\":\"" + addRole.getPriority() + "\",\"appId\":\"" + + app.getId() + "\",\"appRoleId\":\"" + role.get(0).getAppRoleId() + "\"}"; + } + extRole.setName(app.getNameSpace() + "." + addRole.getName().replaceAll(" ", "_")); + extRole.setDescription(addDesc); + addNewRole = mapper.writeValueAsString(extRole); + return addNewRole; + } + + @SuppressWarnings("unchecked") + @Transactional + private boolean addRoleInEcompDB(Role addRoleInDB, EPApp app) throws Exception { + boolean result = false; + List applicationRoles = null; + EPRole epRole = null; + Set roleFunctionList = addRoleInDB.getRoleFunctions(); + List roleFunctionListNew = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + Iterator itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = mapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList()); + try { + if (addRoleInDB.getId() == null) { // check if it is new role + checkIfRoleExitsInExternalSystem(addRoleInDB, app); + EPRole epRoleNew = new EPRole(); + epRoleNew.setActive(addRoleInDB.getActive()); + epRoleNew.setName(addRoleInDB.getName()); + epRoleNew.setPriority(addRoleInDB.getPriority()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRoleNew.setAppId(null); + } else { + epRoleNew.setAppId(app.getId()); + } + dataAccessService.saveDomainObject(epRoleNew, null); + List getRoleCreated = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + List roleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + EPRole epUpdateRole = roleCreated.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + getRoleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + } else{ + getRoleCreated = dataAccessService.getList(EPRole.class, + " where role_name = '" + addRoleInDB.getName() +"'", null, null); + } + // Add role in External Access system + boolean response = addNewRoleInExternalSystem(getRoleCreated, app); + + if (!response) { + throw new Exception("Failed to add role!"); + } + } else { // if role already exists then update it + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_id = " + addRoleInDB.getId(), null, null); + } else { + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and app_role_id = " + addRoleInDB.getId(), null, null); + } + if(applicationRoles.isEmpty() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + applicationRoles = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_id = " + addRoleInDB.getId(), null, null); + } + updateRoleInExternalSystem(addRoleInDB, app); + deleteRoleFunction(app, applicationRoles); + if (applicationRoles.size() > 0 || !applicationRoles.isEmpty()) { + epRole = applicationRoles.get(0); + epRole.setName(addRoleInDB.getName()); + epRole.setPriority(addRoleInDB.getPriority()); + epRole.setActive(addRoleInDB.getActive()); + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRole.setAppId(null); + epRole.setAppRoleId(null); + } else if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && applicationRoles.get(0).getAppRoleId() == null){ + epRole.setAppRoleId(epRole.getId()); + } + dataAccessService.saveDomainObject(epRole, null); + } + + saveRoleFunction(listWithoutDuplicates, app, applicationRoles); + } + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e); + throw new Exception(e.getMessage()); + } + return result; + } + + private void checkIfRoleExitsInExternalSystem(Role checkRole, EPApp app) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + String roleName = app.getNameSpace()+"."+checkRole.getName().replaceAll(" ", "_"); + HttpEntity checkRoleEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity checkRoleInExternalSystem = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/"+roleName, HttpMethod.GET, checkRoleEntity, String.class); + if(!checkRoleInExternalSystem.getBody().equals("{}")){ + logger.debug("Role already exists in external system ", checkRoleInExternalSystem.getBody()); + throw new Exception("Role already exists in external system"); + } + } + + private void saveRoleFunction(List roleFunctionListNew, EPApp app, List applicationRoles) throws Exception { + for (RoleFunction roleFunc : roleFunctionListNew) { + EPAppRoleFunction appRoleFunc = new EPAppRoleFunction(); + appRoleFunc.setAppId(app.getId()); + appRoleFunc.setRoleId(applicationRoles.get(0).getId()); + appRoleFunc.setCode(roleFunc.getCode()); + dataAccessService.saveDomainObject(appRoleFunc, null); + } + } + + @SuppressWarnings("unchecked") + private void deleteRoleFunction(EPApp app, List role) { + List appRoleFunctionList = dataAccessService.getList(EPAppRoleFunction.class, + " where app_id = " + app.getId() + " and role_id = " + role.get(0).getId(), null, null); + if (!appRoleFunctionList.isEmpty() || appRoleFunctionList.size() > 0) { + for (EPAppRoleFunction approleFunction : appRoleFunctionList) { + dataAccessService.deleteDomainObject(approleFunction, null); + } + } + } + + @SuppressWarnings("unchecked") + public String getUser(String loginId, String uebkey) throws Exception { + final Map params = new HashMap<>(); + List userList = null; + CentralUser cenUser = null; + EPApp app = null; + String result = null; + try { + params.put("orgUserIdValue", loginId); + List appList = (List) getApp(uebkey); + if (appList.size() > 0) { + app = appList.get(0); + userList = (List) dataAccessService.getList(EPUser.class, + " where org_user_id = '" + loginId + "'", null, null); + if (userList.size() > 0) { + EPUser user = userList.get(0); + ObjectMapper mapper = new ObjectMapper(); + Set userAppSet = user.getEPUserApps(); + cenUser = createEPUser(user, userAppSet, app); + result = mapper.writeValueAsString(cenUser); + } else if (userList.size() == 0) { + throw new Exception("User not found"); + } + } else { + throw new Exception("Application not found"); + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUser is failed", e); + throw new Exception(e.getMessage()); + } + return result; + } + + @Override + public List getRolesForApp(String uebkey) throws Exception { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getRolesForApp"); + List roleList = new ArrayList<>(); + final Map params = new HashMap<>(); + try { + List app = getApp(uebkey); + List appRolesList = getAppRoles(app.get(0).getId(), null); + createCentralRoleObject(app, appRolesList, roleList, params); + } catch (Exception e) { + throw new Exception("getRolesForApp Failed", e); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished getRolesForApp"); + return roleList; + } + + @SuppressWarnings("unchecked") + @Override + public List getRoleFuncList(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List getRoleFuncList = null; + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + //Sync all functions from external system into Ecomp portal DB + logger.debug(EELFLoggerDelegate.debugLogger, "Entering into syncRoleFunctionFromExternalAccessSystem"); + syncRoleFunctionFromExternalAccessSystem(app); + logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); + getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); + return getRoleFuncList; + } + + @SuppressWarnings("unchecked") + public CentralUser createEPUser(EPUser userInfo, Set userAppSet, EPApp app) throws Exception { + + final Map params = new HashMap<>(); + CentralUser userAppList = new CentralUser(); + CentralUser user1 = null; + try { + userAppList.userApps = new TreeSet(); + for (EPUserApp userApp : userAppSet) { + if (userApp.getRole().getActive()) { + EPApp epApp = userApp.getApp(); + String globalRole = userApp.getRole().getName().toLowerCase(); + if (((epApp.getId().equals(app.getId())) + && (!userApp.getRole().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID))) + || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) + && (globalRole.startsWith("global_")))) { + CentralUserApp cua = new CentralUserApp(); + cua.setUserId(null); + CentralApp cenApp = new CentralApp(1L, epApp.getCreated(), epApp.getModified(), + epApp.getCreatedId(), epApp.getModifiedId(), epApp.getRowNum(), epApp.getName(), + epApp.getImageUrl(), epApp.getDescription(), epApp.getNotes(), epApp.getUrl(), + epApp.getAlternateUrl(), epApp.getAppRestEndpoint(), epApp.getMlAppName(), + epApp.getMlAppAdminId(), String.valueOf(epApp.getMotsId()), epApp.getAppPassword(), + String.valueOf(epApp.getOpen()), String.valueOf(epApp.getEnabled()), + epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(), + epApp.getUebTopicName()); + cua.setApp(cenApp); + params.put("roleId", userApp.getRole().getId()); + params.put("appId", userApp.getApp().getId()); + List appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet roleFunctionSet = new TreeSet(); + for (CentralRoleFunction roleFunc : appRoleFunctionList) { + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(roleFunc.getId(), + roleFunc.getCode(), roleFunc.getName(), null, null); + roleFunctionSet.add(cenRoleFunc); + } + CentralRole cenRole = new CentralRole(userApp.getRole().getAppRoleId(), + userApp.getRole().getCreated(), userApp.getRole().getModified(), + userApp.getRole().getCreatedId(), userApp.getRole().getModifiedId(), + userApp.getRole().getRowNum(), userApp.getRole().getName(), + userApp.getRole().getActive(), userApp.getRole().getPriority(), roleFunctionSet, null, + null); + cua.setRole(cenRole); + + userAppList.userApps.add(cua); + } + } + } + + user1 = new CentralUser(null, userInfo.getCreated(), userInfo.getModified(), userInfo.getCreatedId(), + userInfo.getModifiedId(), userInfo.getRowNum(), userInfo.getOrgId(), userInfo.getManagerId(), + userInfo.getFirstName(), userInfo.getMiddleInitial(), userInfo.getLastName(), userInfo.getPhone(), + userInfo.getFax(), userInfo.getCellular(), userInfo.getEmail(), userInfo.getAddressId(), + userInfo.getAlertMethodCd(), userInfo.getHrid(), userInfo.getOrgUserId(), userInfo.getOrgCode(), + userInfo.getAddress1(), userInfo.getAddress2(), userInfo.getCity(), userInfo.getState(), + userInfo.getZipCode(), userInfo.getCountry(), userInfo.getOrgManagerUserId(), + userInfo.getLocationClli(), userInfo.getBusinessCountryCode(), userInfo.getBusinessCountryName(), + userInfo.getBusinessUnit(), userInfo.getBusinessUnitName(), userInfo.getDepartment(), + userInfo.getDepartmentName(), userInfo.getCompanyCode(), userInfo.getCompany(), + userInfo.getZipCodeSuffix(), userInfo.getJobTitle(), userInfo.getCommandChain(), + userInfo.getSiloStatus(), userInfo.getCostCenter(), userInfo.getFinancialLocCode(), + userInfo.getLoginId(), userInfo.getLoginPwd(), userInfo.getLastLoginDate(), userInfo.getActive(), + userInfo.getInternal(), userInfo.getSelectedProfileId(), userInfo.getTimeZoneId(), + userInfo.isOnline(), userInfo.getChatId(), userAppList.userApps, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "createEPUser failed", e); + throw new Exception(e.getMessage()); + } + + return user1; + } + + @SuppressWarnings("unchecked") + @Override + public CentralRole getRoleInfo(Long roleId, String uebkey) throws Exception { + final Map params = new HashMap<>(); + List roleList = new ArrayList<>(); + CentralRole cenRole = new CentralRole(); + List roleInfo = null; + List app = null; + try { + app = getApp(uebkey); + if (app.isEmpty() || app.size() == 0) { + throw new Exception("Application not found"); + } + String filter = null; + if (app.get(0).getId() == PortalConstants.PORTAL_APP_ID) { + filter = " where role_id = " + roleId + " and app_id is null "; + } else { + filter = " where app_role_id = " + roleId + " and app_id = " + app.get(0).getId(); + + } + roleInfo = dataAccessService.getList(EPRole.class, filter, null, null); + roleList = createCentralRoleObject(app, roleInfo, roleList, params); + if (roleList.isEmpty()) { + return cenRole; + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e); + throw new Exception(e.getMessage()); + + } + return roleList.get(0); + } + + @SuppressWarnings("unchecked") + private List createCentralRoleObject(List app, List roleInfo, + List roleList, Map params) { + for (EPRole role : roleInfo) { + params.put("roleId", role.getId()); + params.put("appId", app.get(0).getId()); + List cenRoleFuncList = dataAccessService.executeNamedQuery("getAppRoleFunctionList", + params, null); + SortedSet roleFunctionSet = new TreeSet(); + for (CentralRoleFunction roleFunc : cenRoleFuncList) { + CentralRoleFunction cenRoleFunc = new CentralRoleFunction(role.getId(), roleFunc.getCode(), + roleFunc.getName(), null, null); + roleFunctionSet.add(cenRoleFunc); + } + SortedSet childRoles = new TreeSet(); + CentralRole cenRole = null; + if (role.getAppRoleId() == null) { + cenRole = new CentralRole(role.getId(), role.getCreated(), role.getModified(), role.getCreatedId(), + role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), role.getPriority(), + roleFunctionSet, childRoles, null); + } else { + cenRole = new CentralRole(role.getAppRoleId(), role.getCreated(), role.getModified(), + role.getCreatedId(), role.getModifiedId(), role.getRowNum(), role.getName(), role.getActive(), + role.getPriority(), roleFunctionSet, childRoles, null); + } + roleList.add(cenRole); + } + return roleList; + } + + @SuppressWarnings("unchecked") + @Override + public CentralRoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception { + CentralRoleFunction roleFunc = null; + EPApp app = getApp(uebkey).get(0); + List getRoleFuncList = null; + final Map params = new HashMap<>(); + try { + params.put("functionCode", functionCode); + params.put("appId", String.valueOf(app.getId())); + getRoleFuncList = dataAccessService.executeNamedQuery("getRoleFunction", params, null); + if (getRoleFuncList.isEmpty() | getRoleFuncList.size() == 0) { + return roleFunc; + } + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e); + throw new Exception("getRoleFunction failed"); + } + return getRoleFuncList.get(0); + } + + @Override + public void saveCentralRoleFunction(CentralRoleFunction domainCentralRoleFunction, EPApp app) throws Exception { + try { + addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + dataAccessService.saveDomainObject(domainCentralRoleFunction, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction failed", e); + throw new Exception(e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + private void addRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + ObjectMapper mapper = new ObjectMapper(); + final Map params = new HashMap<>(); + params.put("functionCd", domainCentralRoleFunction.getCode()); + params.put("appId", String.valueOf(app.getId())); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + List appRoleFunc = dataAccessService.executeNamedQuery("getAppFunctionDetails", params, + null); + String roleFuncName = null; + if (!appRoleFunc.isEmpty()) { + roleFuncName = appRoleFunc.get(0).getCode(); + } else { + roleFuncName = domainCentralRoleFunction.getCode(); + } + String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + HttpEntity getSinglePermEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity getResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perms/" + + app.getNameSpace() + "." + checkType + "/" + roleFuncName + "/*", + HttpMethod.GET, getSinglePermEntity, String.class); + if (getResponse.getStatusCode().value() != 200) { + throw new Exception(getResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + String res = getResponse.getBody(); + if (res.equals("{}")) { + try{ + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); + } + } else { + try{ + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity entity = new HttpEntity<>(updateRole, headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm", + HttpMethod.PUT, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add fucntion in external central auth system", e); + + } + } + } + + @Override + @Transactional + public void deleteCentralRoleFunction(String code, String uebkey) { + try { + EPApp app = getApp(uebkey).get(0); + final Map params = new HashMap<>(); + params.put("functionCd", code); + params.put("appId", String.valueOf(app.getId())); + CentralRoleFunction domainCentralRoleFunction = (CentralRoleFunction) dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null).get(0); + deleteRoleFunctionInExternalSystem(domainCentralRoleFunction, app); + //Delete role function dependecy records + deleteAppRoleFunctions(code, app); + dataAccessService.deleteDomainObject(domainCentralRoleFunction, null); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction failed", e); + } + } + + private void deleteAppRoleFunctions(String code, EPApp app) { + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = "+app.getId()+" and function_cd = '"+ code +"'", null); + } + + private void deleteRoleFunctionInExternalSystem(CentralRoleFunction domainCentralRoleFunction, EPApp app) + throws Exception { + try{ + ObjectMapper mapper = new ObjectMapper(); + ExternalAccessPerms extPerms = new ExternalAccessPerms(); + String checkType = domainCentralRoleFunction.getCode().contains("menu") ? "menu" : "url"; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + extPerms.setAction("*"); + extPerms.setInstance(domainCentralRoleFunction.getCode()); + extPerms.setType(app.getNameSpace() + "." + checkType); + extPerms.setDescription(domainCentralRoleFunction.getName()); + String updateRole = mapper.writeValueAsString(extPerms); + HttpEntity entity = new HttpEntity<>(updateRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm?force=true", + HttpMethod.DELETE, entity, String.class); + } catch(Exception e){ + if(e.getMessage().equalsIgnoreCase("404 Not Found")){ + logger.debug(EELFLoggerDelegate.debugLogger, " It seems like function is already deleted in external central auth system but exists in local DB", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to delete functions in External System", e); + } + } + } + + @Override + public void saveRoleForApplication(Role saveRole, String uebkey) throws Exception { + try { + EPApp app = getApp(uebkey).get(0); + addRoleInEcompDB(saveRole, app); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e); + throw new Exception(e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + @Override + public void deleteRoleForApplication(String deleteRole, String uebkey) throws Exception { + Session localSession = null; + Transaction transaction = null; + boolean result = false; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + + List epRoleList = null; + ResponseEntity deleteResponse = null; + EPApp app = getApp(uebkey).get(0); + if(app.getId() == 1) + { + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id is null " + "and role_name = '" + deleteRole +"'", null, null); + } + else{ + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + deleteRole +"'", null, null); + } + // Delete app role functions before deleting role + deleteRoleFunction(app, epRoleList); + if(app.getId() == 1) + { + // Delete fn_user_ role + dataAccessService.deleteDomainObjects(EPUserApp.class, + " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); + } + // Delete Role in External System + String deleteRoleKey = "{\"name\":\"" + app.getNameSpace() + "." + + epRoleList.get(0).getName().replaceAll(" ", "_") + "\"}"; + deleteResponse = deleteRoleInExternalSystem(deleteRoleKey); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete role in external access system!"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + dataAccessService.deleteDomainObject(epRoleList.get(0), null); + result = true; + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication failed", e); + throw new Exception(e.getMessage()); + }finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in deleteRoleForApplication while closing database session for role: '" + deleteRole + "'."); + } + } + } + + private void deleteUserRoleInExternalSystem(EPRole role, EPApp app, String LoginId) throws Exception { + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity getResponse = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/" + + LoginId + + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"), + HttpMethod.GET, entity, String.class); + if (getResponse.getStatusCode().value() != 200) { + throw new Exception(getResponse.getBody()); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + String res = getResponse.getBody(); + if (!res.equals("{}")) { + HttpEntity userRoleentity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity deleteResponse = template + .exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + LoginId + + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN) + + "/" + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_"), + HttpMethod.DELETE, userRoleentity, String.class); + if (deleteResponse.getStatusCode().value() != 200) { + throw new Exception("Failed to delete user role"); + } + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system"); + } + } + + @SuppressWarnings("unchecked") + @Override + public List getActiveRoles(String uebkey) throws Exception { + List roleList = new ArrayList<>(); + try { + List app = getApp(uebkey); + final Map params = new HashMap<>(); + // check if portal + Long appId = null; + if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) { + appId = app.get(0).getId(); + } + List epRole = dataAccessService.getList(EPRole.class, + " where app_id = " + appId + " and active_yn = 'Y'", null, null); + roleList = createCentralRoleObject(app, epRole, roleList, params); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e); + throw new Exception(e.getMessage()); + } + return roleList; + + } + + @SuppressWarnings("unchecked") + @Override + public void deleteDependcyRoleRecord(Long roleId, String uebkey, String LoginId) throws Exception { + boolean result = false; + Session localSession = null; + Transaction transaction = null; + EPApp app = null; + try { + localSession = sessionFactory.openSession(); + transaction = localSession.beginTransaction(); + List epRoleList = null; + app = getApp(uebkey).get(0); + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and app_role_id = " + roleId, null, null); + if(epRoleList.isEmpty()){ + epRoleList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_id = " + roleId, null, null); + } + // Delete User Role in External System before deleting role + deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId); + // Delete user app roles + dataAccessService.deleteDomainObjects(EPUserApp.class, + " app_id = " + app.getId() + " and role_id = " + epRoleList.get(0).getId(), null); + + deleteRoleDependeciesRecord(localSession, epRoleList.get(0).getId()); + logger.debug(EELFLoggerDelegate.debugLogger, "about to commit the transaction"); + transaction.commit(); + logger.debug(EELFLoggerDelegate.debugLogger, "committed the transaction"); + result = true; + } catch (Exception e) { + EcompPortalUtils.rollbackTransaction(transaction, + "deleteDependcyRoleRecord rollback, exception = " + e); + logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); + }finally { + localSession.close(); + if (!result) { + throw new Exception( + "Exception occurred in syncAppRoles while closing database session for role: '" + app.getId() + "'."); + } + } + } + + @SuppressWarnings("unchecked") + @Transactional + public void syncRoleFunctionFromExternalAccessSystem(EPApp app){ + try{ + ResponseEntity response = null; + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "perms/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extPerms = jsonObj.getJSONArray("perm"); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).getString("type").equals(app.getNameSpace() + ".access")) { + extPerms.remove(i); + i--; + } + } + ExternalAccessPermsDetail permDetails = null; + List permsDetailList = new ArrayList<>(); + for (int i = 0; i < extPerms.length(); i++) { + if (extPerms.getJSONObject(i).has("roles")) { + ObjectMapper rolesListMapper = new ObjectMapper(); + JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles"); + List list = rolesListMapper.readValue(resRoles.toString(), + TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), + list, extPerms.getJSONObject(i).getString("description")); + permsDetailList.add(permDetails); + } else { + permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"), + extPerms.getJSONObject(i).getString("instance"), extPerms.getJSONObject(i).getString("action"), + extPerms.getJSONObject(i).getString("description")); + permsDetailList.add(permDetails); + } + } + + final Map params = new HashMap<>(); + final Map roleFuncMap = new HashMap<>(); + params.put("appId", app.getId()); + List appFunctions = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, + null); + if (appFunctions.size() > 0) { + for (CentralRoleFunction roleFunc : appFunctions) { + roleFuncMap.put(roleFunc.getCode(), roleFunc); + } + } + // delete all application role functions + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); + + // Add if new functions and app role functions were added in Externalsystem + for (ExternalAccessPermsDetail permsDetail : permsDetailList) { + if (!roleFuncMap.containsKey(permsDetail.getInstance())) { + CentralRoleFunction addFunction = new CentralRoleFunction(); + addFunction.setAppId(app.getId()); + addFunction.setCode(permsDetail.getInstance()); + addFunction.setName(permsDetail.getDescription()); + dataAccessService.saveDomainObject(addFunction, null); + } + List epRolesList = null; + List roles = permsDetail.getRoles(); + if (roles != null) { + for (String roleList : roles) { + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", + null, null); + } else { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1).replaceAll("_", " ") +"'", + null, null); + } + if(epRolesList.isEmpty()){ + if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id is null " + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1) + + "'", + null, null); + } else { + epRolesList = dataAccessService.getList(EPRole.class, + " where app_id = " + app.getId() + " and role_name = '" + + roleList.substring(app.getNameSpace().length() + 1)+"'", + null, null); + } + } + // save all application role functions + if (epRolesList.size() > 0 || !epRolesList.isEmpty()) { + EPAppRoleFunction addAppRoleFunc = new EPAppRoleFunction(); + addAppRoleFunc.setAppId(app.getId()); + addAppRoleFunc.setCode(permsDetail.getInstance()); + addAppRoleFunc.setRoleId(epRolesList.get(0).getId()); + dataAccessService.saveDomainObject(addAppRoleFunc, null); + } + } + } + } + logger.debug(EELFLoggerDelegate.debugLogger, "Finished syncRoleFunctionFromExternalAccessSystem"); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed syncRoleFunctionFromExternalAccessSystem", e); + + } + } + + @SuppressWarnings("unchecked") + public Integer bulkUploadFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List roleFuncList = null; + roleFuncList = dataAccessService.getList(RoleFunction.class, null); + CentralRoleFunction cenRoleFunc = null; + Integer functionsAdded = 0; + try { + for (RoleFunction roleFunc : roleFuncList) { + cenRoleFunc = new CentralRoleFunction(roleFunc.getCode(), roleFunc.getName()); + addRoleFunctionInExternalSystem(cenRoleFunc, app); + functionsAdded++; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e.getMessage(), e); + } + return functionsAdded; + } + + public Integer bulkUploadRoles(String uebkey) throws Exception { + List app = getApp(uebkey); + List roles = getAppRoles(app.get(0).getId(), null); + List cenRoleList = new ArrayList<>(); + final Map params = new HashMap<>(); + Integer rolesListAdded = 0; + try { + cenRoleList = createCentralRoleObject(app, roles, cenRoleList, params); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); + String roleList = mapper.writeValueAsString(cenRoleList); + List roleObjectList = mapper.readValue(roleList, + TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class)); + for (Role role : roleObjectList) { + addRoleInExternalSystem(role, app.get(0)); + rolesListAdded++; + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e); + throw new Exception(e.getMessage()); + } + return rolesListAdded; + } + + private void addRoleInExternalSystem(Role role, EPApp app) throws Exception { + String addRoleNew = createNewRoleInExternalSystem(role, app); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + try{ + HttpEntity entity = new HttpEntity<>(addRoleNew, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, entity, String.class); + } catch(Exception e){ + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "Role already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleInExternalSystem", e.getMessage()); + } + } + } + + @SuppressWarnings("unchecked") + public Integer bulkUploadRolesFunctions(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + List roles = getAppRoles(app.getId(), null); + final Map params = new HashMap<>(); + Integer roleFunctions = 0; + try { + for (EPRole role : roles) { + params.put("roleId", role.getId()); + List appRoleFunc = dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null); + if(!appRoleFunc.isEmpty()){ + for(BulkUploadRoleFunction addRoleFunc : appRoleFunc){ + addRoleFunctionsInExternalSystem(addRoleFunc, role, app); + roleFunctions++; + } + } + } + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions failed", e); + } + return roleFunctions; + } + + private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, EPRole role, EPApp app){ + String checkType = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url"; + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + ObjectMapper mapper = new ObjectMapper(); + try{ + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, addRoleFunc.getFunctionCd(), "*", addRoleFunc.getFunctionName()); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", HttpMethod.POST, entity, String.class); + } catch(Exception e){ + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "RoleFunction already exits but does not break functionality",e); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", e.getMessage()); + } + } + } + + @Override + public void bulkUploadPartnerFunctions(String uebkey, List roleFunctionsList) throws Exception { + EPApp app = getApp(uebkey).get(0); + CentralRoleFunction cenRoleFunc = null; + for (RoleFunction roleFunction : roleFunctionsList) { + cenRoleFunc = new CentralRoleFunction(roleFunction.getCode(), roleFunction.getName()); + addRoleFunctionInExternalSystem(cenRoleFunc, app); + } + } + + @Override + public void bulkUploadPartnerRoles(String uebkey, List roleList) throws Exception { + EPApp app = getApp(uebkey).get(0); + for (Role role : roleList) { + addRoleInExternalSystem(role, app); + } + } + + @SuppressWarnings("unchecked") + @Override + public void bulkUploadPartnerRoleFunctions(String uebkey, List roleList) throws Exception { + EPApp app = getApp(uebkey).get(0); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + for (Role role : roleList) { + try { + Set roleFunctionList = role.getRoleFunctions(); + List roleFunctionListNew = new ArrayList<>(); + ObjectMapper roleFunctionsMapper = new ObjectMapper(); + Iterator itetaror = roleFunctionList.iterator(); + while (itetaror.hasNext()) { + Object nextValue = itetaror.next(); + RoleFunction roleFunction = roleFunctionsMapper.convertValue(nextValue, RoleFunction.class); + roleFunctionListNew.add(roleFunction); + } + List listWithoutDuplicates = roleFunctionListNew.stream().distinct() + .collect(Collectors.toList()); + for (RoleFunction roleFunction : listWithoutDuplicates) { + String checkType = roleFunction.getCode().contains("menu") ? "menu" : "url"; + ExternalAccessRolePerms extRolePerms = null; + ExternalAccessPerms extPerms = null; + ObjectMapper mapper = new ObjectMapper(); + extPerms = new ExternalAccessPerms(app.getNameSpace() + "." + checkType, roleFunction.getCode(), + "*"); + extRolePerms = new ExternalAccessRolePerms(extPerms, + app.getNameSpace() + "." + role.getName().replaceAll(" ", "_")); + String updateRolePerms = mapper.writeValueAsString(extRolePerms); + HttpEntity entity = new HttpEntity<>(updateRolePerms, headers); + template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "role/perm", HttpMethod.PUT, entity, String.class); + } + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, + "RoleFunction already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addRoleFunctionsInExternalSystem", + e.getMessage()); + } + } + + } + } + + @SuppressWarnings("unchecked") + @Transactional + public void SyncApplicationRolesWithEcompDB(EPApp app){ + try{ + ResponseEntity response = null; + List finalRoleList = new ArrayList<>(); + ExternalRoleDescription ApplicationRole = new ExternalRoleDescription(); + ExternalAccessPerms externalAccessPerms = null; + List functionCodelist = new ArrayList<>(); + List externalRoleDetailsList = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/ns/" + app.getNameSpace(), HttpMethod.GET, entity, String.class); + String res = response.getBody(); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to External Access system and the result is :", res); + JSONObject jsonObj = new JSONObject(res); + JSONArray extRole = jsonObj.getJSONArray("role"); + for (int i = 0; i < extRole.length(); i++) { + if (extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".admin") + || extRole.getJSONObject(i).getString("name").equals(app.getNameSpace() + ".owner") + ) { + extRole.remove(i); + i--; + } + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && extRole.getJSONObject(i).get("name").equals(app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"))){ + extRole.remove(i); + i--; + } + } + List applicationRoleFunctionList = new ArrayList<>(); + for (int i = 0; i < extRole.length(); i++) { + ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails(); + EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction(); + JSONObject Role = (JSONObject) extRole.get(i); + if(!extRole.getJSONObject(i).has("description")) + { + ApplicationRole.setActive("true"); + ApplicationRole.setAppId("null"); + ApplicationRole.setPriority("null"); + ApplicationRole.setAppRoleId("null"); + String roleName =extRole.getJSONObject(i).getString("name"); + ApplicationRole.setName(roleName.substring(app.getNameSpace().length()+1)); + } + else { + String desc = extRole.getJSONObject(i).getString("description"); + ApplicationRole = mapper.readValue(desc, ExternalRoleDescription.class); + } + + + SortedSet externalAccessPermsOfRole = new TreeSet<>(); + if (extRole.getJSONObject(i).has("perms")) { + JSONArray extPerm = (JSONArray) Role.get("perms"); + for (int j = 0; j < extPerm.length(); j++) { + JSONObject perms = extPerm.getJSONObject(j); + externalAccessPerms = new ExternalAccessPerms(perms.getString("type"), perms.getString("instance"), + perms.getString("action")); + ePAppRoleFunction.setCode(externalAccessPerms.getInstance()); + functionCodelist.add(ePAppRoleFunction.getCode()); + externalAccessPermsOfRole.add(externalAccessPerms); + } + } + + if (ApplicationRole.getActive().equals("null")) { + externalRoleDetail.setActive(false); + } else { + externalRoleDetail.setActive(Boolean.parseBoolean(ApplicationRole.getActive().toString())); + } + externalRoleDetail.setName(ApplicationRole.getName()); + + if (ApplicationRole.getAppId().equals("null") && app.getId() == 1) { + externalRoleDetail.setAppId(null); + } else if(ApplicationRole.getAppId().equals("null")){ + externalRoleDetail.setAppId(app.getId()); + }else { + externalRoleDetail.setAppId(Long.parseLong(ApplicationRole.getAppId().toString())); + } + + if (ApplicationRole.getPriority().equals("null")) { + externalRoleDetail.setPriority(null); + } else { + externalRoleDetail.setPriority(Integer.parseInt(ApplicationRole.getPriority().toString())); + } + + if (ApplicationRole.getAppRoleId().equals("null") && app.getId() == 1) { + externalRoleDetail.setAppRoleId(null); + } + + if (!externalAccessPermsOfRole.isEmpty() || externalAccessPermsOfRole.size() > 0) { + for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) { + EPAppRoleFunction apRoleFunction = new EPAppRoleFunction(); + apRoleFunction.setAppId(app.getId()); + apRoleFunction.setRoleId(Long.parseLong(ApplicationRole.getId())); + apRoleFunction.setCode(externalpermission.getInstance()); + applicationRoleFunctionList.add(apRoleFunction); + } + } + externalRoleDetailsList.add(externalRoleDetail); + } + + for (ExternalRoleDetails externalRole : externalRoleDetailsList) { + EPRole ecompRole = new EPRole(); + ecompRole = convertExternalRoleDetailstoEpRole(externalRole); + finalRoleList.add(ecompRole); + } + + List applicationRolesList = new ArrayList<>(); + applicationRolesList = getAppRoles(app.getId(), null); + List applicationRoleIdList = new ArrayList<>(); + for (EPRole applicationRole : applicationRolesList) { + applicationRoleIdList.add(applicationRole.getName()); + } + + List roleListToBeAddInEcompDB = new ArrayList<>(); + for (EPRole aafRole : finalRoleList) { + if (!applicationRoleIdList.contains(aafRole.getName())) { + roleListToBeAddInEcompDB.add(aafRole); + } + } + + // Check if roles exits in external Access system and make it inactive + final Map checkRolesInactive = new HashMap<>(); + for(EPRole extrole : finalRoleList){ + checkRolesInactive.put(extrole.getName(), extrole); + } + for (EPRole role : applicationRolesList) { + final Map extRoleParams = new HashMap<>(); + List roleList = new ArrayList<>(); + extRoleParams.put("appRoleName", role.getName()); + if (!checkRolesInactive.containsKey(role.getName())) { + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", extRoleParams, null); + } else { + extRoleParams.put("appId", app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", extRoleParams, null); + } + EPRole updateRoleInactive = roleList.get(0); + updateRoleInactive.setActive(false); + dataAccessService.saveDomainObject(updateRoleInactive, null); + } + } + + for (EPRole roleItem : finalRoleList) { + final Map roleParams = new HashMap<>(); + List currentList = new ArrayList<>(); + roleParams.put("appRoleName", roleItem.getName()); + if (app.getId() == 1) { + currentList = dataAccessService.executeNamedQuery("getPortalAppRoles", roleParams, null); + } else { + roleParams.put("appId", app.getId().toString()); + currentList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", roleParams, null); + } + + if (!currentList.isEmpty()) { + Boolean aafRoleActive; + Boolean localRoleActive; + boolean result; + aafRoleActive = Boolean.valueOf(roleItem.getActive()); + localRoleActive = Boolean.valueOf(currentList.get(0).getActive()); + result = aafRoleActive.equals(localRoleActive); + EPRole updateRole = currentList.get(0); + + if (!result) { + updateRole.setActive(roleItem.getActive()); + dataAccessService.saveDomainObject(updateRole, null); + } + if (roleItem.getPriority() != null + && !currentList.get(0).getPriority().equals(roleItem.getPriority())) { + updateRole.setPriority(roleItem.getPriority()); + dataAccessService.saveDomainObject(updateRole, null); + } + } + } + + EPRole roleToBeAddedInEcompDB = new EPRole(); + for (int i = 0; i < roleListToBeAddInEcompDB.size(); i++) { + roleToBeAddedInEcompDB = roleListToBeAddInEcompDB.get(i); + if(app.getId() == 1) + { + roleToBeAddedInEcompDB.setAppRoleId(null); + } + dataAccessService.saveDomainObject(roleToBeAddedInEcompDB, null); + List getRoleCreatedInSync = null; + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + getRoleCreatedInSync = dataAccessService.getList(EPRole.class, + " where role_name = '" + roleToBeAddedInEcompDB.getName() +"'", null, null); + EPRole epUpdateRole = getRoleCreatedInSync.get(0); + epUpdateRole.setAppRoleId(epUpdateRole.getId()); + dataAccessService.saveDomainObject(epUpdateRole, null); + } + List roleList = new ArrayList<>(); + final Map params = new HashMap<>(); + + params.put("appRoleName", roleToBeAddedInEcompDB.getName()); + if (app.getId() == 1) { + roleList = dataAccessService.executeNamedQuery("getPortalAppRoles", params, null); + } else { + params.put("appId", app.getId().toString()); + roleList = dataAccessService.executeNamedQuery("getRoletoUpdateAAF", params, null); + } + EPRole role = roleList.get(0); + Role aaFrole = new Role(); + aaFrole.setId(role.getId()); + aaFrole.setActive(role.getActive()); + aaFrole.setPriority(role.getPriority()); + aaFrole.setName(role.getName()); + updateRoleInExternalSystem(aaFrole, app); + } + dataAccessService.deleteDomainObjects(EPAppRoleFunction.class, " app_id = " + app.getId(), null); + for (EPAppRoleFunction rolefun : applicationRoleFunctionList) { + dataAccessService.saveDomainObject(rolefun, null); + } + + logger.debug(EELFLoggerDelegate.debugLogger, "Finished SyncApplicationRolesWithEcompDB"); + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to SyncApplicationRolesWithEcompDB", e); + } + } + + public EPRole convertExternalRoleDetailstoEpRole(ExternalRoleDetails externalRoleDetails) { + EPRole role = new EPRole(); + role.setActive(externalRoleDetails.isActive()); + role.setAppId(externalRoleDetails.getAppId()); + role.setAppRoleId(externalRoleDetails.getAppRoleId()); + role.setName(externalRoleDetails.getName()); + role.setPriority(externalRoleDetails.getPriority()); + return role; + } + + @SuppressWarnings("unchecked") + @Override + public Integer bulkUploadUserRoles(String uebkey) throws Exception { + EPApp app = getApp(uebkey).get(0); + final Map params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + List userRolesList = null; + Integer userRolesAdded = 0; + if (app.getCentralAuth()) { + userRolesList = dataAccessService.executeNamedQuery("getBulkUserRoles", params, null); + for (BulkUploadUserRoles userRolesUpload : userRolesList) { + addUserRoleInExternalSystem(userRolesUpload); + userRolesAdded++; + } + } + return userRolesAdded; + } + + private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload){ + try{ + String name = ""; + ObjectMapper mapper = new ObjectMapper(); + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = userRolesUpload.getOrgUserId() + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ExternalAccessUser extUser = new ExternalAccessUser(name, + userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName().replaceAll(" ", "_")); + String userRole = mapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity entity = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + logger.error(EELFLoggerDelegate.errorLogger, "UserRole already exits but does not break functionality"); + } else { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to addUserRoleInExternalSystem", e.getMessage()); + } + } + } + + @Override + public void deleteRoleDependeciesRecord(Session localSession, Long roleId) throws Exception { + try { + // Delete from fn_role_function + String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + Query query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from ep_app_role_function + sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from ep_role_notification + sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_role_composite + sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + // Delete from fn_user_pseudo_role + sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + //Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + //Delete form EP_WIDGET_CATALOG_ROLE + sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + //Delete form fn_menu_functional_roles + sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId; + logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); + query = localSession.createSQLQuery(sql); + query.executeUpdate(); + + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord failed " , e); + throw new Exception("delete Failed"+ e.getMessage()); + } + + } + + + @SuppressWarnings("unchecked") + @Override + public List getMenuFunctionsList(String uebkey) throws Exception { + List appMenuFunctionsList = null; + try{ + EPApp app = getApp(uebkey).get(0); + final Map appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + appMenuFunctionsList = dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed getMenuFunctionsList", e); + return appMenuFunctionsList; + } + return appMenuFunctionsList; + } +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java index 0963f048..5979fe82 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/PortalAdminServiceImpl.java @@ -29,25 +29,34 @@ import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; +import org.openecomp.portalapp.portal.domain.EPApp; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; import org.openecomp.portalapp.portal.transport.FieldsValidator; import org.openecomp.portalapp.portal.transport.PortalAdmin; import org.openecomp.portalapp.portal.transport.PortalAdminUserRole; import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; +import org.openecomp.portalapp.portal.utils.PortalConstants; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.databind.ObjectMapper; @Service("portalAdminService") @org.springframework.context.annotation.Configuration @EnableAspectJAutoProxy @EPMetricsLog -public class PortalAdminServiceImpl implements PortalAdminService { +public class PortalAdminServiceImpl implements PortalAdminService { private String SYS_ADMIN_ROLE_ID = "1"; private String ECOMP_APP_ID = "1"; @@ -60,7 +69,11 @@ public class PortalAdminServiceImpl implements PortalAdminService { private DataAccessService dataAccessService; @Autowired SearchService searchService; - + @Autowired + private EPAppService epAppService; + + RestTemplate template = new RestTemplate(); + @PostConstruct private void init() { SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID); @@ -130,7 +143,8 @@ public class PortalAdminServiceImpl implements PortalAdminService { } transaction.commit(); - result = true; + // Add role in the external central auth system + result = addPortalAdminInExternalCentralAuth(user.getOrgUserId(), PortalConstants.PORTAL_ADMIN_ROLE); } catch (Exception e) { EcompPortalUtils.rollbackTransaction(transaction, "createPortalAdmin rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); @@ -147,6 +161,42 @@ public class PortalAdminServiceImpl implements PortalAdminService { } return fieldsValidator; } + + private boolean addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole){ + boolean result = false; + try{ + String name = ""; + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = loginId + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID); + String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_"); + ObjectMapper addUserRoleMapper = new ObjectMapper(); + ExternalAccessUser extUser = new ExternalAccessUser(name, extRole); + String userRole = addUserRoleMapper.writeValueAsString(extUser); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + + HttpEntity addUserRole = new HttpEntity<>(userRole, headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole", + HttpMethod.POST, addUserRole, String.class); + result = true; + } catch (Exception e) { + // This happens only if role already exists in external central access system but not in local DB thats where we logging here + if (e.getMessage().equalsIgnoreCase("409 Conflict")) { + result = true; + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + result = false; + } + } + return result; + } public FieldsValidator deletePortalAdmin(Long userId) { FieldsValidator fieldsValidator = new FieldsValidator(); @@ -161,7 +211,7 @@ public class PortalAdminServiceImpl implements PortalAdminService { dataAccessService.deleteDomainObjects(PortalAdminUserRole.class, "user_id='" + userId + "' AND role_id='" + SYS_ADMIN_ROLE_ID + "'", null); transaction.commit(); - result = true; + result = deletePortalAdminInExternalCentralAuth(userId, PortalConstants.PORTAL_ADMIN_ROLE); } catch (Exception e) { EcompPortalUtils.rollbackTransaction(transaction, "deletePortalAdmin rollback, exception = " + e); logger.error(EELFLoggerDelegate.errorLogger, EcompPortalUtils.getStackTrace(e)); @@ -177,6 +227,40 @@ public class PortalAdminServiceImpl implements PortalAdminService { return fieldsValidator; } + + @SuppressWarnings("unchecked") + private boolean deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole){ + boolean result = false; + try{ + String name = ""; + List localUserList = dataAccessService.getList(EPUser.class, " where user_id = " + userId, + null, null); + if (EPCommonSystemProperties.containsProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = localUserList.get(0).getOrgUserId() + SystemProperties + .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + EPApp app = epAppService.getApp(PortalConstants.PORTAL_APP_ID); + String extRole = app.getNameSpace()+"."+portalAdminRole.replaceAll(" ", "_"); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); + HttpEntity addUserRole = new HttpEntity<>(headers); + template.exchange( + SystemProperties.getProperty( + EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/"+name+"/"+extRole, + HttpMethod.DELETE, addUserRole, String.class); + result = true; + } catch (Exception e) { + if (e.getMessage().equalsIgnoreCase("404 Not Found")) { + logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found", e.getMessage()); + } else{ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e); + result = false; + } + } + return result; + } + private void logQuery(String sql) { logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java index 1b1b6069..b222d189 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/SharedContextServiceImpl.java @@ -108,7 +108,7 @@ public class SharedContextServiceImpl implements SharedContextService { * (non-Javadoc) * * @see org.openecomp.portalsdk.core.service.SharedContextService# - * saveSharedContext(com. att.fusion.core.domain.SharedContext) + * saveSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) */ @Override public void saveSharedContext(SharedContext context) { @@ -119,7 +119,7 @@ public class SharedContextServiceImpl implements SharedContextService { * (non-Javadoc) * * @see org.openecomp.portalsdk.core.service.SharedContextService# - * deleteSharedContext(com. att.fusion.core.domain.SharedContext) + * deleteSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) */ @Override public void deleteSharedContext(SharedContext context) { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java index 58809210..1315c5e9 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -31,16 +31,18 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; +import java.util.stream.Collectors; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.cxf.transport.http.HTTPException; -import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; +import org.json.JSONArray; +import org.json.JSONObject; import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; import org.openecomp.portalapp.externalsystemapproval.model.ExternalSystemUser; import org.openecomp.portalapp.portal.domain.EPApp; @@ -48,15 +50,20 @@ import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.domain.EPUserApp; import org.openecomp.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.openecomp.portalapp.portal.domain.EPUserAppRoles; import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequest; import org.openecomp.portalapp.portal.domain.EPUserAppRolesRequestDetail; -import org.openecomp.portalapp.portal.domain.EpUserAppRoles; import org.openecomp.portalapp.portal.domain.ExternalSystemAccess; import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog; import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalapp.portal.transport.AppWithRolesForUser; +import org.openecomp.portalapp.portal.transport.EPUserAppCurrentRoles; +import org.openecomp.portalapp.portal.transport.EcompUserAppRoles; +import org.openecomp.portalapp.portal.transport.ExternalAccessUser; +import org.openecomp.portalapp.portal.transport.ExternalAccessUserRoleDetail; import org.openecomp.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.openecomp.portalapp.portal.transport.ExternalRoleDescription; import org.openecomp.portalapp.portal.transport.FieldsValidator; import org.openecomp.portalapp.portal.transport.FunctionalMenuItem; import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; @@ -74,6 +81,11 @@ import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.service.RoleService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -87,7 +99,7 @@ public class UserRolesCommonServiceImpl { private static final Object syncRests = new Object(); @Autowired - private DataAccessService dataAccessService; + private DataAccessService dataAccessService; @Autowired private SessionFactory sessionFactory; @Autowired @@ -99,7 +111,12 @@ public class UserRolesCommonServiceImpl { @Autowired private EPRoleService epRoleService; @Autowired - private RoleService roleService; + private RoleService roleService; + + @Autowired + private ExternalAccessRolesService externalAccessRolesService; + + RestTemplate template = new RestTemplate(); /** * @@ -255,12 +272,10 @@ public class UserRolesCommonServiceImpl { EPApp app = (EPApp) localSession.get(EPApp.class, appId); HashMap rolesMap = new HashMap(); - if (appId == PortalConstants.PORTAL_APP_ID) { // local app - String appIdValue = null; + if (appId.equals(PortalConstants.PORTAL_APP_ID)) { // local app + String appIdValue = ""; if(!extRequestValue){ - appIdValue = "and id != " + PortalConstants.PORTAL_APP_ID; - }else{ - appIdValue = ""; + appIdValue = "and id != " + PortalConstants.SYS_ADMIN_ROLE_ID; } @SuppressWarnings("unchecked") List roles = localSession @@ -274,19 +289,27 @@ public class UserRolesCommonServiceImpl { List roles = localSession .createQuery("from " + EPRole.class.getName() + " where appId=" + appId).list(); for (EPRole role : roles) { - rolesMap.put(role.getAppRoleId(), role); + if (!extRequestValue && app.getCentralAuth()) { + rolesMap.put(role.getId(), role); + } else { + rolesMap.put(role.getAppRoleId(), role); + } } } + EPRole role = null; for (EcompRole userRole : newRolesToAdd) { EPUserApp userApp = new EPUserApp(); if (("PUT".equals(reqType) || "POST".equals(reqType)) && userRole.getName().equals(PortalConstants.ADMIN_ROLE)) { role = (EPRole) localSession.get(EPRole.class, new Long(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); userApp.setRole(role); - } else if (userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID) && !extRequestValue){ + } else if ((userRole.getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !extRequestValue){ continue; - } else { - userApp.setRole(rolesMap.get(userRole.getId())); + }else if((userRole.getId().equals(PortalConstants.SYS_ADMIN_ROLE_ID)) && app.getId().equals(PortalConstants.PORTAL_APP_ID) && !extRequestValue){ + continue; + } + else { + userApp.setRole(rolesMap.get(userRole.getId())); } userApp.setUserId(client.getId()); @@ -305,10 +328,10 @@ public class UserRolesCommonServiceImpl { * code expects the app_id to be null as there is no * concept of App_id in SDK */ + localSession.flush(); SQLQuery sqlQuery = localSession .createSQLQuery("update fn_role set app_id = null where app_id = 1 "); sqlQuery.executeUpdate(); - } } @@ -523,32 +546,7 @@ public class UserRolesCommonServiceImpl { } } } - - // Delete from fn_role_function - String sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - Query query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from ep_role_notification - sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from fn_role_composite - sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" - + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - - // Delete from fn_user_pseudo_role - sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId; - logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql); - query = localSession.createSQLQuery(sql); - query.executeUpdate(); - + externalAccessRolesService.deleteRoleDependeciesRecord(localSession, roleId); logger.debug(EELFLoggerDelegate.debugLogger, "about to delete the role: " + role.toString()); localSession.delete(role); logger.debug(EELFLoggerDelegate.debugLogger, "deleted the role"); @@ -571,6 +569,10 @@ public class UserRolesCommonServiceImpl { } } + + + + /** * Called when updating the list of roles for the user * @@ -691,8 +693,8 @@ public class UserRolesCommonServiceImpl { } if (rolesInAppForUser != null) { - EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.size()]; - for (int i = 0; i < rolesInAppForUser.roles.size(); i++) { + EcompRole[] userAppRoles = new EcompRole[rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size()]; + for (int i = 0; i < rolesInAppForUser.roles.stream().distinct().collect(Collectors.toList()).size(); i++) { RoleInAppForUser roleInAppForUser = rolesInAppForUser.roles.get(i); EcompRole role = new EcompRole(); role.setId(roleInAppForUser.roleId); @@ -759,6 +761,67 @@ public class UserRolesCommonServiceImpl { return rolesList; } + /** + * It adds new user for remote application + * + * @param roleInAppForUserList + * @param remoteAppUser + * @param userId + * @param app + * @param mapper + * @param searchService + * @param applicationsRestClientService + * @throws Exception + */ + private void addRemoteUser(List roleInAppForUserList, String userId, EPApp app, ObjectMapper mapper, SearchService searchService, ApplicationsRestClientService applicationsRestClientService) throws Exception{ + EPUser addRemoteUser = null; + if (remoteUserShouldBeCreated(roleInAppForUserList)) { + + createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app)); + // If we succeed, we know that the new user was + // persisted on remote app. + addRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + if (addRemoteUser == null) { + logger.error(EELFLoggerDelegate.errorLogger, + "Failed to persist new user: " + userId + " in remote app. appId = " + app.getId()); + // return null; + } + } + } + + /** + * It checks whether the remote user exists or not + * if exits returns user object else null + * + * @param userId + * @param app + * @param applicationsRestClientService + * @return + * @throws HTTPException + */ + private EPUser checkIfRemoteUserExits(String userId, EPApp app, ApplicationsRestClientService applicationsRestClientService) throws HTTPException{ + EPUser checkRemoteUser = null; + try { + checkRemoteUser = getUserFromApp(userId, app, applicationsRestClientService); + } catch (HTTPException e) { + // Some apps are returning 400 if user is not found. + if (e.getResponseCode() == 400) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", + e); + } else if(e.getResponseCode() == 404) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 404; continuing", + e); + } else { + // Other response code, let it come thru. + throw e; + } + } + return checkRemoteUser; + } + + /* * (non-Javadoc) * @@ -783,58 +846,59 @@ public class UserRolesCommonServiceImpl { EPApp app = appsService.getApp(appId); applyChangesToUserAppRolesForMyLoginsRequest(user, appId); - // if local app - if (appId == PortalConstants.PORTAL_APP_ID) { - // EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + // if centralized app + if (app.getCentralAuth()) { + // We should add If user does not exist in remote application + if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + EPUser remoteAppUser = null; + remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService); + + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, + applicationsRestClientService); + } + } + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, applicationsRestClientService, appId, userId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, userRolesInLocalApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); - - } else {// remote app + List roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + } + // In case if portal is not centralized then follow existing approach + else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInLocalApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, "Portal"); + } else{// remote app EPUser remoteAppUser = null; - try { - remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", - e); - } else { - // Other response code, let it come thru. - throw e; - } - } - if (remoteAppUser == null) { - if (remoteUserShouldBeCreated(roleInAppForUserList)) { - - createNewUserOnRemoteApp(userId, app, applicationsRestClientService, searchService, mapper, isAppUpgradeVersion(app)); - // If we succeed, we know that the new user was - // persisted on remote app. - remoteAppUser = getUserFromApp(userId, app, applicationsRestClientService); - if (remoteAppUser == null) { - logger.error(EELFLoggerDelegate.errorLogger, - "Failed to persist new user: " + userId + " in remote app. appId = " + appId); - // return null; - } + if(!app.getCentralAuth() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + + remoteAppUser = checkIfRemoteUserExits(userId, app, applicationsRestClientService); + + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId, app, mapper, searchService, applicationsRestClientService); } - } - if (remoteAppUser != null) { - Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, - applicationsRestClientService, appId, userId); - RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, - userRolesInRemoteApp); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); + if (remoteAppUser != null) { + Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper, + applicationsRestClientService, appId, userId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(userId, appId, + userRolesInRemoteApp); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, epRequestValue, null); - // If no roles remain, request app to set user inactive. - if (userRolesInRemoteApp.size() == 0) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, - userId); - remoteAppUser.setActive(false); - postUserToRemoteApp(userId, user, app, applicationsRestClientService); + // If no roles remain, request app to set user inactive. + if (userRolesInRemoteApp.size() == 0) { + logger.debug(EELFLoggerDelegate.debugLogger, + "setAppWithUserRoleStateForUser: no roles in app {}, set user {} to inactive", app, + userId); + remoteAppUser.setActive(false); + postUserToRemoteApp(userId, user, app, applicationsRestClientService); + } } } } @@ -849,7 +913,147 @@ public class UserRolesCommonServiceImpl { } return result; } - + + @SuppressWarnings("unchecked") + private void updateUserRolesInExternalSystem(EPApp app, String orgUserId, List roleInAppUser) + { + try{ + //check if user exists + final Map userParams = new HashMap<>(); + userParams.put("orgUserIdValue", orgUserId); + List userInfo = checkIfUserExists(userParams); + if (userInfo.size() == 0 || userInfo.isEmpty()) { + createLocalUserIfNecessary(orgUserId); + } + final Map loginIdParams = new HashMap<>(); + loginIdParams.put("orgUserIdValue", orgUserId); + EPUser user = (EPUser) dataAccessService.executeNamedQuery("epUserAppId", loginIdParams, null).get(0); + String name = ""; + if (EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) { + name = orgUserId + + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN); + } + ObjectMapper mapper = new ObjectMapper(); + HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth() ; + HttpEntity getUserRolesEntity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles"); + ResponseEntity getResponse = template + .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class); + if(getResponse.getStatusCode().value() == 200){ + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and received user roles: ", getResponse.getBody()); + + } + List userRoleDetailList = new ArrayList<>(); + String res = getResponse.getBody(); + JSONObject jsonObj = null; + JSONArray extRoles = null; + if (!res.equals("{}")) { + jsonObj = new JSONObject(res); + extRoles = jsonObj.getJSONArray("role"); + } + ExternalAccessUserRoleDetail userRoleDetail = null; + if (extRoles != null) { + for (int i = 0; i < extRoles.length(); i++) { + if (extRoles.getJSONObject(i).getString("name").startsWith(app.getNameSpace() + ".") && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".admin") + && !extRoles.getJSONObject(i).getString("name").equals(app.getNameSpace()+".owner")) { + ObjectMapper descMapper = new ObjectMapper(); + if(extRoles.getJSONObject(i).has("description")){ + ExternalRoleDescription desc = descMapper.readValue( + extRoles.getJSONObject(i).getString("description"), ExternalRoleDescription.class); + userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), + desc); + userRoleDetailList.add(userRoleDetail); + }else{ + userRoleDetail = new ExternalAccessUserRoleDetail(extRoles.getJSONObject(i).getString("name"), + null); + userRoleDetailList.add(userRoleDetail); + } + + } + } + } + for (ExternalAccessUserRoleDetail userRole : userRoleDetailList) { + HttpEntity entity = new HttpEntity<>(headers); + template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + + "userRole/" + name + "/" + userRole.getName(), HttpMethod.DELETE, entity, String.class); + } + final Map roleInAppUserMap = new HashMap<>(); + for(RoleInAppForUser roleInAppUserNew: roleInAppUser){ + roleInAppUserMap.put(roleInAppUserNew.getRoleName(), roleInAppUserNew); + } + final Map params = new HashMap<>(); + params.put("appId", app.getId()); + params.put("userId", user.getId()); + List userAppList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", params, null); + // Check if incoming request has sys admin or account admin, if exists add in external system + if (!roleInAppUser.isEmpty()) { + for (EcompUserAppRoles userApp : userAppList) { + if ((userApp.getRoleId().equals(PortalConstants.SYS_ADMIN_ROLE_ID) + || userApp.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) && !roleInAppUserMap.containsKey(userApp.getRoleName())) { + RoleInAppForUser addSpecialRole = new RoleInAppForUser(); + addSpecialRole.setIsApplied(true); + addSpecialRole.setRoleId(userApp.getRoleId()); + addSpecialRole.setRoleName(userApp.getRoleName()); + roleInAppUser.add(addSpecialRole); + } + } + } + List roleInAppUserNonDupls = roleInAppUser.stream().distinct().collect(Collectors.toList()); + for (RoleInAppForUser addRole : roleInAppUserNonDupls) { + ExternalAccessUser extUser = null; + if ((addRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)) + && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) { + try{ + String extRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ","_"); + HttpEntity entity = new HttpEntity<>(headers); + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to External Access system"); + ResponseEntity getRoleResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"+extRole, + HttpMethod.GET, entity, String.class); + String extAdminRole = app.getNameSpace()+"."+PortalConstants.ADMIN_ROLE.replaceAll(" ", "_"); + if(getRoleResponse.getBody().equals("{}")){ + String addDesc = "{\"name\":\"" +extAdminRole+ "\"}"; + HttpEntity roleEntity = new HttpEntity<>(addDesc,headers); + template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role", + HttpMethod.POST, roleEntity, String.class); + } + extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + PortalConstants.ADMIN_ROLE.replaceAll(" ", "_")); + } catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add admin role for application {} ",app.getId(),e); + continue; + } + } else { + extUser = new ExternalAccessUser(name, + app.getNameSpace() + "." + addRole.getRoleName().replaceAll(" ", "_")); + } + // Assign user role for an application in external access system + String userRole = mapper.writeValueAsString(extUser); + HttpEntity entity = new HttpEntity<>(userRole, headers); + if (addRole.getIsApplied()) { + logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system and adding user role", + addRole.getRoleName()); + ResponseEntity addResponse = template.exchange( + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole", + HttpMethod.POST, entity, String.class); + logger.debug(EELFLoggerDelegate.debugLogger, "Connected to external system and added user role", + getResponse.getBody(), addRole.getRoleName()); + if (addResponse.getStatusCode().value() != 201) { + logger.debug(EELFLoggerDelegate.debugLogger, + "Connected to external system unable to save user role", getResponse.getBody(), + addRole.getRoleName()); + throw new Exception("Failed to add user role for application"); + } + } + } + }catch(Exception e){ + logger.error(EELFLoggerDelegate.errorLogger, "Failed to add user role for application {}", app.getId(),e); + } + + } + /** * * @param userId @@ -1066,60 +1270,86 @@ public class UserRolesCommonServiceImpl { .executeNamedQuery("userAppRolesRequestList", params, null); epRequestIdSize = epRequestId.size(); } - if(!app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + if(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getCentralAuth()){ EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles"); syncAppRoles(sessionFactory, app.getId(), appRoles); } List roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(), app.getId(), app.getMlAppName()); - // if local app - if (app.getId() == PortalConstants.PORTAL_APP_ID) { - // EPUser localUser = getUserFromApp(orgUserId, app, applicationsRestClientService); + List userRoleList = null; + if(userId != null){ + final Map appParams = new HashMap<>(); + appParams.put("userId", userId.getId()); + appParams.put("appId", app.getId()); + userRoleList = dataAccessService.executeNamedQuery("getUserAppExistingRoles", appParams, null); + } + boolean checkIfAdminRoleExists = false; + if (reqType.equals("DELETE")) { + checkIfAdminRoleExists = userRoleList.stream() + .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); + } else { + checkIfAdminRoleExists = roleInAppForUserList.stream() + .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)); + } + // if Centralized app + if (app.getCentralAuth()) { + // We should add If user does not exist in remote application + try { + if (!(!app.getId().equals(PortalConstants.PORTAL_APP_ID) && checkIfAdminRoleExists + && (roleInAppForUserList.size() == 1 || reqType.equals("DELETE")))) { + EPUser remoteAppUser = null; + remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, + applicationsRestClientService); + if (remoteAppUser == null) { + addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, + applicationsRestClientService); + reqMessage = "Saved Successfully"; + } + } + } catch (Exception e) { + reqMessage = e.getMessage(); + logger.error(EELFLoggerDelegate.errorLogger, "Failed to added remote user", e); + throw new Exception(reqMessage); + } Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, applicationsRestClientService, app.getId(), orgUserId); RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInLocalApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", - logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + List roleAppUserList = rolesInAppForUser.roles; + // Apply changes in external Access system + updateUserRolesInExternalSystem(app, rolesInAppForUser.orgUserId, roleAppUserList); + logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", logMessage, + newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + } + // If local application is not centralized + else if(!app.getCentralAuth() && app.getId().equals(PortalConstants.PORTAL_APP_ID)){ + Set userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList, mapper, + applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInLocalApp); result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); } else {// remote app + + if(!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)){ EPUser remoteAppUser = null; - try { - remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); - } catch (HTTPException e) { - // Some apps are returning 400 if user is not found. - if (e.getResponseCode() == 400) { - logger.debug(EELFLoggerDelegate.debugLogger, - "setAppWithUserRoleStateForUser: getuserFromApp threw exception with response code 400; continuing", - e); - } else { - // Other response code, let it come thru. - throw e; - } - } + remoteAppUser = checkIfRemoteUserExits(userId.getOrgUserId(), app, applicationsRestClientService); if (remoteAppUser == null) { - createNewUserOnRemoteApp(orgUserId, app, applicationsRestClientService, searchService, mapper, - isAppUpgradeVersion(app)); - // If we succeed, we know that the new user was - // persisted on remote app. - remoteAppUser = getUserFromApp(orgUserId, app, applicationsRestClientService); - if (remoteAppUser == null) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to persist new user: " + orgUserId - + " in remote app. appId = " + app.getId()); - // return null; - } + addRemoteUser(roleInAppForUserList, userId.getOrgUserId(), app, mapper, searchService, applicationsRestClientService); reqMessage = "Saved Successfully"; } - if (remoteAppUser != null) { + if (remoteAppUser != null) { Set userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, - mapper, applicationsRestClientService, app.getId(), orgUserId); - + mapper, applicationsRestClientService, app.getId(), orgUserId); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), userRolesInRemoteApp); - logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", - logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); - result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType); + logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), + newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, + reqType); // If no roles remain, request app to set user inactive. /*if (userRolesInRemoteApp.size() == 0) { logger.debug(EELFLoggerDelegate.debugLogger, @@ -1129,7 +1359,19 @@ public class UserRolesCommonServiceImpl { remoteAppUser.setActive(false); postUserToRemoteApp(orgUserId, user, app, applicationsRestClientService); }*/ + } + } else { + if(!(reqType.equals("DELETE") && userId == null)){ + reqMessage = "Saved Successfully"; + } + Set userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList); + RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(), + userRolesInRemoteApp); + logger.info(EELFLoggerDelegate.debugLogger, "{} user app roles: for app {}, user {}", + logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId()); + result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, + reqType); } if(!result){ reqMessage = "Failed to save the user app role(s)"; @@ -1138,7 +1380,6 @@ public class UserRolesCommonServiceImpl { updateStatus = "C"; applyChangesToAppRolesRequest(app.getId(), userId.getId(), updateStatus, epRequestId.get(0)); } - } } catch (Exception e) { String message = String.format("Failed to create user or update user roles for User %s, AppId %s", @@ -1268,23 +1509,16 @@ public class UserRolesCommonServiceImpl { * @see org.openecomp.portalapp.portal.service.UserRolesService# * getAppRolesForUser(java.lang.Long, java.lang.String) */ + @SuppressWarnings("unchecked") public List getAppRolesForUser(Long appId, String userId, Boolean extRequestValue) { List rolesInAppForUser = null; - List userInfo = null; + EPApp app = appsService.getApp(appId); try { - // for ecomp portal app, no need to make a remote call if (appId == PortalConstants.PORTAL_APP_ID) { - final Map userParams = new HashMap<>(); - userParams.put("orgUserIdValue", userId); - userInfo = checkIfUserExists(userParams); - if(userInfo.size() == 0 || userInfo.isEmpty()) - { - createLocalUserIfNecessary(userId); - } - List roleList = roleService.getAvailableRoles(); + List roleList = roleService.getAvailableRoles(userId); List activeRoleList = new ArrayList(); for(Role role: roleList) { if(role.getActive()) { @@ -1296,28 +1530,66 @@ public class UserRolesCommonServiceImpl { } } - - EPApp app = appsService.getApp(appId); - EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); - Set roleSet = localUser.getAppEPRoles(app); - rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSet.toArray(new EPRole[0]), extRequestValue); + EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); + // If localUser does not exists return roles + Set roleSet = null; + EPRole[] roleSetList = null; + if(localUser != null){ + roleSet = localUser.getAppEPRoles(app); + roleSetList = roleSet.toArray(new EPRole[0]); + } + rolesInAppForUser = constructRolesInAppForUserGet(activeRoleList, roleSetList, extRequestValue); return rolesInAppForUser; } - - EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); - + + EcompRole[] appRoles = null; + List roles = new ArrayList<>(); + if(app.getCentralAuth()){ + List applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);; + for(EPRole role : applicationRoles){ + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getId()); + ecompRole.setName(role.getName()); + roles.add(ecompRole); + } + appRoles = roles.toArray(new EcompRole[roles.size()]); + } else{ + appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles"); + } // Test this error case, for generating an internal Ecomp Portal // error // EcompRole[] appRoles = null; // If there is an exception in the rest client api, then null will // be returned. if (appRoles != null) { + if(!app.getCentralAuth()) { syncAppRoles(sessionFactory, appId, appRoles); + } EcompRole[] userAppRoles = null; try { try { - userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, - String.format("/user/%s/roles", userId)); + if(app.getCentralAuth()){ + final Map params = new HashMap<>(); + final Map userParams = new HashMap<>(); + params.put("orgUserIdValue", userId); + List user = dataAccessService.executeNamedQuery("epUserAppId", params, null); + userParams.put("appId", app.getId()); + userParams.put("userId", user.get(0).getId()); + List userAppsRolesList = dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null); + List setUserRoles = new ArrayList<>(); + for(EPUserAppCurrentRoles role : userAppsRolesList){ + EcompRole ecompRole = new EcompRole(); + ecompRole.setId(role.getRoleId()); + ecompRole.setName(role.getRoleName()); + setUserRoles.add(ecompRole); + } + userAppRoles = setUserRoles.toArray(new EcompRole[setUserRoles.size()]); + rolesInAppForUser = constructRolesInAppForUserGet(appRoles, userAppRoles); + return rolesInAppForUser; + }else{ + userAppRoles = applicationsRestClientService.get(EcompRole[].class, appId, + String.format("/user/%s/roles", userId)); + } } catch (HTTPException e) { // Some apps are returning 400 if user is not found. if (e.getResponseCode() == 400) { @@ -1390,7 +1662,7 @@ public class UserRolesCommonServiceImpl { public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) { FieldsValidator fieldsValidator = new FieldsValidator(); final Map params = new HashMap<>(); - EpUserAppRoles appRole= new EpUserAppRoles(); + EPUserAppRoles appRole= new EPUserAppRoles(); try { logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); @@ -1409,7 +1681,7 @@ public class UserRolesCommonServiceImpl { Boolean isAppliedVal = userAppRoles.isApplied; params.put("appRoleId", userAppRoles.roleId); if (isAppliedVal) { - appRole = (EpUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); + appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail(); epAppRoleDetail.setReqRoleId(appRole.getRoleId()); epAppRoleDetail.setReqType("P"); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java index d7685627..1fead505 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/service/WidgetParameterServiceImpl.java @@ -49,8 +49,8 @@ public class WidgetParameterServiceImpl implements WidgetParameterService{ List restrictionsList = new ArrayList(); Criterion widgetIdCrit = Restrictions.eq("widgetId", widgetId); restrictionsList.add(widgetIdCrit); - Criterion attIdCrit = Restrictions.eq("userId", userId); - restrictionsList.add(attIdCrit); + Criterion userIdCrit = Restrictions.eq("userId", userId); + restrictionsList.add(userIdCrit); Criterion paramIdCrit = Restrictions.eq("paramId", paramId); restrictionsList.add(paramIdCrit); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunction.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunction.java new file mode 100644 index 00000000..d25cec5d --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadRoleFunction.java @@ -0,0 +1,68 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BulkUploadRoleFunction implements Serializable{ + + + private static final long serialVersionUID = -1880947347092068841L; + + @Id + @Column(name="function_name") + private String functionName; + @Id + @Column(name="function_cd") + private String functionCd; + + public String getFunctionName() { + return functionName; + } + public void setFunctionName(String functionName) { + this.functionName = functionName; + } + public String getFunctionCd() { + return functionCd; + } + public void setFunctionCd(String functionCd) { + this.functionCd = functionCd; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((functionCd == null) ? 0 : functionCd.hashCode()); + result = prime * result + ((functionName == null) ? 0 : functionName.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BulkUploadRoleFunction other = (BulkUploadRoleFunction) obj; + if (functionCd == null) { + if (other.functionCd != null) + return false; + } else if (!functionCd.equals(other.functionCd)) + return false; + if (functionName == null) { + if (other.functionName != null) + return false; + } else if (!functionName.equals(other.functionName)) + return false; + return true; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRoles.java new file mode 100644 index 00000000..8187ce4e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/BulkUploadUserRoles.java @@ -0,0 +1,83 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BulkUploadUserRoles implements Serializable{ + + private static final long serialVersionUID = -7478654947593502185L; + + @Id + @Column(name="role_name") + private String roleName; + @Id + @Column(name="org_user_id") + private String orgUserId; + @Id + @Column(name="auth_namespace") + private String appNameSpace; + + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public String getOrgUserId() { + return orgUserId; + } + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + public String getAppNameSpace() { + return appNameSpace; + } + public void setAppNameSpace(String appNameSpace) { + this.appNameSpace = appNameSpace; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((appNameSpace == null) ? 0 : appNameSpace.hashCode()); + result = prime * result + ((orgUserId == null) ? 0 : orgUserId.hashCode()); + result = prime * result + ((roleName == null) ? 0 : roleName.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BulkUploadUserRoles other = (BulkUploadUserRoles) obj; + if (appNameSpace == null) { + if (other.appNameSpace != null) + return false; + } else if (!appNameSpace.equals(other.appNameSpace)) + return false; + if (orgUserId == null) { + if (other.orgUserId != null) + return false; + } else if (!orgUserId.equals(other.orgUserId)) + return false; + if (roleName == null) { + if (other.roleName != null) + return false; + } else if (!roleName.equals(other.roleName)) + return false; + return true; + } + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java new file mode 100644 index 00000000..97907422 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralApp.java @@ -0,0 +1,210 @@ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; + +public class CentralApp { + public Long id; + public Date created; + public Date modified; + public Long createdId; + public Long modifiedId; + public Long rowNum; + public String name; // app_name + public String imageUrl; // app_image_url + public String description; // app_description + public String notes; // app_notes + public String url; // app_url + public String alternateUrl; // app_alternate_url + public String restEndpoint; // app_rest_endpoint + public String mlAppName; // ml_app_name + public String mlAppAdminId; // ml_app_admin_id; + public String motsId; // mots_id + public String appPassword; // app_password + public String open; + public String enabled; + public byte[] thumbnail; + public String username; // app_username + public String uebKey; // ueb_key + public String uebSecret; // ueb_secret + public String uebTopicName; // ueb_topic_name + + + public CentralApp(Long id, Date created, Date modified, Long createdId, Long modifiedId, Long rowNum, String name, + String imageUrl, String description, String notes, String url, String alternateUrl, String restEndpoint, + String mlAppName, String mlAppAdminId, String motsId, String appPassword, String open, String enabled, + byte[] thumbnail, String username, String uebKey, String uebSecret, String uebTopicName) { + super(); + this.id = id; + this.created = created; + this.modified = modified; + this.createdId = createdId; + this.modifiedId = modifiedId; + this.rowNum = rowNum; + this.name = name; + this.imageUrl = imageUrl; + this.description = description; + this.notes = notes; + this.url = url; + this.alternateUrl = alternateUrl; + this.restEndpoint = restEndpoint; + this.mlAppName = mlAppName; + this.mlAppAdminId = mlAppAdminId; + this.motsId = motsId; + this.appPassword = appPassword; + this.open = open; + this.enabled = enabled; + this.thumbnail = thumbnail; + this.username = username; + this.uebKey = uebKey; + this.uebSecret = uebSecret; + this.uebTopicName = uebTopicName; + } + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + public Date getCreated() { + return created; + } + public void setCreated(Date created) { + this.created = created; + } + public Date getModified() { + return modified; + } + public void setModified(Date modified) { + this.modified = modified; + } + public Long getCreatedId() { + return createdId; + } + public void setCreatedId(Long createdId) { + this.createdId = createdId; + } + public Long getModifiedId() { + return modifiedId; + } + public void setModifiedId(Long modifiedId) { + this.modifiedId = modifiedId; + } + public Long getRowNum() { + return rowNum; + } + public void setRowNum(Long rowNum) { + this.rowNum = rowNum; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getImageUrl() { + return imageUrl; + } + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getNotes() { + return notes; + } + public void setNotes(String notes) { + this.notes = notes; + } + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getAlternateUrl() { + return alternateUrl; + } + public void setAlternateUrl(String alternateUrl) { + this.alternateUrl = alternateUrl; + } + public String getRestEndpoint() { + return restEndpoint; + } + public void setRestEndpoint(String restEndpoint) { + this.restEndpoint = restEndpoint; + } + public String getMlAppName() { + return mlAppName; + } + public void setMlAppName(String mlAppName) { + this.mlAppName = mlAppName; + } + public String getMlAppAdminId() { + return mlAppAdminId; + } + public void setMlAppAdminId(String mlAppAdminId) { + this.mlAppAdminId = mlAppAdminId; + } + public String getMotsId() { + return motsId; + } + public void setMotsId(String motsId) { + this.motsId = motsId; + } + public String getAppPassword() { + return appPassword; + } + public void setAppPassword(String appPassword) { + this.appPassword = appPassword; + } + public String getOpen() { + return open; + } + public void setOpen(String open) { + this.open = open; + } + public String getEnabled() { + return enabled; + } + public void setEnabled(String enabled) { + this.enabled = enabled; + } + public byte[] getThumbnail() { + return thumbnail; + } + public void setThumbnail(byte[] thumbnail) { + this.thumbnail = thumbnail; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getUebKey() { + return uebKey; + } + public void setUebKey(String uebKey) { + this.uebKey = uebKey; + } + public String getUebSecret() { + return uebSecret; + } + public void setUebSecret(String uebSecret) { + this.uebSecret = uebSecret; + } + public String getUebTopicName() { + return uebTopicName; + } + public void setUebTopicName(String uebTopicName) { + this.uebTopicName = uebTopicName; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java new file mode 100644 index 00000000..a3c3c9d5 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralRole.java @@ -0,0 +1,159 @@ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; +import java.util.SortedSet; + +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; +import org.openecomp.portalapp.portal.domain.EPRole; + +public class CentralRole implements Comparable{ + public Long id; + public Date created; + public Date modified; + public Long createdId; + public Long modifiedId; + public Long rowNum; + + public String name; + public boolean active; + public Integer priority; + + public SortedSet roleFunctions = null; + + public SortedSet childRoles = null; + + public SortedSet parentRoles = null; + + public CentralRole(Long id, Date created, Date modified, Long createdId, Long modifiedId, Long rowNum, + String name, boolean active, Integer priority, SortedSet roleFunctions, + SortedSet childRoles, SortedSet parentRoles) { + super(); + this.id = id; + this.created = created; + this.modified = modified; + this.createdId = createdId; + this.modifiedId = modifiedId; + this.rowNum = rowNum; + this.name = name; + this.active = active; + this.priority = priority; + this.roleFunctions = roleFunctions; + this.childRoles = childRoles; + this.parentRoles = parentRoles; + } + + public CentralRole(){ + + } + + public CentralRole(Long id, String name){ + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getModified() { + return modified; + } + + public void setModified(Date modified) { + this.modified = modified; + } + + public Long getCreatedId() { + return createdId; + } + + public void setCreatedId(Long createdId) { + this.createdId = createdId; + } + + public Long getModifiedId() { + return modifiedId; + } + + public void setModifiedId(Long modifiedId) { + this.modifiedId = modifiedId; + } + + public Long getRowNum() { + return rowNum; + } + + public void setRowNum(Long rowNum) { + this.rowNum = rowNum; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public Integer getPriority() { + return priority; + } + + public void setPriority(Integer priority) { + this.priority = priority; + } + + public SortedSet getRoleFunctions() { + return roleFunctions; + } + + public void setRoleFunctions(SortedSet roleFunctions) { + this.roleFunctions = roleFunctions; + } + + public SortedSet getChildRoles() { + return childRoles; + } + + public void setChildRoles(SortedSet childRoles) { + this.childRoles = childRoles; + } + + public SortedSet getParentRoles() { + return parentRoles; + } + + public void setParentRoles(SortedSet parentRoles) { + this.parentRoles = parentRoles; + } + + public int compareTo(Object obj){ + EPRole other = (EPRole)obj; + + String c1 = getName(); + String c2 = other.getName(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java new file mode 100644 index 00000000..f8174825 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUser.java @@ -0,0 +1,139 @@ +package org.openecomp.portalapp.portal.transport; + +import java.util.Date; +import java.util.Set; + +public class CentralUser { + + + public Long id; + public Date created; + public Date modified; + public Long createdId; + public Long modifiedId; + public Long rowNum; + + public Long orgId; + public Long managerId; + public String firstName; + public String middleInitial; + public String lastName; + public String phone; + public String fax; + public String cellular; + public String email; + public Long addressId; + public String alertMethodCd; + public String hrid; + public String orgUserId; + public String orgCode; + public String address1; + public String address2; + public String city; + public String state; + public String zipCode; + public String country; + public String orgManagerUserId; + public String locationClli; + public String businessCountryCode; + public String businessCountryName; + public String businessUnit; + public String businessUnitName; + public String department; + public String departmentName; + public String companyCode; + public String company; + public String zipCodeSuffix; + public String jobTitle; + public String commandChain; + public String siloStatus; + public String costCenter; + public String financialLocCode; + + public String loginId; + public String loginPwd; + public Date lastLoginDate; + public boolean active; + public boolean internal; + public Long selectedProfileId; + public Long timeZoneId; + public boolean online; + public String chatId; + + public Set userApps = null; + public Set pseudoRoles = null; + + public CentralUser(){ + + } + + public CentralUser(Long id, Date created, Date modified, Long createdId, Long modifiedId, Long rowNum, Long orgId, + Long managerId, String firstName, String middleInitial, String lastName, String phone, String fax, + String cellular, String email, Long addressId, String alertMethodCd, String hrid, String orgUserId, + String orgCode, String address1, String address2, String city, String state, String zipCode, String country, + String orgManagerUserId, String locationClli, String businessCountryCode, String businessCountryName, + String businessUnit, String businessUnitName, String department, String departmentName, String companyCode, + String company, String zipCodeSuffix, String jobTitle, String commandChain, String siloStatus, + String costCenter, String financialLocCode, String loginId, String loginPwd, Date lastLoginDate, + boolean active, boolean internal, Long selectedProfileId, Long timeZoneId, boolean online, String chatId, + Set userApps, Set pseudoRoles) { + super(); + this.id = id; + this.created = created; + this.modified = modified; + this.createdId = createdId; + this.modifiedId = modifiedId; + this.rowNum = rowNum; + this.orgId = orgId; + this.managerId = managerId; + this.firstName = firstName; + this.middleInitial = middleInitial; + this.lastName = lastName; + this.phone = phone; + this.fax = fax; + this.cellular = cellular; + this.email = email; + this.addressId = addressId; + this.alertMethodCd = alertMethodCd; + this.hrid = hrid; + this.orgUserId = orgUserId; + this.orgCode = orgCode; + this.address1 = address1; + this.address2 = address2; + this.city = city; + this.state = state; + this.zipCode = zipCode; + this.country = country; + this.orgManagerUserId = orgManagerUserId; + this.locationClli = locationClli; + this.businessCountryCode = businessCountryCode; + this.businessCountryName = businessCountryName; + this.businessUnit = businessUnit; + this.businessUnitName = businessUnitName; + this.department = department; + this.departmentName = departmentName; + this.companyCode = companyCode; + this.company = company; + this.zipCodeSuffix = zipCodeSuffix; + this.jobTitle = jobTitle; + this.commandChain = commandChain; + this.siloStatus = siloStatus; + this.costCenter = costCenter; + this.financialLocCode = financialLocCode; + this.loginId = loginId; + this.loginPwd = loginPwd; + this.lastLoginDate = lastLoginDate; + this.active = active; + this.internal = internal; + this.selectedProfileId = selectedProfileId; + this.timeZoneId = timeZoneId; + this.online = online; + this.chatId = chatId; + this.userApps = userApps; + this.pseudoRoles = pseudoRoles; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUserApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUserApp.java new file mode 100644 index 00000000..9317b9fe --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/CentralUserApp.java @@ -0,0 +1,70 @@ +package org.openecomp.portalapp.portal.transport; + +@SuppressWarnings("rawtypes") +public class CentralUserApp implements Comparable{ + + private Long userId; + private CentralApp app; + private CentralRole role; + private Short priority; + + + + public Long getUserId() { + return userId; + } + + + + public void setUserId(Long userId) { + this.userId = userId; + } + + + + public CentralApp getApp() { + return app; + } + + + + public void setApp(CentralApp app) { + this.app = app; + } + + + + public CentralRole getRole() { + return role; + } + + + + public void setRole(CentralRole role) { + this.role = role; + } + + + + public Short getPriority() { + return priority; + } + + + + public void setPriority(Short priority) { + this.priority = priority; + } + + + + public int compareTo(Object other){ + CentralUserApp castOther = (CentralUserApp) other; + + Long c1 = (this.getUserId()==null ? 0 : this.getUserId()) + (this.priority==null ? 0 : this.priority); + Long c2 = (castOther.getUserId()==null ? 0 : castOther.getUserId()) + (castOther.getApp()==null||castOther.getApp().getId()==null ? 0 : castOther.getApp().getId()) + (castOther.priority==null ? 0 : castOther.priority); + + return c1.compareTo(c2); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRoles.java new file mode 100644 index 00000000..085df3b8 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EPUserAppCurrentRoles.java @@ -0,0 +1,98 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EPUserAppCurrentRoles implements Serializable{ + + private static final long serialVersionUID = -8145807875293949759L; + + @Id + @Column(name="role_name") + private String roleName; + @Id + @Column(name="user_id") + private Long userId; + @Id + @Column(name="priority") + private String priority ; + @Id + @Column(name="role_id") + private Long roleId; + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((priority == null) ? 0 : priority.hashCode()); + result = prime * result + ((roleId == null) ? 0 : roleId.hashCode()); + result = prime * result + ((roleName == null) ? 0 : roleName.hashCode()); + result = prime * result + ((userId == null) ? 0 : userId.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EPUserAppCurrentRoles other = (EPUserAppCurrentRoles) obj; + if (priority == null) { + if (other.priority != null) + return false; + } else if (!priority.equals(other.priority)) + return false; + if (roleId == null) { + if (other.roleId != null) + return false; + } else if (!roleId.equals(other.roleId)) + return false; + if (roleName == null) { + if (other.roleName != null) + return false; + } else if (!roleName.equals(other.roleName)) + return false; + if (userId == null) { + if (other.userId != null) + return false; + } else if (!userId.equals(other.userId)) + return false; + return true; + } + + + +} + \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserAppRoles.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserAppRoles.java new file mode 100644 index 00000000..3ac21040 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EcompUserAppRoles.java @@ -0,0 +1,66 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +import com.fasterxml.jackson.annotation.JsonInclude; + +@Entity +@JsonInclude(JsonInclude.Include.NON_NULL) +public class EcompUserAppRoles implements Serializable { + + private static final long serialVersionUID = -3394219387296578741L; + + @Id + @Column(name="app_id") + private String appId; + @Id + @Column(name="user_id") + private Long userId; + @Id + @Column(name="priority") + private String priority ; + @Id + @Column(name="role_id") + private Long roleId; + @Id + @Column(name="role_name") + private String roleName; + public String getAppId() { + return appId; + } + public void setAppId(String appId) { + this.appId = appId; + } + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public Long getRoleId() { + return roleId; + } + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + public String getRoleName() { + return roleName; + } + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java index 00df522a..6f7c96b3 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItem.java @@ -88,6 +88,9 @@ public class EpNotificationItem extends DomainVo { @Column(name = "created_date") public Date createdDate; + + @Column(name = "notification_hyperlink") + public String notificationHyperlink; @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true) @@ -212,6 +215,14 @@ public class EpNotificationItem extends DomainVo { public void setMsgSource(String msgSource) { this.msgSource = msgSource; } + + public String getNotificationHyperlink() { + return notificationHyperlink; + } + + public void setNotificationHyperlink(String notificationHyperlink) { + this.notificationHyperlink = notificationHyperlink; + } @Override public int hashCode() { diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java index 3cb0f3a6..d1ebe13c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EpNotificationItemVO.java @@ -65,7 +65,10 @@ public class EpNotificationItemVO extends DomainVo { private Date createdDate; private String loginId; + + private String notificationHyperlink; + /** * Answers whether the notification is expired. * @@ -188,4 +191,13 @@ public class EpNotificationItemVO extends DomainVo { public void setMsgSource(String msgSource) { this.msgSource = msgSource; } + + public String getNotificationHyperlink() { + return notificationHyperlink; + } + + public void setNotificationHyperlink(String notificationHyperlink) { + this.notificationHyperlink = notificationHyperlink; + } + } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java index 4922b03e..fe4a3cde 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/EventWidget.java @@ -31,7 +31,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; *//** * This is to handle portal admins - * @author aw3218 *//* @Entity @Table(name="fn_event_widget_data") diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java new file mode 100644 index 00000000..60f9f63a --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPerms.java @@ -0,0 +1,96 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +public class ExternalAccessPerms implements Serializable, Comparable{ + + /** + * + */ + private static final long serialVersionUID = -200964838466882602L; + public String type; + public String instance; + public String action; + public String description; + + + public ExternalAccessPerms() { + super(); + } + + + + public ExternalAccessPerms(String type, String instance, String action, String description) { + super(); + this.type = type; + this.instance = instance; + this.action = action; + this.description = description; + } + + public ExternalAccessPerms(String type, String instance, String action) { + super(); + this.type = type; + this.instance = instance; + this.action = action; + } + + + /** + * @return the type + */ + public String getType() { + return type; + } + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + /** + * @return the instance + */ + public String getInstance() { + return instance; + } + /** + * @param instance the instance to set + */ + public void setInstance(String instance) { + this.instance = instance; + } + /** + * @return the action + */ + public String getAction() { + return action; + } + /** + * @param action the action to set + */ + public void setAction(String action) { + this.action = action; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + + @Override + public int compareTo(Object obj){ + ExternalAccessPerms other = (ExternalAccessPerms)obj; + + String c1 = getInstance(); + String c2 = other.getInstance(); + + return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2); + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetail.java new file mode 100644 index 00000000..39c29dd8 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessPermsDetail.java @@ -0,0 +1,90 @@ +package org.openecomp.portalapp.portal.transport; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonRootName; + +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonRootName(value="perm") +public class ExternalAccessPermsDetail { + + private String type; + private String instance; + private String action; + private List roles; + private String description; + + + + public ExternalAccessPermsDetail() { + super(); + } + + /** + * @param type + * @param instance + * @param action + * @param roles + * @param description + */ + public ExternalAccessPermsDetail(String type, String instance, String action, List roles, + String description) { + super(); + this.type = type; + this.instance = instance; + this.action = action; + this.roles = roles; + this.description = description; + } + + /** + * @param type + * @param instance + * @param action + * @param description + */ + public ExternalAccessPermsDetail(String type, String instance, String action, + String description) { + super(); + this.type = type; + this.instance = instance; + this.action = action; + this.description = description; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getInstance() { + return instance; + } + public void setInstance(String instance) { + this.instance = instance; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public List getRoles() { + return roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRole.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRole.java new file mode 100644 index 00000000..949c191e --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRole.java @@ -0,0 +1,39 @@ +package org.openecomp.portalapp.portal.transport; + +import java.io.Serializable; + +public class ExternalAccessRole implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 3439986826362436339L; + public String name; + public String description; + + public ExternalAccessRole() { + + } + + public ExternalAccessRole(String name, String description) { + super(); + this.name = name; + this.description = description; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePerms.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePerms.java new file mode 100644 index 00000000..460b02ac --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessRolePerms.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.portal.transport; + +public class ExternalAccessRolePerms { + + private ExternalAccessPerms perm; + private String role; + + + public ExternalAccessRolePerms(ExternalAccessPerms perm, String role) { + super(); + this.perm = perm; + this.role = role; + } + + public ExternalAccessPerms getPerm() { + return perm; + } + public void setPerm(ExternalAccessPerms perm) { + this.perm = perm; + } + public String getRole() { + return role; + } + public void setRole(String role) { + this.role = role; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUser.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUser.java new file mode 100644 index 00000000..30674bf3 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUser.java @@ -0,0 +1,28 @@ +package org.openecomp.portalapp.portal.transport; + +public class ExternalAccessUser { + + private String user; + private String role; + + public ExternalAccessUser(String user, String role) { + super(); + this.user = user; + this.role = role; + } + + public String getUser() { + return user; + } + public void setUser(String user) { + this.user = user; + } + public String getRole() { + return role; + } + public void setRole(String role) { + this.role = role; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java new file mode 100644 index 00000000..e5d89e22 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalAccessUserRoleDetail.java @@ -0,0 +1,36 @@ +package org.openecomp.portalapp.portal.transport; + +public class ExternalAccessUserRoleDetail { + + private String name; + private ExternalRoleDescription description; + + + /** + * + */ + public ExternalAccessUserRoleDetail() { + super(); + } + + public ExternalAccessUserRoleDetail(String name, ExternalRoleDescription description) { + super(); + this.name = name; + this.description = description; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public ExternalRoleDescription getDescription() { + return description; + } + public void setDescription(ExternalRoleDescription description) { + this.description = description; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java new file mode 100644 index 00000000..d6eba633 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/ExternalRoleDescription.java @@ -0,0 +1,50 @@ +package org.openecomp.portalapp.portal.transport; + +public class ExternalRoleDescription { + + private String id; + private String name; + private String active; + private String priority; + private String appId; + private String appRoleId; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getActive() { + return active; + } + public void setActive(String active) { + this.active = active; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getAppId() { + return appId; + } + public void setAppId(String appId) { + this.appId = appId; + } + public String getAppRoleId() { + return appRoleId; + } + public void setAppRoleId(String appRoleId) { + this.appRoleId = appRoleId; + } + + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java index a4198d1d..3187d093 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -66,6 +66,10 @@ public class OnboardingApp { public String uebSecret; public Boolean restrictedApp; + + public Boolean isCentralAuth; + + public String nameSpace; /** * Sets the name, myLoginsAppName, myLoginsAppOwner, username and diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java index 34be46e3..a80517d2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/ueb/EPUebHelper.java @@ -155,7 +155,7 @@ public class EPUebHelper { // // Test existence of topic at UEB url // - // (ie http://uebsb91kcdc.it.att.com:3904/topics/ECOMP-PORTAL-INBOX) + // (ie http://uebsb91kcdc.it.com:3904/topics/ECOMP-PORTAL-INBOX) // boolean available = true; LinkedList urlList = Helper.uebUrlList(); diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java index dd33bf6e..4d472801 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EPCommonSystemProperties.java @@ -61,7 +61,14 @@ public class EPCommonSystemProperties extends SystemProperties { public static final String AUTH_USER_SERVER = "auth_user_server"; public static final String EXTERNAL_ACCESS_ENABLE = "external_access_enable"; + + public static final String EXTERNAL_SYSTEM_NOTIFICATION_URL = "external_system_notification_url"; + public static final String EXTERNAL_CENTRAL_AUTH_USER_NAME = "ext_central_access_user_name"; + public static final String EXTERNAL_CENTRAL_AUTH_PASSWORD = "ext_central_access_password"; + public static final String EXTERNAL_CENTRAL_ACCESS_URL = "ext_central_access_url"; + public static final String EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN = "ext_central_access_user_domain"; + public static final String WIDGET_MS_PROTOCOL = "microservices.widget.protocol"; public static final String WIDGET_MS_HOSTNAME = "microservices.widget.hostname"; -} \ No newline at end of file +} diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java index d471d90b..0284452a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/EcompPortalUtils.java @@ -29,6 +29,7 @@ import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.DatatypeConverter; import org.hibernate.Session; import org.hibernate.Transaction; @@ -36,8 +37,11 @@ import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum; import org.openecomp.portalapp.portal.logging.logic.EPLogUtil; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; import org.openecomp.portalsdk.core.util.SystemProperties; import org.slf4j.MDC; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -369,5 +373,45 @@ public class EcompPortalUtils { } } + /** + * It returns headers where username and password of external central auth + * is encoded to base64 + * + * @return header which contains external central auth username and password + * base64 encoded + * @throws Exception + * if unable to decrypt the password + */ + public static HttpHeaders base64encodeKeyForAAFBasicAuth() throws Exception { + + String userName = ""; + String decryptedPass = ""; + if (EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME) && EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD)) { + decryptedPass = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_PASSWORD); + userName = SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_AUTH_USER_NAME); + } + String decPass = decrypted(decryptedPass); + String usernamePass = userName + ":" + decPass; + String encToBase64 = String.valueOf((DatatypeConverter.printBase64Binary(usernamePass.getBytes()))); + HttpHeaders headers = new HttpHeaders(); + headers.add("Authorization", "Basic " + encToBase64); + headers.setContentType(MediaType.APPLICATION_JSON); + return headers; + } + + private static String decrypted(String encrypted) throws Exception { + String result = ""; + if (encrypted != null && encrypted.length() > 0) { + try { + result = CipherUtil.decrypt(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key)); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e); + throw e; + } + } + return result; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java index 485a80f5..57bb543f 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/portal/utils/PortalConstants.java @@ -24,6 +24,7 @@ public interface PortalConstants { public static final Long DEFAULT_NOTIFICATION_CREATOR = 1L; public static final String REST_AUX_API = "/auxapi"; public static final Long ACCOUNT_ADMIN_ROLE_ID = 999L; - public static final int SYS_ADMIN_ROLE_ID = 1; + public static final Long SYS_ADMIN_ROLE_ID = 1L; public static final String ADMIN_ROLE = "Account Administrator"; + public static final String PORTAL_ADMIN_ROLE = "System Administrator"; } diff --git a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java index 7dcf0e95..533ed53d 100644 --- a/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java +++ b/ecomp-portal-BE-common/src/main/java/org/openecomp/portalapp/util/EPUserUtils.java @@ -19,11 +19,13 @@ */ package org.openecomp.portalapp.util; +import java.util.ArrayList; import java.util.Enumeration; 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; @@ -31,15 +33,24 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.transform.Transformers; +import org.openecomp.portalapp.portal.domain.CentralRoleFunction; import org.openecomp.portalapp.portal.domain.EPRole; import org.openecomp.portalapp.portal.domain.EPUser; import org.openecomp.portalapp.portal.domain.EPUserApp; +import org.openecomp.portalapp.portal.service.EPRoleFunctionService; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; import org.openecomp.portalsdk.core.domain.RoleFunction; import org.openecomp.portalsdk.core.exception.SessionExpiredException; import org.openecomp.portalsdk.core.lm.FusionLicenseManager; import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.openecomp.portalsdk.core.menu.MenuBuilder; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; import org.openecomp.portalsdk.core.service.DataAccessService; import org.openecomp.portalsdk.core.util.SystemProperties; import org.openecomp.portalsdk.core.web.support.AppUtils; @@ -54,6 +65,9 @@ public class EPUserUtils { public static final String ALL_ROLE_FUNCTIONS = "allRoleFunctions"; private static DataAccessService dataAccessService; + + @Autowired + private static SessionFactory sessionFactory; /** * Gets the EPUser object from the session. @@ -89,17 +103,17 @@ public class EPUserUtils { */ @SuppressWarnings("rawtypes") public static void setUserSession(HttpServletRequest request, EPUser user, Set applicationMenuData, - Set businessDirectMenuData, String loginMethod_ignored, List allRoleFunctions) { + Set businessDirectMenuData, String loginMethod_ignored, EPRoleFunctionService ePRoleFunctionService) { HttpSession session = request.getSession(true); // clear the current user session to avoid any conflicts EPUserUtils.clearUserSession(request); session.setAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME), user); - getAllRoleFunctions(allRoleFunctions, session); - - getRoleFunctions(request); - + setAllRoleFunctions(ePRoleFunctionService.getRoleFunctions(), session); + + ePRoleFunctionService.getRoleFunctions(request,user); + // truncate the role (and therefore the role function) data to save // memory in the session user.setEPRoles(null); @@ -146,7 +160,7 @@ public class EPUserUtils { * @param session * HttpSession */ - private static void getAllRoleFunctions(List allRoleFunctions, HttpSession session) { + private static void setAllRoleFunctions(List allRoleFunctions, HttpSession session) { if (allRoleFunctions == null) return; Set roleFnSet = new HashSet(); @@ -176,45 +190,6 @@ public class EPUserUtils { session.removeAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); } - /** - * Builds a set of role functions and sets a session attribute with it. - * - * @param request - * HttpServletRequest - * @return Set of role functions that was built. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static Set getRoleFunctions(HttpServletRequest request) { - HashSet roleFunctions = null; - - HttpSession session = request.getSession(); - roleFunctions = (HashSet) session - .getAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)); - - if (roleFunctions == null) { - HashMap roles = getRoles(request); - roleFunctions = new HashSet(); - - Iterator i = roles.keySet().iterator(); - - while (i.hasNext()) { - Long roleKey = (Long) i.next(); - EPRole role = (EPRole) roles.get(roleKey); - - Iterator j = role.getRoleFunctions().iterator(); - - while (j.hasNext()) { - RoleFunction function = (RoleFunction) j.next(); - roleFunctions.add(function.getCode()); - } - } - - session.setAttribute(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME), - roleFunctions); - } - - return roleFunctions; - } /** * Gets role information from the user session, in the cached user object. @@ -225,7 +200,7 @@ public class EPUserUtils { * @return Map of role ID to role object */ @SuppressWarnings("rawtypes") - private static HashMap getRoles(HttpServletRequest request) { + public static HashMap getRoles(HttpServletRequest request) { HashMap roles = null; HttpSession session = AppUtils.getSession(request); diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index eea9467a..342a6e8c 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -321,7 +321,12 @@ - + + + + + + @@ -433,6 +438,29 @@ + + + + + seq_epp_app_role_func + + + + + + + + + + + + + + + + @@ -612,17 +640,17 @@ + + + + + @@ -1074,7 +1112,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1102,7 +1140,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1131,7 +1170,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1161,7 +1201,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1193,7 +1234,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1228,7 +1270,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1266,7 +1309,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1307,7 +1351,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1344,7 +1389,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1381,7 +1427,8 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name a.APP_NOTES , a.APP_URL , a.APP_ALTERNATE_URL , a.APP_REST_ENDPOINT , a.ML_APP_NAME , a.ML_APP_ADMIN_ID , a.MOTS_ID , a.APP_PASSWORD , a.THUMBNAIL , a.APP_USERNAME , a.OPEN , a.ENABLED , - a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE + a.UEB_TOPIC_NAME , a.UEB_KEY , a.UEB_SECRET , a.APP_TYPE , a.AUTH_CENTRAL , + a.AUTH_NAMESPACE from FN_APP a -- Portal assigns role 999 to app administrator left outer join FN_USER_ROLE r ON a.APP_ID = r.APP_ID and r.USER_ID = :userId and r.ROLE_ID != 999 @@ -1460,6 +1507,16 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name ]]> + + + + + + + class="org.openecomp.portalapp.portal.domain.EPUserAppRoles" /> @@ -1681,7 +1738,7 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name select fr.role_name, fa.app_name from fn_role fr, fn_user_role fur, fn_app fa, fn_user fu - Where fu.user_id = fur.user_id and fur.role_id = fr.role_id and fa.app_id = fur.app_id and fu.org_user_id = :userId + Where fu.user_id = fur.user_id and fur.role_id = fr.role_id and fa.app_id = fur.app_id and fu.org_user_id = :userId and fr.active_yn='Y' and (fa.enabled = 'Y' or fa.app_id=1) ; ]]> @@ -1711,5 +1768,173 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' order by app_name delete from ep_user_notification where notification_id in (select notification_id from ep_notification where curdate() >= DATE_ADD(end_time,INTERVAL 3 MONTH)) ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp deleted file mode 100644 index d90704c3..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,120 +0,0 @@ -<%-- - ================================================================================ - ECOMP Portal - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - Licensed 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. - ================================================================================ - --%> -<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ page import="java.net.URLEncoder" %> -<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %> - - - - - - - - - - - - - - - - - - - - <% - String returnUrl = request.getParameter("returnUrl"); - String redirectUrl = request.getParameter("redirectUrl"); - returnUrl = ((returnUrl == null) ? (request.isSecure() ?"https://":"http://") + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/process_csp" + "?redirectUrl=" + redirectUrl: URLEncoder.encode(returnUrl)); - %> - - -
- -
- AT&T -
-
-
-
-
- -
- - Click here to login - -
-
-
-
-
-







- -
- - - - diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp deleted file mode 100644 index 94c2f55e..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/jsp/login_external.jsp +++ /dev/null @@ -1,162 +0,0 @@ -<%-- - ================================================================================ - ECOMP Portal - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - Licensed 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. - ================================================================================ - --%> -<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> -<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> -<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties" %> - -" /> - - - - - - Login - - - - - - - - - - - - - - - - - -
- -
- AT&T -
-
- -
-
- Portal -

ECOMP Portal

- - -
-
- - -
-
-                - -
-
-
-






- -
- - - - diff --git a/ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/app.js b/ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/app.js deleted file mode 100644 index be422026..00000000 --- a/ecomp-portal-BE-common/src/main/webapp/static/ebz/angular_js/app.js +++ /dev/null @@ -1,3 +0,0 @@ -angular.module('att.abs.helper', []); - -var app=angular.module("abs", []); \ No newline at end of file diff --git a/ecomp-portal-BE-common/src/main/webapp/static/fusion/images/onap-portal-logo.png b/ecomp-portal-BE-common/src/main/webapp/static/fusion/images/onap-portal-logo.png index f48d3d47..3fa9b92e 100644 Binary files a/ecomp-portal-BE-common/src/main/webapp/static/fusion/images/onap-portal-logo.png and b/ecomp-portal-BE-common/src/main/webapp/static/fusion/images/onap-portal-logo.png differ diff --git a/ecomp-portal-BE-os/README.md b/ecomp-portal-BE-os/README.md index aa406022..e116bc6d 100644 --- a/ecomp-portal-BE-os/README.md +++ b/ecomp-portal-BE-os/README.md @@ -14,10 +14,11 @@ https://www.eclipse.org/m2e-wtp/ ## Release Notes -Version 1.1.0, July 2017 +Version 1.1.0 (Amsterdam), November 2017 - [Portal-6] Updates to License and Trademark in the PORTAL Source Code - [Portal-7] Improvements added as part of the rebasing process - [Portal-17] Remove jfree related items +- [PORTAL-21] FE changes to OS for AAF centralization and name space field; DB script updates for EcompPortalDDLMySql_1710_Common.sql under ecomp-portal-DB-common, EcompPortalDMLMySql_1710_OS.sql under ecomp-portal-DB-os; - [Portal-30] Failed to communicate with the widget microservice: Fixed - [Portal-35] Replaced the portal logo with onap logo on the login screen. - [Portal-40] Fix to add user roles @@ -26,6 +27,12 @@ Version 1.1.0, July 2017 - [Portal-48] Fix to save a new app on Application onboarding - [Portal-49] image icon is missing on Widget corner - [Portal-63] remove att_abs_tpls*.js and greensock url +- [Portal-69] unable to pick role in Functional Menu Update +- [Portal-73] unable to onboard new Application fix +- [Portal-50] Enabled the junit coverage in ONAP +- [Portal-76] Edit functional menu modal doesn't show +- [Portal-61] Fixed the routing problem, loaded data and changed the notification hyperlink +- [Portal-77] Changes to remove preview image and update the new image automatically on App onbarding page Version 1.0.0, February 2017 - Initial release diff --git a/ecomp-portal-BE-os/pom.xml b/ecomp-portal-BE-os/pom.xml index d00d47a0..a8c19a54 100644 --- a/ecomp-portal-BE-os/pom.xml +++ b/ecomp-portal-BE-os/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - org.openecomp.portal + org.onap.portal ecompportal-be-os war 1.1 @@ -10,18 +10,17 @@ 4.2.0.RELEASE 4.3.11.Final 1.0.0 - 1.1.0 - 1.1.0 + 1.3.0-SNAPSHOT + 1.3.0-SNAPSHOT UTF-8 - false - + true + 0 **.js https://nexus.onap.org content/repositories/snapshots/ content/repositories/releases/ - /content/sites/site/org/onap/portal/${project.version} @@ -42,28 +41,26 @@ true + ecomp-site - dav:${nexusproxy}${sitePath} + dav:${nexusproxy}/content/sites/site/org/onap/portal/${project.version} - ecomp-releases - OpenECOMP - Release Repository + onap-releases ${nexusproxy}/${releaseNexusPath} - ecomp-snapshots - OpenECOMP - Snapshot Repository + onap-snapshots ${nexusproxy}/${snapshotNexusPath} - ecomp-public - ecomp onap public Repository + onap-public https://nexus.onap.org/content/groups/public @@ -99,6 +96,121 @@ 1.8 + + org.jacoco + jacoco-maven-plugin + 0.7.5.201505241946 + + + + + pre-unit-test + + prepare-agent + + + + ${basedir}/target/coverage-reports/jacoco-ut.exec + + surefireArgLine + ${skipTests} + + + + + + post-unit-test + test + + report + + + + ${project.build.directory}/coverage-reports/jacoco-ut.exec + + ${project.reporting.outputDirectory}/jacoco-ut + ${skipTests} + + + + + + default-instrument + + instrument + + + ${skipTests} + + + + default-restore-instrumented-classes + + restore-instrumented-classes + + + ${skipTests} + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 3.0.2 + + + copy-src + generate-resources + + copy-resources + + + ${basedir}/target/classes + false + ${skipTests} + + + ${basedir}/../ecomp-portal-BE-common/target/classes + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + ${skipTests} + + **/*Test.java + **/*TestCase.java + **/*TestSuite.java + + + + **/*TestFromSuite.java + + + ${basedir}/src/main/webapp + ../ecomp-portal-BE-common/src/main/webapp + ../ecomp-portal-BE-common + + + classpath: + + + maven-war-plugin @@ -118,13 +230,13 @@ - org.openecomp.portal + org.onap.portal ecompportal-be-common - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-app-overlay - + @@ -249,17 +361,29 @@ + org.springframework @@ -412,7 +536,6 @@ * - @@ -540,14 +663,14 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-app-overlay ${epsdk.version} war - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-app-common ${epsdk.version} jar @@ -555,14 +678,14 @@ - org.openecomp.portal + org.onap.portal ecompportal-be-common ${portal.version} war - org.openecomp.portal + org.onap.portal ecompportal-be-common ${portal.version} jar @@ -570,7 +693,7 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-fw ${epsdk.version} @@ -594,13 +717,13 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-core ${epsdk.version} - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-workflow ${epsdk.version} @@ -608,7 +731,7 @@ - org.openecomp.ecompsdkos + org.onap.portal.sdk epsdk-analytics ${epsdk.version} @@ -628,13 +751,26 @@ 4.11 test - + org.onap.portal + ecomp-portal-BE-common-test + ${portal.version} + test + + + org.mockito + mockito-core + 1.8.5 + test + + commons-beanutils commons-beanutils 1.9.2 - + + + org.mitre diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java index 8365ebc2..48f447b4 100644 --- a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/OpenIdConnectLoginStrategy.java @@ -64,7 +64,7 @@ public class OpenIdConnectLoginStrategy extends org.openecomp.portalsdk.core.aut user.setLastName(userInfo.getFamilyName()); //store the currently logged in user's information in the session - EPUserUtils.setUserSession(request, user, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), null); + EPUserUtils.setUserSession(request, user, new HashSet(), new HashSet(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),null); logger.info(EELFLoggerDelegate.errorLogger, request.getContextPath()); SessionCookieUtil.preSetUp(request, response); diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java index c1fee7f3..0c3c4996 100644 --- a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/authentication/SimpleLoginStrategy.java @@ -24,6 +24,7 @@ import javax.servlet.http.HttpServletResponse; import org.openecomp.portalapp.command.EPLoginBean; import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleFunctionService; import org.openecomp.portalapp.portal.service.EPRoleService; import org.openecomp.portalapp.portal.utils.EPSystemProperties; import org.openecomp.portalapp.portal.utils.EcompPortalUtils; @@ -45,6 +46,9 @@ public class SimpleLoginStrategy extends org.openecomp.portalsdk.core.auth.Login @Autowired private EPRoleService roleService; + @Autowired + private EPRoleFunctionService ePRoleFunctionService; + private static final String GLOBAL_LOCATION_KEY = "Location"; EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SimpleLoginStrategy.class); @@ -66,7 +70,7 @@ public class SimpleLoginStrategy extends org.openecomp.portalsdk.core.auth.Login } else { // store the currently logged in user's information in the session - EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "", roleService.getRoleFunctions()); + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), "", ePRoleFunctionService); logger.info(EELFLoggerDelegate.debugLogger, commandBean.getUser().getOrgUserId() + " exists in the the system."); } diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java index a16cf56b..92d63742 100644 --- a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java @@ -200,7 +200,7 @@ public class ExternalAppConfig extends AppConfig implements Configurable { registry.addInterceptor(sessionTimeoutInterceptor()).excludePathPatterns("/oid-login", "/portalApi/healthCheck", "/portalApi/healthCheck/", "/portalApi/healthCheckSuspend", "/portalApi/healthCheckSuspend/", "/portalApi/healthCheckResume", "/portalApi/healthCheckResume/", "/login_external", - "/login_external.htm*", "login", "/login.htm*", "/auxapi/*", "/context/*", "/api*", + "/login_external.htm*", "login", "/login.htm*","/auxapi/*","/context/*", "/api*", "/single_signon.htm", "/single_signon", "/dashboard", "/OpenSourceLogin.htm"); registry.addInterceptor(portalResourceInterceptor()); diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java index 6f3d2278..33cc4dd7 100644 --- a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/controller/LoginController.java @@ -36,6 +36,7 @@ import org.json.JSONObject; import org.openecomp.portalapp.command.EPLoginBean; import org.openecomp.portalapp.portal.domain.SharedContext; import org.openecomp.portalapp.portal.service.EPLoginService; +import org.openecomp.portalapp.portal.service.EPRoleFunctionService; import org.openecomp.portalapp.portal.service.EPRoleService; import org.openecomp.portalapp.portal.service.SharedContextService; import org.openecomp.portalapp.portal.utils.EPSystemProperties; @@ -84,6 +85,9 @@ public class LoginController extends EPUnRestrictedBaseController implements Log @Autowired private EPRoleService roleService; + @Autowired + private EPRoleFunctionService ePRoleFunctionService; + String viewName = "login"; private String welcomeView; @@ -142,8 +146,7 @@ public class LoginController extends EPUnRestrictedBaseController implements Log } else { // store the currently logged in user's information in the session - EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), - roleService.getRoleFunctions()); + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),ePRoleFunctionService); try{ logger.info(EELFLoggerDelegate.debugLogger, "******************* store user info into share context begins"); @@ -249,7 +252,7 @@ public class LoginController extends EPUnRestrictedBaseController implements Log sbAdditionalInfo.append(String.format("Login-Id: %s, Login-Method: %s, Request-URL: %s", orgUserId, "", fullURL)); logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId); - EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM), roleService.getRoleFunctions()); + EPUserUtils.setUserSession(request, commandBean.getUser(), commandBean.getMenu(), commandBean.getBusinessDirectMenu(), SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM),ePRoleFunctionService); logger.info(EELFLoggerDelegate.debugLogger, "*********************** now set up user session for " + orgUserId + " finished"); //Store user's information into share context diff --git a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java index f953634a..eee12234 100644 --- a/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java +++ b/ecomp-portal-BE-os/src/main/java/org/openecomp/portalapp/portal/transport/OnboardingApp.java @@ -56,6 +56,10 @@ public class OnboardingApp { public String uebSecret; public Boolean restrictedApp; + + public Boolean isCentralAuth; + + public String nameSpace; public void normalize() { this.name = (this.name == null) ? "" : this.name.trim(); diff --git a/ecomp-portal-BE-os/src/main/resources/portal.properties b/ecomp-portal-BE-os/src/main/resources/portal.properties index a1982632..e23d04e4 100644 --- a/ecomp-portal-BE-os/src/main/resources/portal.properties +++ b/ecomp-portal-BE-os/src/main/resources/portal.properties @@ -42,3 +42,8 @@ ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-DEV-LOCAL # Consumer group name for UEB topic. # Use the special tag to generate a unique one for each sdk-app server. ueb_app_consumer_group_name = {UUID} + +role_access_centralized = remote + +ext_req_connection_timeout = 15000 +ext_req_read_timeout = 20000 diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties index 0c32ef65..68d60140 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/raptor.properties @@ -107,7 +107,7 @@ flat_file_upper_limit=200000 request_get_params=c_master,isEmbedded print_footer_in_download=yes ## footer mentioned here appears in downloaded excel -footer_first_line=AT&T Proprietary +footer_first_line=Raptor footer_second_line=Use Pursuant to Company Instructions ## to run report in popup window report_in_popup_window=yes diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties index 0fc2c69d..8f74a9f2 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/conf/system.properties @@ -35,7 +35,7 @@ hb.idle_connection_test_period = 3600 # Ecomp portal title app_display_name = Portal -files_path = /demeter/WebApps/dev/ECOMP_APP/files +files_path = /tmp context_root = ECOMPPORTAL # menu settings menu_query_name = menuData @@ -116,3 +116,6 @@ authenticate_user_server=http://todo_enter_auth_server_hostname:8383/openid-conn #window width threshold to collapse left/right menu when page onload window_width_threshold_left_menu = 1400 window_width_threshold_right_menu = 1350 + +#External system notification URL +external_system_notification_url= http://todo_external_system_notification_url? diff --git a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp index 1b269d80..a8265c71 100644 --- a/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp +++ b/ecomp-portal-BE-os/src/main/webapp/WEB-INF/jsp/login.jsp @@ -37,11 +37,9 @@ - - + +
+ +
+ + +
+ +
+
-
- +
+
+ - -
+ \ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget-parameters.controller.js b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget-parameters.controller.js index fb9a254f..10ccb9bf 100644 --- a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget-parameters.controller.js +++ b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget-parameters.controller.js @@ -21,7 +21,8 @@ (function () { class WidgetParameterController { - constructor($scope, widgetsCatalogService, userProfileService) { + constructor($scope, widgetsCatalogService, userProfileService, $state,items) { + $scope.ngDialogData=items; let widgetId = $scope.ngDialogData.widgetId; $scope.modflag = false; $scope.isLoadingTable = false; @@ -70,12 +71,13 @@ if(res.status == 'OK'){ $scope.modflag = false; $scope.widgetParam[index].showEdit = false; + $state.reload(); } }); }; } } - WidgetParameterController.$inject = ['$scope', 'widgetsCatalogService', 'userProfileService']; + WidgetParameterController.$inject = ['$scope', 'widgetsCatalogService', 'userProfileService', '$state','items']; angular.module('ecompApp').controller('WidgetParameterController', WidgetParameterController); -})(); +})(); \ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget.controller.less b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget.controller.less index 8f326c42..5c0ce37d 100644 --- a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget.controller.less +++ b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard-widget.controller.less @@ -79,4 +79,59 @@ padding-bottom: 20px; height: 32px; border-color: slategrey !important; width:100%; - } \ No newline at end of file + } + .heading1-txt { + margin-top: 10px; + margin-bottom: 10px; + } + .manage-widgets-txt { + margin-top: 25px; + } + .widget-table-control { + margin:30px; + } + .widget-table { + height:300px; + } + .widget-field { + margin-top: 15px; + margin-left: -80px; + } + .widget-add { + font-size:18px; + } + .widget-type-txt-area { + margin-top: 0px; + margin-bottom: 0px; + height: 150px; + } + .widget-button-height { + height:50px; + } + .widget-button { + float:right; + margin-top:20px; + } + .widget-close-button { + float:right; + } + + .btn-calendar-icon { + position: relative; + width: 10px; + right:25px; + top:0px; +} +.dialog-control{ +bottom:30px; +} +input[type="text"]:focus { + z-index: 0; +} + + .get-access-table{ + height:500px; + overflow:auto; + } + + \ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.controller.js b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.controller.js index 8481b5ed..4c5ee2cf 100644 --- a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.controller.js +++ b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.controller.js @@ -54,9 +54,10 @@ function _classCallCheck(instance, Constructor) { $scope.editWidgetModalPopup = function(availableData, resourceType) { $scope.editData = JSON.stringify(availableData); $scope.availableDataTemp = $scope.availableData; - ngDialog.open({ + var modalInstance = $modal.open({ templateUrl: 'app/views/dashboard/dashboard-widget-manage.html', controller: 'CommonWidgetController', + windowClass: 'modal-docked', resolve: { message: function message() { var message = { @@ -66,30 +67,41 @@ function _classCallCheck(instance, Constructor) { return message; } } - }).closePromise.then(needUpdate => { - if (resourceType == 'NEWS') { - $scope.updateNews(); - } else if (resourceType == 'EVENTS') { - $scope.updateEvents(); - } else if (resourceType == 'IMPORTANTRESOURCES') { - $scope.updateImportRes(); - } - }); + }) + + modalInstance.result.finally(function (needUpdate){ + if (resourceType == 'NEWS') { + $scope.updateNews(); + } else if (resourceType == 'EVENTS') { + $scope.updateEvents(); + } else if (resourceType == 'IMPORTANTRESOURCES') { + $scope.updateImportRes(); + } + }); }; $scope.editWidgetParameters = function(widgetId) { let data = { widgetId: widgetId } - ngDialog.open({ + var modalInstance = $modal.open({ templateUrl: 'app/views/dashboard/dashboard-widget-parameter-manage.html', controller: 'WidgetParameterController', - data: data - }).closePromise.then(needUpdate => { + windowClass: 'modal-docked', - }); + resolve: { + items: function () { + return data; + } + } + }) + + modalInstance.result.then(function (needUpdate) { + }); }; + + $scope.sort_options = [{ index: 0, value: 'N', @@ -488,7 +500,8 @@ function _classCallCheck(instance, Constructor) { } - }; + + }; this.auditLog = function(app) { console.log(app); diff --git a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.less b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.less index 8d8f39fe..02cd960d 100644 --- a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.less +++ b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.less @@ -33,7 +33,7 @@ flex-flow: row wrap; width: @table-width; //margin-left: 230px; - margin-bottom: 63px; + margin-bottom: 0px; margin:auto; .app-gridster-header { background-color: @u; @@ -478,10 +478,7 @@ On click the images will be displayed at normal size to complete the effect -webkit-transition: background-color 0.3s ease-out; -moz-transition: background-color 0.3s ease-out; transition: background-color 0.3s ease-out; - span{ - color: #888; } - } .widgetHeaderBtnPosition { width: 30px; @@ -910,4 +907,40 @@ ul { } .icon-content-gridguide{ cursor:move; -} \ No newline at end of file +} + .error-info-txt { + display: none; + font-size: 12px; + margin-left: 5px; + } + .account-info-msg { + color: red; + } + .icon-info { + margin-left: 50%; + font-size: 90px; + color: black; + } + .gridster-box-pointer { + cursor: pointer; + } + .gridster-txt{ + font-size: 12px; + } + .gridster-icon { + font-size: 80px; + color: #067ab4; + } + .widget-gridster { + cursor:move; + } + .widgetHeaderBtns-span { + color: #888; + } + .widgetHeaderBtns-img { + margin-bottom: 3px; + margin-left: 3px; + } + .widget-menu-options { + display: block; + } \ No newline at end of file diff --git a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.tpl.html b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.tpl.html index d71b8f79..a981fd66 100644 --- a/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.tpl.html +++ b/ecomp-portal-FE-common/client/app/views/dashboard/dashboard.tpl.html @@ -19,12 +19,11 @@ -->
-