From b9a6ae1246c02031deb7f5e0d016f242e7d99452 Mon Sep 17 00:00:00 2001 From: Dominic Lunanuova Date: Wed, 7 Feb 2018 22:10:00 +0000 Subject: Refactor to use org.onap local packages This is stage 1 of refactoring to use org.onap instead of org.openecomp in java packages and class names. Leaving the update from openecomp portalsdk to onap epsdk for a future exercise since I'm trying to get a standalone GUI working (i.e. non-portal). Issue-ID: DMAAP-159 Change-Id: I6a9368c66fa3603b1d9984f600802326ff2f0592 Signed-off-by: Dominic Lunanuova --- dcae_dmaapbc_webapp/dbca-common/pom.xml | 6 +- .../dcae/dmaapbc/client/DmaapBcRestClient.java | 1495 ++++++++++++++++++++ .../dcae/dmaapbc/client/HttpStatusAndResponse.java | 66 + .../dcae/dmaapbc/client/IRestClientConstants.java | 34 + .../dcae/dmaapbc/client/SimpleRestClientBase.java | 291 ++++ .../dbcapp/controller/DataBusHomeController.java | 35 + .../dbcapp/controller/DataRouterController.java | 321 +++++ .../controller/DbcappRestrictedBaseController.java | 968 +++++++++++++ .../dbcapp/controller/DmaapAccessController.java | 356 +++++ .../dbcapp/controller/HealthCheckController.java | 142 ++ .../dbcapp/controller/MessageRouterController.java | 207 +++ .../dcae/dmaapbc/dbcapp/domain/DmaapAccess.java | 152 ++ .../dbcapp/domain/ManifestTransportModel.java | 32 + .../dmaapbc/dbcapp/rest/DbcUsvcRestClient.java | 182 +++ .../dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java | 42 + ...omponentsClientHttpRequestFactoryBasicAuth.java | 46 + .../dmaapbc/dbcapp/service/DmaapAccessService.java | 63 + .../dbcapp/service/DmaapAccessServiceImpl.java | 97 ++ .../dcae/dmaapbc/dbcapp/util/DbcappProperties.java | 71 + .../java/org/onap/dcae/dmaapbc/model/DR_Node.java | 87 ++ .../java/org/onap/dcae/dmaapbc/model/DR_Pub.java | 96 ++ .../java/org/onap/dcae/dmaapbc/model/DR_Sub.java | 152 ++ .../org/onap/dcae/dmaapbc/model/DcaeLocation.java | 96 ++ .../java/org/onap/dcae/dmaapbc/model/Dmaap.java | 141 ++ .../org/onap/dcae/dmaapbc/model/DmaapObject.java | 70 + .../org/onap/dcae/dmaapbc/model/ErrorResponse.java | 65 + .../java/org/onap/dcae/dmaapbc/model/Feed.java | 193 +++ .../org/onap/dcae/dmaapbc/model/MR_Client.java | 110 ++ .../org/onap/dcae/dmaapbc/model/MR_Cluster.java | 108 ++ .../java/org/onap/dcae/dmaapbc/model/Topic.java | 144 ++ .../main/java/org/onap/fusionapp/model/Result.java | 18 + .../onap/fusionapp/service/AdminAuthExtension.java | 13 + .../onap/fusionapp/util/CustomLoggingFilter.java | 37 + .../dcae/dmaapbc/client/DmaapBcRestClient.java | 1495 -------------------- .../dcae/dmaapbc/client/HttpStatusAndResponse.java | 66 - .../dcae/dmaapbc/client/IRestClientConstants.java | 34 - .../dcae/dmaapbc/client/SimpleRestClientBase.java | 291 ---- .../dbcapp/controller/DataBusHomeController.java | 35 - .../dbcapp/controller/DataRouterController.java | 321 ----- .../controller/DbcappRestrictedBaseController.java | 968 ------------- .../dbcapp/controller/DmaapAccessController.java | 356 ----- .../dbcapp/controller/HealthCheckController.java | 142 -- .../dbcapp/controller/MessageRouterController.java | 207 --- .../dcae/dmaapbc/dbcapp/domain/DmaapAccess.java | 152 -- .../dbcapp/domain/ManifestTransportModel.java | 32 - .../dmaapbc/dbcapp/rest/DbcUsvcRestClient.java | 182 --- .../dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java | 42 - ...omponentsClientHttpRequestFactoryBasicAuth.java | 46 - .../dmaapbc/dbcapp/service/DmaapAccessService.java | 63 - .../dbcapp/service/DmaapAccessServiceImpl.java | 97 -- .../dcae/dmaapbc/dbcapp/util/DbcappProperties.java | 71 - .../org/openecomp/dcae/dmaapbc/model/DR_Node.java | 87 -- .../org/openecomp/dcae/dmaapbc/model/DR_Pub.java | 96 -- .../org/openecomp/dcae/dmaapbc/model/DR_Sub.java | 152 -- .../openecomp/dcae/dmaapbc/model/DcaeLocation.java | 96 -- .../org/openecomp/dcae/dmaapbc/model/Dmaap.java | 141 -- .../openecomp/dcae/dmaapbc/model/DmaapObject.java | 70 - .../dcae/dmaapbc/model/ErrorResponse.java | 65 - .../org/openecomp/dcae/dmaapbc/model/Feed.java | 193 --- .../openecomp/dcae/dmaapbc/model/MR_Client.java | 110 -- .../openecomp/dcae/dmaapbc/model/MR_Cluster.java | 108 -- .../org/openecomp/dcae/dmaapbc/model/Topic.java | 144 -- .../java/org/openecomp/fusionapp/model/Result.java | 18 - .../fusionapp/service/AdminAuthExtension.java | 13 - .../fusionapp/util/CustomLoggingFilter.java | 37 - .../onap/dcae/dmaapbc/model/DcaeLocationTest.java | 46 + .../core/MockApplicationContextTestSuite.java | 116 ++ .../test/java/org/onap/fusionapp/SanityTest.java | 20 + .../onap/fusionapp/service/ProfileServiceTest.java | 37 + .../dcae/dmaapbc/model/DcaeLocationTest.java | 46 - .../core/MockApplicationContextTestSuite.java | 116 -- .../java/org/openecomp/fusionapp/SanityTest.java | 20 - .../fusionapp/service/ProfileServiceTest.java | 37 - .../dbca-os/db-scripts/dbca-dml-mysql-1707-os.sql | 2 +- dcae_dmaapbc_webapp/dbca-os/pom.xml | 14 +- .../org/onap/portalapp/conf/ExternalAppConfig.java | 171 +++ .../portalapp/conf/ExternalAppInitializer.java | 47 + .../portalapp/conf/HibernateMappingLocations.java | 60 + .../portalapp/lm/FusionLicenseManagerImpl.java | 81 ++ .../onap/portalapp/login/LoginStrategyImpl.java | 111 ++ .../java/org/onap/service/AdminAuthExtension.java | 65 + .../portalapp/conf/ExternalAppConfig.java | 171 --- .../portalapp/conf/ExternalAppInitializer.java | 47 - .../portalapp/conf/HibernateMappingLocations.java | 60 - .../portalapp/lm/FusionLicenseManagerImpl.java | 81 -- .../portalapp/login/LoginStrategyImpl.java | 111 -- .../portalapp/service/AdminAuthExtension.java | 64 - .../dbca-os/src/main/resources/logback.xml | 2 +- dcae_dmaapbc_webapp/dbca-overlay/pom.xml | 4 +- .../src/main/webapp/WEB-INF/dbcapp/dbcapp.hbm.xml | 2 +- dcae_dmaapbc_webapp/pom.xml | 4 +- pom.xml | 4 +- 92 files changed, 6703 insertions(+), 6702 deletions(-) create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/DmaapBcRestClient.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/HttpStatusAndResponse.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/IRestClientConstants.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/SimpleRestClientBase.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataRouterController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/util/DbcappProperties.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Node.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Pub.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Sub.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DcaeLocation.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Dmaap.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DmaapObject.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/ErrorResponse.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Feed.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Client.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Cluster.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Topic.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/model/Result.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/DmaapBcRestClient.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/HttpStatusAndResponse.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/IRestClientConstants.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/SimpleRestClientBase.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataRouterController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/util/DbcappProperties.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Node.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Pub.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Sub.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DcaeLocation.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Dmaap.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DmaapObject.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/ErrorResponse.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Feed.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Client.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Cluster.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Topic.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/model/Result.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/service/AdminAuthExtension.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/util/CustomLoggingFilter.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/dcae/dmaapbc/model/DcaeLocationTest.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/SanityTest.java create mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/dcae/dmaapbc/model/DcaeLocationTest.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/SanityTest.java delete mode 100644 dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/service/ProfileServiceTest.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java create mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/service/AdminAuthExtension.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java delete mode 100644 dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java diff --git a/dcae_dmaapbc_webapp/dbca-common/pom.xml b/dcae_dmaapbc_webapp/dbca-common/pom.xml index b036b2a..8a65d5d 100644 --- a/dcae_dmaapbc_webapp/dbca-common/pom.xml +++ b/dcae_dmaapbc_webapp/dbca-common/pom.xml @@ -3,9 +3,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.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-common - 1.1.0-SNAPSHOT + 1.2.0-SNAPSHOT jar DCAE DMaaP Bus Controller Webapp Common Java Files Code for the DCAE DMaaP Bus Controller GUI @@ -15,7 +15,7 @@ 4.2.0.RELEASE 4.3.11.Final 1.1.0 - 1.1.0-SNAPSHOT + 1.2.0-SNAPSHOT true https://nexus.onap.org /content/repositories/snapshots/ diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/DmaapBcRestClient.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/DmaapBcRestClient.java new file mode 100644 index 0000000..5aafa74 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/DmaapBcRestClient.java @@ -0,0 +1,1495 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller REST Client + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.client; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.apache.http.client.utils.URIBuilder; +import org.onap.dcae.dmaapbc.model.DR_Node; +import org.onap.dcae.dmaapbc.model.DR_Pub; +import org.onap.dcae.dmaapbc.model.DR_Sub; +import org.onap.dcae.dmaapbc.model.DcaeLocation; +import org.onap.dcae.dmaapbc.model.Dmaap; +import org.onap.dcae.dmaapbc.model.DmaapObject; +import org.onap.dcae.dmaapbc.model.ErrorResponse; +import org.onap.dcae.dmaapbc.model.Feed; +import org.onap.dcae.dmaapbc.model.MR_Client; +import org.onap.dcae.dmaapbc.model.MR_Cluster; +import org.onap.dcae.dmaapbc.model.Topic; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Provides methods to communicate with the DMaaP Bus Controller REST API. This + * hides all JSON; instead it accepts and returns Java objects. + */ +public class DmaapBcRestClient extends SimpleRestClientBase { + + private static Logger logger = LoggerFactory.getLogger(DmaapBcRestClient.class); + + // Omit leading and trailing slashes here + private static final String DCAELOCATIONS = "dcaeLocations"; + private static final String DMAAP = "dmaap"; + private static final String DR_NODES = "dr_nodes"; + private static final String DR_PUBS = "dr_pubs"; + private static final String DR_SUBS = "dr_subs"; + private static final String FEEDS = "feeds"; + private static final String TOPICS = "topics"; + private static final String MR_CLUSTERS = "mr_clusters"; + private static final String MR_CLIENTS = "mr_clients"; + + /** + * Reusable JSON (de)serializer + */ + private final ObjectMapper mapper; + + /** + * URL of the DMAAP REST endpoint + */ + private final String dmaapRestUrl; + + /** + * Constructor that configures the client for the specified endpoint using + * no authentication. + * + * @param dmaapRestUrl + * URL of the endpoint + */ + public DmaapBcRestClient(final String dmaapRestUrl) { + super(); + this.dmaapRestUrl = dmaapRestUrl; + this.mapper = new ObjectMapper(); + // Don't serialize null-value fields in objects + this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + /** + * Constructor that onfigures the client for the specified endpoint using + * the specified username and password for basic HTTP authentication. + * + * @param dmaapRestUrl + * URL of the endpoint + * @param username + * User name + * @param password + * Password + */ + public DmaapBcRestClient(final String dmaapRestUrl, final String username, final String password) { + super(username, password); + this.dmaapRestUrl = dmaapRestUrl; + this.mapper = new ObjectMapper(); + // Don't serialize null-value fields in objects + this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + /** + * Configures the behavior of the JSON deserializer used to build business + * objects (e.g., a Feed) from REST responses. + * + * @param failOnUnknownProperties + * If true, rejects JSON responses with unexpected fields + * (default behavior); if false, ignores unexpected fields. + */ + public void setFailOnUnknownProperties(boolean failOnUnknownProperties) { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); + } + + /** + * Gets the DMaaP endpoint URL that is used by methods in this class. + * + * @return dmaapEndpointUrl + */ + public String getDmaapRestUrl() { + return this.dmaapRestUrl; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of DCAE locations. + * + * @return List of DmaapObject: list contains DcaeLocation object(s) on + * success; a single ErrorResponse object if the remote site rejects + * the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getDcaeLocations() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DCAELOCATIONS)); + logger.debug("getDcaeLocations: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDcaeLocations: unexpected null response"); + + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getDcaeLocations: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets the DCAE location with the specified name. + * + * @param locName + * name of the location to get + * @return DmaapObject: a DcaeLocation object on success; an ErrorResponse + * object if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getDcaeLocation(final String locName) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DCAELOCATIONS, locName)); + logger.debug("getDcaeLocation: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDcaeLocation: unexpected null response"); + + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); + } catch (Exception ex) { + logger.debug("getDcaeLocation: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a DCAE location in DMaaP. + * + * @param dcaeLoc + * DcaeLocation to be created + * @return Status and response: expect 200 and a DcaeLocation on success; a + * code and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postDcaeLocation(DcaeLocation dcaeLoc) throws Exception { + String jsonBody = mapper.writeValueAsString(dcaeLoc); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DCAELOCATIONS), jsonBody); + if (hsr == null) + throw new Exception("postDcaeLocation: unexpected null response"); + logger.debug("postDcaeLocation: resp is {}", hsr); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postDcaeLocation: null response body"); + return response; + } + try { + DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDcaeLocation: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the DCAE location with the specified name. + * + * @param locName + * Name of the location to delete + * @return Status and response: expect 204 and a DcaeLocation on success; a + * code and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteDcaeLocation(final String locName) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DCAELOCATIONS, locName)); + logger.debug("deleteDcaeLocation: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteDcaeLocation: unexpected null response"); + // Returns a loc on success, error message string on error. + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteDcaeLocation: null response body"); + return response; + } + try { + DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteDcaeLocation: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a DCAE location. + * + * @param dcaeLoc + * DCAE Location to be updated + * @return Status and response; expect 200 and a DcaeLocation on success, a + * string error on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putDcaeLocation(DcaeLocation dcaeLoc) throws Exception { + String jsonBody = mapper.writeValueAsString(dcaeLoc); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DCAELOCATIONS, dcaeLoc.getDcaeLocationName()), + jsonBody); + logger.debug("putDcaeLocation: resp is {}", hsr); + if (hsr == null) + throw new Exception("putDcaeLocation: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putDcaeLocation: null response body"); + return response; + } + try { + DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putDcaeLocation: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets the DMAAP instance for this DCAE deployment. + * + * @return DmaapObject: a Dmaap object on success; an ErrorResponse object + * if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getDmaap() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DMAAP)); + logger.debug("getDmaap: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDmaap: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), Dmaap.class); + } catch (Exception ex) { + logger.debug("getDmaap: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a new DMaaP set system wide configuration settings for the + * dcaeEnvironment + * + * @param dmaap + * Dmaap properties + * @return Status and response: expect 200 and a Dmaap on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postDmaap(Dmaap dmaap) throws Exception { + String jsonBody = mapper.writeValueAsString(dmaap); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DMAAP), jsonBody); + if (hsr == null) + throw new Exception("postDmaap: unexpected null response"); + logger.debug("postDmaap: resp is {}", hsr); + // Returns ? on success, error message string on error. + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postDmaap: null response body"); + return response; + } + try { + Dmaap resp = mapper.readValue(hsr.getResponseString(), Dmaap.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDmaap: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates DMaaP system wide configuration settings for the dcaeEnvironment. + * + * @param dmaap + * Dmaap properties + * @return Status and response; expect 200 and a DR_Pub on success; a code + * and and ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putDmaap(Dmaap dmaap) throws Exception { + String jsonBody = mapper.writeValueAsString(dmaap); + // Oddly, this PUT has no ID parameter in the URL + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DMAAP), jsonBody); + if (hsr == null) + throw new Exception("putDmaap: unexpected null response"); + logger.debug("putDmaap: resp is {}", hsr); + // Returns ? on success, error message string on error. + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putDmaap: null response body"); + return response; + } + try { + Dmaap resp = mapper.readValue(hsr.getResponseString(), Dmaap.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putDmaap: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + // NO DELETE_DMAAP METHOD + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of data router nodes. + * + * @return List of DmaapObject: list contains DR_Node object(s) on success; + * a single ErrorResponse object if the remote site rejects the + * request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getDRNodes() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_NODES)); + logger.debug("getDRNodes: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRNodes: unexpected null response"); + + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getDRNodes: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets a data router node with the specified ID. + * + * @param fqdn + * Name of the node to get + * @return DmaapObject: a DR_Node object on success; an ErrorResponse object + * if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getDRNode(final String fqdn) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_NODES, fqdn)); + logger.debug("getDRNode: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRNode: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), DR_Node.class); + } catch (Exception ex) { + logger.debug("getDRNode: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a data router node. + * + * @param drNode + * Node to be created + * @return Status and response: expect 200 and a DR_Node on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postDRNode(DR_Node drNode) throws Exception { + String jsonBody = mapper.writeValueAsString(drNode); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_NODES), jsonBody); + logger.debug("postDRNode: resp is {}", hsr); + if (hsr == null) + throw new Exception("postDRNode: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postDRNode: null response body"); + return response; + } + try { + DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDRNode: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a data router node. + * + * @param drNode + * Node to be updated + * @return Status and response: expect 200 and a DR_Node on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putDRNode(DR_Node drNode) throws Exception { + String jsonBody = mapper.writeValueAsString(drNode); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_NODES, drNode.getFqdn()), jsonBody); + logger.debug("putDRNode: resp is {}", hsr); + if (hsr == null) + throw new Exception("putDRNode: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putDRNode: null response body"); + return response; + } + try { + DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDRNode: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the data router node with the specified FQDN. + * + * @param fqdn + * Name of the node to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteDRNode(final String fqdn) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_NODES, fqdn)); + logger.debug("deleteDRNode: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteDRNode: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteDRNode: null response body"); + return response; + } + try { + DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteDRNode: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of data router publishers. + * + * @return List of DmaapObject: list contains DR_Pub object(s) on success; a + * single ErrorResponse object if the remote site rejects the + * request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getDRPubs() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_PUBS)); + logger.debug("getDRPubs: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRPubs: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getDRPubs: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets a data router publisher with the specified ID. + * + * @param pubId + * ID of the publisher to get + * @return DmaapObject: a DR_Pub object on success; an ErrorResponse object + * if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getDRPub(final String pubId) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_PUBS, pubId)); + logger.debug("getDRPub: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRPub: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), DR_Pub.class); + } catch (Exception ex) { + logger.debug("getDRPub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a data router publisher. + * + * @param drPub + * Data router publisher properties + * @return Status and response: expect 200 and a DR_Pub on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postDRPub(DR_Pub drPub) throws Exception { + String jsonBody = mapper.writeValueAsString(drPub); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_PUBS), jsonBody); + logger.debug("postDRPub: resp is {}", hsr); + if (hsr == null) + throw new Exception("postDRPub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postDRPub: null response body"); + return response; + } + try { + DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDRPub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a data router publisher. + * + * @param drPub + * Publisher to be updated + * @return Status and response: expect 200 and a DR_Pub on success, a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putDRPub(DR_Pub drPub) throws Exception { + String jsonBody = mapper.writeValueAsString(drPub); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_PUBS, drPub.getPubId()), jsonBody); + logger.debug("putDRPub: resp is {}", hsr); + if (hsr == null) + throw new Exception("putDRPub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putDRPub: null response body"); + return response; + } + try { + DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDRPub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the data router publisher with the specified ID. + * + * @param pubId + * ID of the publisher to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteDRPub(final String pubId) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_PUBS, pubId)); + logger.debug("deleteDRPub: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteDRPub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteDRPub: null response body"); + return response; + } + try { + DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteDRPub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of data router subscribers. + * + * @return List of DmaapObject: list contains DR_Sub object(s) on success; a + * single ErrorResponse object if the remote site rejects the + * request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getDRSubs() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_SUBS)); + logger.debug("getDRSubs: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRSubs: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getDRSubs: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets a data router subscriber with the specified ID. + * + * @param subId + * ID of the subscriber to get + * @return DmaapObject: a DR_Sub object on success; an ErrorResponse object + * if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getDRSub(final String subId) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_SUBS, subId)); + logger.debug("getDRPub: resp is {}", hsr); + if (hsr == null) + throw new Exception("getDRSub: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), DR_Sub.class); + } catch (Exception ex) { + logger.debug("getDRSub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a data router subscriber. + * + * @param drSub + * Data router subscriber properties + * @return Status and response: expect 200 and a DR_Sub on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postDRSub(DR_Sub drSub) throws Exception { + String jsonBody = mapper.writeValueAsString(drSub); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_SUBS), jsonBody); + logger.debug("postDRSub: resp is {}", hsr); + if (hsr == null) + throw new Exception("postDRSub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postDRSub: null response body"); + return response; + } + try { + DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postDRSub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a data router subscriber. + * + * @param drSub + * Subscriber to be updated + * @return Status and response; expect 200 and a DR_Sub on success, a string + * error on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putDRSub(DR_Sub drSub) throws Exception { + String jsonBody = mapper.writeValueAsString(drSub); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_SUBS, drSub.getSubId()), jsonBody); + logger.debug("putDRSub: resp is {}", hsr); + if (hsr == null) + throw new Exception("putDRSub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putDRSub: null response body"); + return response; + } + try { + DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putDRSub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the data router subscriber with the specified ID. + * + * @param subId + * ID of the subscriber to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteDRSub(final String subId) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_SUBS, subId)); + logger.debug("deleteDRSub: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteDRSub: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteDRSub: null response body"); + return response; + } + try { + DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteDRSub: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of data router feeds. + * + * @return List of DmaapObject: list contains DcaeLocation object(s) on + * success; a single ErrorResponse object if the remote site rejects + * the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getFeeds() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(FEEDS)); + logger.debug("getFeeds: resp is {}", hsr); + if (hsr == null) + throw new Exception("getFeeds: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getFeeds: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets a data router feed with the specified ID. + * + * @param feedId + * ID of the feed to get + * @return DmaapObject: a Feed object on success; an ErrorResponse object if + * the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getFeed(final String feedId) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(FEEDS, feedId)); + logger.debug("getFeed: resp is {}", hsr); + if (hsr == null) + throw new Exception("getFeed: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), Feed.class); + } catch (Exception ex) { + logger.debug("getFeed: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a feed and adds any specified pubs and subs. + * + * @param feed + * Data router feed properties + * @return Status and response: expect 200 and a Feed on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postFeed(Feed feed) throws Exception { + String jsonBody = mapper.writeValueAsString(feed); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(FEEDS), jsonBody); + logger.debug("postFeed: resp is {}", hsr); + if (hsr == null) + throw new Exception("postFeed: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postFeed: null response body"); + return response; + } + try { + Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postFeed: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a data router feed. + * + * @param feed + * Feed to be updated + * @return Status and response: expect 200 and a Feed on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putFeed(Feed feed) throws Exception { + String jsonBody = mapper.writeValueAsString(feed); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(FEEDS, feed.getFeedId()), jsonBody); + logger.debug("putFeed: resp is {}", hsr); + if (hsr == null) + throw new Exception("putFeed: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putFeed: null response body"); + return response; + } + try { + Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putFeed: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the data router feed with the specified ID. + * + * @param feedId + * ID of the feed to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteFeed(final String feedId) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(FEEDS, feedId)); + logger.debug("deleteFeed: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteFeed: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteFeed: null response body"); + return response; + } + try { + Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteFeed: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of message router topics. + * + * @return List of DmaapObject: list contains Topic object(s) on success; a + * single ErrorResponse object if the remote site rejects the + * request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getTopics() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(TOPICS)); + logger.debug("getTopics: resp is {}", hsr); + if (hsr == null) + throw new Exception("getTopics: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getTopics: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets the message router topic with the specified FQTN. + * + * @param fqtn + * Fully qualified topic name + * @return DmaapObject: a Topic object on success; an ErrorResponse object + * if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getTopic(final String fqtn) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(TOPICS, fqtn)); + logger.debug("getTopic: resp is {}", hsr); + if (hsr == null) + throw new Exception("getTopic: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), Topic.class); + } catch (Exception ex) { + logger.debug("getTopic: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a topic and grants appropriate permissions to specified pubs and + * subs. + * + * @param topic + * Message router topic properties + * @return Status and response: expect 200 and a Topic on success; a code + * and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postTopic(Topic topic) throws Exception { + String jsonBody = mapper.writeValueAsString(topic); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(TOPICS), jsonBody); + logger.debug("postTopic: resp is {}", hsr); + if (hsr == null) + throw new Exception("postTopic: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postTopic: null response body"); + return response; + } + try { + Topic resp = mapper.readValue(hsr.getResponseString(), Topic.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postTopic: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the message router topic with the specified FQTN. + * + * @param fqtn + * Fully qualified topic name to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteTopic(final String fqtn) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(TOPICS, fqtn)); + logger.debug("deleteTopic: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteTopic: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteTopic: null response body"); + return response; + } + try { + Topic resp = mapper.readValue(hsr.getResponseString(), Topic.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteTopic: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of message router clients. + * + * @return List of DmaapObject: list contains MR_Client object(s) on + * success; a single ErrorResponse object if the remote site rejects + * the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getMRClients() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLIENTS)); + logger.debug("getMRClients: resp is {}", hsr); + if (hsr == null) + throw new Exception("getMRClients: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getMRClients: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets the message router client with the specified ID. + * + * @param mrClientId + * ID of the client to get + * @return DmaapObject: a MR_Client object on success; an ErrorResponse + * object if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getMRClient(final String mrClientId) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLIENTS, mrClientId)); + logger.debug("getMRClient: resp is {}", hsr); + if (hsr == null) + throw new Exception("getMRClient: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), MR_Client.class); + } catch (Exception ex) { + logger.debug("getMRClient: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a message router client. + * + * @param mrClient + * Message router client properties + * @return Status and response: expect 200 and a MR_Client on success; a + * code and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postMRClient(MR_Client mrClient) throws Exception { + String jsonBody = mapper.writeValueAsString(mrClient); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(MR_CLIENTS), jsonBody); + logger.debug("postMRClient: resp is {}", hsr); + if (hsr == null) + throw new Exception("postMRClient: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postMRClient: null response body"); + return response; + } + try { + MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postMRClient: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a message router client. + * + * @param mrClient + * client to be updated + * @return Status and response; expect 200 and a MR_Client on success, a + * string error on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putMRClient(MR_Client mrClient) throws Exception { + String jsonBody = mapper.writeValueAsString(mrClient); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(MR_CLIENTS, mrClient.getMrClientId()), + jsonBody); + logger.debug("putMRClient: resp is {}", hsr); + if (hsr == null) + throw new Exception("putMRClient: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putMRClient: null response body"); + return response; + } + try { + MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putMRClient: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the message router client with the specified ID. + * + * @param mrClientId + * ID of the client to delete + * @return Status and response; expect 204 and a null on success, a string + * error on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteMRClient(final String mrClientId) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(MR_CLIENTS, mrClientId)); + logger.debug("deleteMRClient: resp is {}", hsr); + if (hsr == null) + throw new Exception("deleteMRClient: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteMRClient: null response body"); + return response; + } + try { + MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteMRClient: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Gets a list of message router clusters. + * + * @return List of DmaapObject: list contains MR_Cluster object(s) on + * success; a single ErrorResponse object if the remote site rejects + * the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public List getMRClusters() throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLUSTERS)); + logger.debug("getMRClusters: resp is {}", hsr); + if (hsr == null) + throw new Exception("getMRClusters: unexpected null response"); + List responseList = null; + try { + TypeReference> typeRef = new TypeReference>() { + }; + responseList = mapper.readValue(hsr.getResponseString(), typeRef); + } catch (Exception ex) { + logger.debug("getDcaeLocations: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + responseList = new ArrayList(); + responseList.add(errResp); + } + return responseList; + } + + /** + * Gets the message router cluster with the specified location name. + * + * @param dcaeLocName + * name of the cluster to get + * @return DmaapObject: a MR_Cluster object on success; an ErrorResponse + * object if the remote site rejects the request. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public DmaapObject getMRCluster(final String dcaeLocName) throws Exception { + HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLUSTERS, dcaeLocName)); + logger.debug("getMRCluster: resp is {}", hsr); + if (hsr == null) + throw new Exception("getMRCluster: unexpected null response"); + DmaapObject response = null; + try { + response = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); + } catch (Exception ex) { + logger.debug("getMRCluster: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + } + return response; + } + + /** + * Creates a message router cluster. + * + * @param mrCluster + * Message router cluster properties + * @return Status and response: expect 200 and a MR_Cluster on success; a + * code and an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse postMRCluster(MR_Cluster mrCluster) throws Exception { + String jsonBody = mapper.writeValueAsString(mrCluster); + HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(MR_CLUSTERS), jsonBody); + logger.debug("postMRCluster: resp is {}", hsr); + if (hsr == null) + throw new Exception("postMRCluster: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("postMRCluster: null response body"); + return response; + } + try { + MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("postMRCluster: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Updates a message router cluster. + * + * @param mrCluster + * cluster to be updated + * @return Status and response; expect 200 and a MR_Cluster on success, a + * string error on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse putMRCluster(MR_Cluster mrCluster) throws Exception { + String jsonBody = mapper.writeValueAsString(mrCluster); + HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(MR_CLUSTERS, mrCluster.getDcaeLocationName()), + jsonBody); + logger.debug("putMRCluster: resp is {}", hsr); + if (hsr == null) + throw new Exception("putMRCluster: unexpected null response"); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("putMRCluster: null response body"); + return response; + } + try { + MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("putMRCluster: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + /** + * Deletes the message router cluster with the specified location name. + * + * @param dcaeLocName + * Location name of the cluster to delete + * @return Status and response: expect 204 and a null on success; a code and + * an ErrorResponse on failure. + * @throws Exception + * if host cannot be reached, response cannot be parsed, etc. + */ + public HttpStatusAndResponse deleteMRCluster(final String dcaeLocName) throws Exception { + HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(MR_CLUSTERS, dcaeLocName)); + if (hsr == null) + throw new Exception("deleteMRCluster: unexpected null response"); + logger.debug("deleteMRCluster: resp is {}", hsr); + HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); + if (hsr.getResponse() == null) { + logger.debug("deleteMRCluster: null response body"); + return response; + } + try { + MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); + response.setResponse(resp); + } catch (Exception ex) { + logger.debug("deleteMRCluster: trying to parse response as error: {}", ex.toString()); + // If this parse fails, let the exception be thrown + ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); + response.setResponse(errResp); + } + return response; + } + + ///////////////////////////////////////////////////////////////////// + + /** + * Builds the URI for the DMaaP REST endpoint using configuration and the + * specified task and path parameter(s). Deals with extra or missing slashes + * to allow for some flexibility in the config file. + * + * @param requestPath + * Last part of endpoint path + * @param pathParam + * Additional path parameters in order; ignored if null or empty + * @return REST endpoint URI + * @throws Exception + * if the RESAT URL property is not found + */ + private URI buildDmaapUri(String task, String... pathParam) throws Exception { + if (dmaapRestUrl == null || dmaapRestUrl.length() == 0) + throw new Exception("buildUrlPath: unconfigured, must set dmaapEndpointUrl"); + StringBuilder sb = new StringBuilder(); + // Clean the base of any trailing slashes + sb.append(trimSlashes(dmaapRestUrl)); + sb.append('/'); + // task is controlled in this file, don't clean it. + sb.append(task); + if (pathParam != null) { + for (String pp : pathParam) { + sb.append('/'); + // path comes from the user, definitely clean it. + sb.append(trimSlashes(pp)); + } + } + String urlPath = sb.toString(); + URIBuilder uriBuilder = new URIBuilder(urlPath); + return uriBuilder.build(); + } + + /** + * Strips the specified string of leading and trailing forward-slash + * characters. + * + * @param s + * String to trim + * @return String without any leading or trailing '/' characters. + */ + private String trimSlashes(String s) { + while (s.length() > 0 && s.charAt(0) == '/') + s = s.substring(1, s.length()); + while (s.length() > 0 && s.charAt(s.length() - 1) == '/') + s = s.substring(0, s.length() - 1); + return s; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/HttpStatusAndResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/HttpStatusAndResponse.java new file mode 100644 index 0000000..50faafd --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/HttpStatusAndResponse.java @@ -0,0 +1,66 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller REST Client + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.client; + +/** + * Holds the status code and body that result from accessing an HTTP URL. + */ +public class HttpStatusAndResponse { + + private int statusCode; + private ResponseType response; + + public HttpStatusAndResponse(int status, ResponseType resp) { + this.statusCode = status; + this.response = resp; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(final int code) { + this.statusCode = code; + } + + public ResponseType getResponse() { + return response; + } + + public void setResponse(ResponseType response) { + this.response = response; + } + + /** + * Convenience method to avoid testing for null and calling .toString() + * + * @return String version of the response object; null if the object is + * null. + */ + public String getResponseString() { + return response == null ? null : response.toString(); + } + + @Override + public String toString() { + return "HttpStatusAndResponse[" + Integer.toString(statusCode) + ";" + + (response == null ? "" : response.toString()) + "]"; + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/IRestClientConstants.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/IRestClientConstants.java new file mode 100644 index 0000000..1cf0c96 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/IRestClientConstants.java @@ -0,0 +1,34 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller REST Client + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.client; + +public interface IRestClientConstants { + + /** + * Default configuration file to be found on classpath + */ + public static final String PROPERTY_FILE_NAME = "bc-rest-client.properties"; + + /** + * Base URL of the Bus Controller REST service API + */ + public static final String DMAAP_BUS_CONTROLLER_REST_URL = "dmaap_bus_controller_rest_url"; + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/SimpleRestClientBase.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/SimpleRestClientBase.java new file mode 100644 index 0000000..3fc6474 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/client/SimpleRestClientBase.java @@ -0,0 +1,291 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller REST Client + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.client; + +import java.io.IOException; +import java.net.URI; + +import org.apache.http.Consts; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.AuthCache; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.config.RequestConfig.Builder; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provides a basic client to access a REST endpoint, optionally using HTTP + * basic authentication. + * + * Caveat: If HTTPS access is used and the server uses a self-signed + * certificate, the local trust store must be extended appropriately. The client + * throws exceptions if the JVM cannot validate the server certificate. + */ +public class SimpleRestClientBase { + + private static Logger logger = LoggerFactory.getLogger(SimpleRestClientBase.class); + + /** + * Credentials for HTTP basic authentication (optional). + */ + private final String username; + private final String password; + + /** + * Timeouts (optional) + */ + private Integer connectTimeoutMs = null; + private Integer connectionRequestTimeoutMs = null; + private Integer socketTimeoutMs = null; + + /** + * Constructs a client that does not use any authentication and uses Apache + * HTTPD client default values for timeouts. + */ + public SimpleRestClientBase() { + this(null, null, null, null, null); + } + + /** + * Convenience constructor to build a client that uses the specified + * username and password for basic HTTP authentication on all requests. In + * other words, this client pre-emptively sends the "Basic" header instead + * of first trying the request without, failing, negotiating, then sending + * with credentials. + * + * @param username + * User name for basic HTTP authentication. + * @param password + * Password for basic HTTP authentication. + */ + public SimpleRestClientBase(final String username, final String password) { + this(username, password, null, null, null); + } + + /** + * Convenience constructor to build a client that uses the specified + * timeouts on all requests. + * + * @param connectTimeoutMs + * Connection timeout, in milliseconds + * @param connectionRequestTimeoutMs + * Connection request timeout, in milliseconds + * @param socketTimeoutMs + * Socket timeout, in milliseconds + */ + public SimpleRestClientBase(final Integer connectTimeoutMs, final Integer connectionRequestTimeoutMs, + final Integer socketTimeoutMs) { + this(null, null, connectTimeoutMs, connectionRequestTimeoutMs, socketTimeoutMs); + } + + /** + * Constructs a client with the specified credentials and timeout values. + * + * @param username + * User name for basic HTTP authentication; ignored if null + * @param password + * Password for basic HTTP authentication; ignored if null + * @param connectTimeoutMs + * ignored if null + * @param connectionRequestTimeoutMs + * ignored if null + * @param socketTimeoutMs + * ignored if null + */ + public SimpleRestClientBase(final String username, final String password, final Integer connectTimeoutMs, + final Integer connectionRequestTimeoutMs, final Integer socketTimeoutMs) { + this.username = username; + this.password = password; + this.connectTimeoutMs = null; + this.connectionRequestTimeoutMs = null; + this.socketTimeoutMs = null; + } + + /** + * Constructs and sends a GET request for the URI. + * + * @param uri + * REST endpoint + * @return Result of the get + * @throws Exception + * On any error + */ + public HttpStatusAndResponse getRestContent(final URI uri) throws Exception { + HttpGet httpGet = new HttpGet(uri); + return doRestRequest(httpGet); + } + + /** + * Constructs and sends a POST request using the specified body. + * + * @param uri + * REST endpoint + * @param json + * Content to post + * @return Result of the post; null if an error happens + * @throws Exception + * On any error + */ + public HttpStatusAndResponse postRestContent(final URI uri, final String json) throws Exception { + HttpPost httpPost = new HttpPost(uri); + StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); + httpPost.setEntity(postEntity); + return doRestRequest(httpPost); + } + + /** + * Constructs and sends a PUT request using the specified body. + * + * @param uri + * REST endpoint + * @param json + * Content to put + * @return Result of the put; null if an error happens + * @throws Exception + * On any error + */ + public HttpStatusAndResponse putRestContent(final URI uri, final String json) throws Exception { + HttpPut httpPut = new HttpPut(uri); + StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); + httpPut.setEntity(postEntity); + return doRestRequest(httpPut); + } + + /** + * Constructs and sends a DELETE request for the URI. + * + * @param uri + * REST endpoint + * @return Result of the get + * @throws Exception + * On any error + */ + public HttpStatusAndResponse deleteRestContent(final URI uri) throws Exception { + HttpDelete httpDel = new HttpDelete(uri); + return doRestRequest(httpDel); + } + + /** + * Executes the specified request and gathers the response. + * + * @param request + * HttpGet, HttpPost, etc. + * @return Status code and response body + * @throws ClientProtocolException + * On HTTP protocol error + * @throws IOException + * On read/write error + */ + private HttpStatusAndResponse doRestRequest(final HttpRequestBase request) + throws ClientProtocolException, IOException { + + // Set up authentication if needed + final HttpClientContext context = HttpClientContext.create(); + if (this.username != null || this.password != null) { + UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, credentials); + context.setCredentialsProvider(credentialsProvider); + + HttpHost host = new HttpHost(request.getURI().getHost(), request.getURI().getPort(), + request.getURI().getScheme()); + AuthCache authCache = new BasicAuthCache(); + authCache.put(host, new BasicScheme()); + context.setAuthCache(authCache); + } + final Builder requestConfigBuilder = RequestConfig.custom(); + if (connectionRequestTimeoutMs != null) + requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeoutMs); + if (connectTimeoutMs != null) + requestConfigBuilder.setConnectTimeout(connectTimeoutMs); + if (socketTimeoutMs != null) + requestConfigBuilder.setSocketTimeout(socketTimeoutMs); + RequestConfig requestConfig = requestConfigBuilder.build(); + final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); + CloseableHttpResponse response = null; + String responseJson = null; + try { + response = httpClient.execute(request, context); + // Some methods return non-200 on success + logger.debug("doRestRequest: status is {}", response.getStatusLine()); + HttpEntity entity = response.getEntity(); + // This is common; don't warn + if (entity == null) { + logger.debug("doRestRequest: Entity is null"); + } else { + // entity content length is never set; + // this naively tries to read everything. + responseJson = EntityUtils.toString(entity); + EntityUtils.consume(entity); + // Don't give back empty string; + // it has no more meaning than null. + if (responseJson.length() == 0) + responseJson = null; + } + } finally { + if (response != null) + response.close(); + } + if (response == null) + return null; + return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); + } + + /** + * Basic test invocation. + * + * @param args + * Expect 1 argument, the URL of a REST endpoint. + * @throws Exception + * if anything goes wrong + */ + public static void main(String[] args) throws Exception { + if (args.length != 1) + throw new IllegalArgumentException("Expect 1 argument: REST URL for GET"); + SimpleRestClientBase client = new SimpleRestClientBase(); + URIBuilder uriBuilder = new URIBuilder(args[0]); + URI uri = uriBuilder.build(); + HttpStatusAndResponse hsr = client.getRestContent(uri); + System.out.println("Response code is " + hsr.getStatusCode()); + System.out.println(hsr.getResponseString()); + System.out.println("main ends."); + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java new file mode 100644 index 0000000..8ac462d --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java @@ -0,0 +1,35 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +/** + * This controller maps requests for the DMaaP-BC-App's landing page, which is + * an Angular single-page application. + */ +@Controller +@RequestMapping("/") +public class DataBusHomeController extends DbcappRestrictedBaseController { + + public static final String APP_NAME = "dmaap-bc-app"; + public static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); + + /** + * At one time I published the landing page as simply "/dbc", but it can + * also be accessed with a default suffix; e.g., "/dbc.htm". + * + * @return View name key, which is resolved to a file using an Apache tiles + * "definitions.xml" file. + */ + @RequestMapping(value = { "/dbc" }, method = RequestMethod.GET) + public ModelAndView dbcDefaultController() { + // a model is only useful for JSP; this app is angular. + return new ModelAndView("dbc_home_tdkey"); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataRouterController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataRouterController.java new file mode 100644 index 0000000..c2fbb26 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DataRouterController.java @@ -0,0 +1,321 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.dcae.dmaapbc.dbcapp.util.DbcappProperties; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * Data Router controller: serves Ajax requests made by Angular scripts on pages + * that show feeds, publishers and subscribers. + */ +@Controller +@RequestMapping("/") +public class DataRouterController extends DbcappRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataRouterController.class); + + /** + * Application properties - NOT available to constructor. + */ + @Autowired + private DbcappProperties appProperties; + + private static final String FEED_PATH = "/dr_feed"; + private static final String PUB_PATH = "/dr_pub"; + private static final String SUB_PATH = "/dr_sub"; + + public DataRouterController() { + } + + /** + * Answers a request for one page of data router feeds. + * + * @param request + * HttpServletRequest + * @return Result of + * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} + */ + @RequestMapping(value = { FEED_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDRFeedsByPage(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = getItemListForPageWrapper(request, DmaapDataItem.DR_FEED); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Answers a request for one page of data router publishers. + * + * @param request + * HttpServletRequest + * @return Result of + * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} + */ + @RequestMapping(value = { PUB_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDRPubsByPage(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = getItemListForPageWrapper(request, DmaapDataItem.DR_PUB); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Answers a request for one page of data router subscribers. + * + * @param request + * HttpServletRequest + * @return Result of + * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} + */ + @RequestMapping(value = { SUB_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDRSubsByPage(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = getItemListForPageWrapper(request, DmaapDataItem.DR_SUB); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Adds a feed with the specified information. Expects a JSON block in the + * request body - a Feed object. + * + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { FEED_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addDRFeed(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = addItem(request, DmaapDataItem.DR_FEED, null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Adds a publisher with the specified information. Expects a JSON block in + * the request body - a DR_Pub object. + * + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { PUB_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addDRPub(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = addItem(request, DmaapDataItem.DR_PUB, HttpServletResponse.SC_CREATED); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Adds a subscriber with the specified information. Expects a JSON block in + * the request body - a DR_Sub object. + * + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { SUB_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addDRSub(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = addItem(request, DmaapDataItem.DR_SUB, HttpServletResponse.SC_CREATED); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Updates a feed with the specified information. Expects a JSON block in + * the request body - a Feed object. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { FEED_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateFeed(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = updateItem(request, DmaapDataItem.DR_FEED, Long.toString(id), null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Updates a publisher with the specified information. Expects a JSON block + * in the request body - a DR_Pub object. + * + * The pubId may have a dot in it. Spring, in its infinite wisdom, truncates + * extensions on dotted path parameters; e.g., "foo.json" becomes "foo". + * Avoid truncation here with the extra ":.+" incantation at the end. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { PUB_PATH + "/{id:.+}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateDRPub(@PathVariable("id") String id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = updateItem(request, DmaapDataItem.DR_PUB, id, null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Updates a subscriber with the specified information. Expects a JSON block + * in the request body - a DR_Sub object. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return a JSON object; on success it has a "status" and possibly a "data" + * item; on failure, also has an "error" item. + */ + @RequestMapping(value = { SUB_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateDRSub(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = updateItem(request, DmaapDataItem.DR_SUB, Long.toString(id), null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Deletes a feed with the ID specified as a path parameter. On successful + * delete the endpoint returns 204 (confusingly). + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return A JSON object as an HTTP response; on success it only has + * "status" item; on failure, also has an "error" item. + */ + @RequestMapping(value = { FEED_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDRFeed(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = deleteItem(request, DmaapDataItem.DR_FEED, Long.toString(id), 204); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Deletes the publisher with the ID specified as a path parameter. + * + * The pubId may have a dot in it. Spring, in its infinite wisdom, truncates + * extensions on dotted path parameters; e.g., "foo.json" becomes "foo". + * Avoid truncation here with the extra ":.+" incantation at the end. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return a JSON object; on success it only has "status" item; on failure, + * also has an "error" item. + */ + @RequestMapping(value = { PUB_PATH + "/{id:.+}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDRPub(@PathVariable("id") String id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = deleteItem(request, DmaapDataItem.DR_PUB, id, null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Deletes the subscriber with the ID specified as a path parameter. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return A JSON object; on success it only has "status" item; on failure, + * also has an "error" item. + */ + @RequestMapping(value = { SUB_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDRSub(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = deleteItem(request, DmaapDataItem.DR_SUB, Long.toString(id), 204); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Answers a request for data router feed classification labels, such as + * "Customer Proprietary", which are read from properties. + * + * @param request + * HttpServletRequest + * @return List of string values + */ + @RequestMapping(value = { FEED_PATH + "_pii_types" }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public List getDRFeedPiiType(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + ArrayList response = new ArrayList<>(); + String[] propKeys = appProperties.getCsvListProperty(DbcappProperties.DMAAP_PII_TYPE_LIST); + for (String key : propKeys) + response.add(appProperties.getProperty(key)); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java new file mode 100644 index 0000000..7964e45 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java @@ -0,0 +1,968 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.dcae.dmaapbc.client.DmaapBcRestClient; +import org.onap.dcae.dmaapbc.client.HttpStatusAndResponse; +import org.onap.dcae.dmaapbc.dbcapp.domain.DmaapAccess; +import org.onap.dcae.dmaapbc.dbcapp.rest.DbcUsvcRestClient; +import org.onap.dcae.dmaapbc.dbcapp.service.DmaapAccessService; +import org.onap.dcae.dmaapbc.dbcapp.util.DbcappProperties; +import org.onap.dcae.dmaapbc.model.DR_Pub; +import org.onap.dcae.dmaapbc.model.DR_Sub; +import org.onap.dcae.dmaapbc.model.DcaeLocation; +import org.onap.dcae.dmaapbc.model.Dmaap; +import org.onap.dcae.dmaapbc.model.DmaapObject; +import org.onap.dcae.dmaapbc.model.ErrorResponse; +import org.onap.dcae.dmaapbc.model.Feed; +import org.onap.dcae.dmaapbc.model.MR_Client; +import org.onap.dcae.dmaapbc.model.Topic; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * This base class provides utility methods to child controllers. All of the + * requests are forwarded on to a remote REST API, so there's a large degree of + * commonality among the implementations. Combining them kept the lines-of-code + * count down, at the expense of some complexity. + */ +public class DbcappRestrictedBaseController extends RestrictedBaseController { + + /** + * Query parameter for desired page number + */ + protected static final String PAGE_NUM_QUERY_PARAM = "pageNum"; + + /** + * Query parameter for desired items per page + */ + protected static final String VIEW_PER_PAGE_QUERY_PARAM = "viewPerPage"; + + /** + * Tag for status code in JSON responses - ALWAYS PRESENT. + */ + protected static final String STATUS_RESPONSE_KEY = "status"; + + /** + * Tag for data in JSON responses. + */ + protected static final String DATA_RESPONSE_KEY = "data"; + + /** + * Tag for error message in JSON responses; absent on success. + */ + protected static final String ERROR_RESPONSE_KEY = "error"; + + /** + * Tag for response integer, pages required to display complete result list + */ + protected static final String TOTAL_PAGES_RESPONSE_KEY = "totalPages"; + + /** + * Tag for DMaaP name obtained from REST client. + */ + protected static final String PROFILE_NAME_RESPONSE_KEY = "profileName"; + + /** + * Tag for DMaaP name obtained from REST client. + */ + protected static final String DMAAP_NAME_RESPONSE_KEY = "dmaapName"; + + /** + * Tag for DCAE location name list obtained from REST client. + */ + protected static final String DCAE_LOCATIONS_RESPONSE_KEY = "dcaeLocations"; + + /** + * Logger that conforms with ECOMP guidelines + */ + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DbcappRestrictedBaseController.class); + + /** + * For general use in these methods and subclasses + */ + protected final ObjectMapper mapper = new ObjectMapper(); + + /** + * DAO accesses the profiles via a local database. REST accesses the + * profiles via a remote REST service. + */ + public enum AccessMethod { + DAO, REST + }; + + /** + * Enum for selecting an item type. + */ + public enum DmaapDataItem { + DR_FEED, DR_PUB, DR_SUB, MR_TOPIC, MR_CLIENT; + } + + /** + * Application properties - NOT available to constructor. + */ + @Autowired + private DbcappProperties appProperties; + + /** + * Database access - which might not be used. + */ + @Autowired + private DmaapAccessService dmaapAccessDaoServiceAuto; + + /** + * Read from application properties. + */ + private String mechIdName, mechIdPass; + + /** + * This is set by {@link #getDmaapAccessService()} to the DAO or REST + * implementation as configured in properties. + */ + private DmaapAccessService dmaapAccessService; + + /** + * Hello Spring, here's your no-arg constructor. + */ + public DbcappRestrictedBaseController() { + // Do not serialize null values + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + + /** + * Access method for subclasses. + * + * @return DbcappProperties object that was autowired by Spring. + */ + protected DbcappProperties getAppProperties() { + return appProperties; + } + + /** + * Lazy initialization. As a side effect, caches mech ID and password. + * + * @return Either DAO or REST client that implements the access service + * interface. + */ + protected DmaapAccessService getDmaapAccessService() { + if (dmaapAccessService != null) + return dmaapAccessService; + + // Get the application's mechid + mechIdName = appProperties.getProperty(DbcappProperties.DMAAP_MECHID_NAME); + // This is encrypted + String cipher = appProperties.getProperty(DbcappProperties.DMAAP_MECHID_PASSWORD); + if (mechIdName == null || cipher == null) + throw new RuntimeException("Failed to get MECH_ID name and/or password from properties"); + try { + mechIdPass = CipherUtil.decrypt(cipher); + } catch (Exception ex) { + throw new RuntimeException("Failed to decrypt password from config file", ex); + } + + String accessMethod = appProperties.getProperty(DbcappProperties.PROFILE_ACCESS_METHOD); + if (accessMethod == null) + throw new RuntimeException("Failed to get property " + DbcappProperties.PROFILE_ACCESS_METHOD); + AccessMethod profileAccessMethod = AccessMethod.valueOf(accessMethod.toUpperCase()); + if (AccessMethod.DAO == profileAccessMethod) { + // Spring auto-wired this field + dmaapAccessService = dmaapAccessDaoServiceAuto; + } else { + String url = appProperties.getProperty(DbcappProperties.PROFILE_USVC_URL); + String user = appProperties.getProperty(DbcappProperties.PROFILE_USVC_USER); + String pass = appProperties.getProperty(DbcappProperties.PROFILE_USVC_PASS); + if (url == null || user == null || pass == null) + throw new RuntimeException("getDmaapAccessService: missing property: one of url, user, pass"); + String clearText = null; + try { + clearText = CipherUtil.decrypt(pass); + } catch (Exception ex) { + throw new RuntimeException("getDmaapAccessService: failed to decrypt password from config"); + } + dmaapAccessService = new DbcUsvcRestClient(url, user, clearText); + } + return dmaapAccessService; + } + + /** + * Creates a REST client with appropriate credentials, the user/pass from + * the access profile if present, otherwise with the default mech ID and + * password. + * + * @param dmaapAccess + * Profile + * @return REST client. + */ + protected DmaapBcRestClient getDmaapBcRestClient(DmaapAccess dmaapAccess) { + DmaapBcRestClient restClient = null; + if (dmaapAccess.getMechId() == null || dmaapAccess.getMechId().length() == 0) + restClient = new DmaapBcRestClient(dmaapAccess.getDmaapUrl(), mechIdName, mechIdPass); + else + restClient = new DmaapBcRestClient(dmaapAccess.getDmaapUrl(), dmaapAccess.getMechId(), + dmaapAccess.getPassword()); + return restClient; + } + + /** + * Pulls out of the specified list the appropriate items for the page of + * results specified by the page number and view-per-page parameters. + * + * @param pageNum + * Page number requested by user + * @param viewPerPage + * Number of items per page + * @param itemList + * List of items available + * @return List of items to display + */ + @SuppressWarnings("rawtypes") + private static List shrinkListToPage(final int pageNum, final int viewPerPage, final List itemList) { + // user-friendly page numbers index from 1 + int firstIndexOnThisPage = viewPerPage * (pageNum - 1); + int firstIndexOnNextPage = viewPerPage * pageNum; + int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); + int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); + // answers empty list if from==to + return itemList.subList(fromIndex, toIndex); + } + + /** + * Gets the body of a HTTP request assuming UTF-8 encoding. + * + * @param request + * HttpServletRequest + * @return String version of request body + * @throws IOException + * If the read fails + */ + protected static String getBody(HttpServletRequest request) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try { + InputStream inputStream = request.getInputStream(); + if (inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); + char[] charBuffer = new char[512]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } else { + stringBuilder.append(""); + } + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ex) { + throw ex; + } + } + + } + return stringBuilder.toString(); + } + + /** + * Builds a JSON success response from the specified inputs. + * + * @param statusCode + * e.g., 200 for OK + * @param dataPojo + * Plain old Java object to serialize as JSON; ignored if null. + * @throws JsonProcessingException + * If the POJO cannot be serialized + * @return JSON block with items "status" : 200 and "data" : (data..) + */ + protected String buildJsonSuccess(int statusCode, Object dataPojo) throws JsonProcessingException { + Map model = new HashMap(); + model.put(STATUS_RESPONSE_KEY, statusCode); + if (dataPojo != null) + model.put(DATA_RESPONSE_KEY, dataPojo); + String json = mapper.writeValueAsString(model); + return json; + } + + /** + * Builds a JSON error response from the specified inputs. + * + * @param statusCode + * e.g., 500 for internal server error + * @param errMsg + * Information about the operation that failed + * @param exception + * Converted to string; ignored if null. + * @return JSON block with tags "status" and "error". + */ + protected String buildJsonError(int statusCode, String errMsg, Exception exception) { + Map model = new HashMap(); + model.put(STATUS_RESPONSE_KEY, new Integer(500)); + if (exception == null) { + model.put(ERROR_RESPONSE_KEY, errMsg); + } else { + final int enough = 512; + String exString = exception.toString(); + String exceptionMsg = exString.length() > enough ? exString.substring(0, enough) : exString; + model.put(ERROR_RESPONSE_KEY, errMsg + ": " + exceptionMsg); + } + String json = null; + try { + json = mapper.writeValueAsString(model); + } catch (JsonProcessingException ex) { + // serializing the trivial map should never fail + String err = "buildJsonError: failed to serialize"; + logger.error(EELFLoggerDelegate.errorLogger, err, ex); + throw new RuntimeException(err, ex); + } + return json; + } + + /** + * Gets a list of DMaaP access profiles for this user from the database. The + * profiles have passwords in the clear - this method decrypts the database + * entries. + * + * Initializes the list for new users and/or configuration changes. Checks + * the database list against the configured list of URLs, and creates new + * rows for any configured URLs not present for the user. Most environments + * are expected to have exactly one valid URL, and the webapp uses a fixed + * MechID to authenticate itself to the DMaaP bus controller, so this + * approach means new users can start without any setup of URLs. + * + * @param userId + * User ID + * @return List of DmaapAccess objects + * @throws Exception + * If the URL list is not available in properties + */ + protected List getOrInitDmaapAccessList(String userId) throws Exception { + String[] configUrls = getAppProperties().getCsvListProperty(DbcappProperties.DMAAP_REST_URL_LIST); + if (configUrls == null || configUrls.length == 0) + throw new Exception("getOrInitDmaapAccessList: Failed to get DMAAP REST URL list"); + // Update this list to track which URLs are in the database. + List configUrlList = new ArrayList(configUrls.length); + for (String c : configUrls) { + // Validate URL to detect config botches + URL url = new URL(c); + configUrlList.add(url.toExternalForm()); + } + + List dbAccessList = getDmaapAccessService().getDmaapAccessList(userId); + + // Check the database entries against the configuration. Also + // build a list of non-DAO objects with clear-text passwords. + List clearList = new ArrayList(dbAccessList.size()); + for (DmaapAccess dmaapAccess : dbAccessList) { + // drop this URL from the list. + // If it's not known to config, complain because that's a bogus row. + if (!configUrlList.remove(dmaapAccess.getDmaapUrl())) + logger.warn(EELFLoggerDelegate.errorLogger, "getOrInitDmaapAccessList: detected extra URL {}", + dmaapAccess.getDmaapUrl()); + // Return cleartext in JSON + DmaapAccess clone = new DmaapAccess(dmaapAccess); + clone.setPassword(clone.decryptPassword()); + clearList.add(clone); + } + + // Create new rows for any configured URLs not found for this user. + for (int i = 0; i < configUrlList.size(); ++i) { + String missUrl = configUrlList.get(i); + logger.debug(EELFLoggerDelegate.debugLogger, "getOrInitDmaapAccessList: adding missing URL {}", missUrl); + DmaapAccess newDmaapAccess = new DmaapAccess(); + // Create a semi-reasonable name for the table + newDmaapAccess.setName("dmaap-" + Integer.toString(i + 1)); + newDmaapAccess.setUserId(userId); + newDmaapAccess.setDmaapUrl(missUrl); + // Write to db. + getDmaapAccessService().saveDmaapAccess(newDmaapAccess); + // Add to response, which assumes the write was successful. + clearList.add(newDmaapAccess); + } + + return clearList; + } + + /** + * Gets the user's selected DMaaP access profile. + * + * @param userId + * User ID + * @return DmaapAccess object that is currently selected, or the first one + * found if none are selected; null if no access profiles are + * configured. + * @throws Exception + * If the profile is not found + */ + protected DmaapAccess getSelectedDmaapAccess(String userId) throws Exception { + List profiles = getOrInitDmaapAccessList(userId); + if (profiles.size() == 0) { + logger.debug("getSelectedDmaapAccess: no rows found, returning null"); + return null; + } + + // Return the first one by default if nothing is selected. + DmaapAccess selected = profiles.get(0); + for (DmaapAccess da : profiles) + if (da.getSelected()) + selected = da; + + return selected; + } + + /** + * Supports sorting a list of feeds by the first column displayed: ID + */ + private static Comparator feedComparator = new Comparator() { + @Override + public int compare(DmaapObject o1, DmaapObject o2) { + Feed f1 = (Feed) o1; + Feed f2 = (Feed) o2; + // sort these numbers lexicographically, same as the front end + // table. + return f1.getFeedId().compareTo(f2.getFeedId()); + } + }; + + /** + * Supports sorting a list of publishers by the first column displayed: pub + * ID + */ + private static Comparator pubComparator = new Comparator() { + @Override + public int compare(DmaapObject o1, DmaapObject o2) { + DR_Pub p1 = (DR_Pub) o1; + DR_Pub p2 = (DR_Pub) o2; + return p1.getPubId().compareTo(p2.getPubId()); + } + }; + + /** + * Supports sorting a list of subscribers by the first column displayed: sub + * ID + */ + private static Comparator subComparator = new Comparator() { + @Override + public int compare(DmaapObject o1, DmaapObject o2) { + DR_Sub s1 = (DR_Sub) o1; + DR_Sub s2 = (DR_Sub) o2; + // sort these numbers lexicographically, same as the front end + // table. + return s1.getSubId().compareTo(s2.getSubId()); + } + }; + + /** + * Supports sorting a list of topics by the first column displayed: FQTN + */ + private static Comparator topicComparator = new Comparator() { + @Override + public int compare(DmaapObject o1, DmaapObject o2) { + Topic t1 = (Topic) o1; + Topic t2 = (Topic) o2; + return t1.getFqtn().compareTo(t2.getFqtn()); + } + }; + + /** + * Supports sorting a list of clients by the first column displayed: client + * ID. + */ + private static Comparator clientComparator = new Comparator() { + @Override + public int compare(DmaapObject o1, DmaapObject o2) { + MR_Client c1 = (MR_Client) o1; + MR_Client c2 = (MR_Client) o2; + // sort these numbers lexicographically, same as the front end + // table. + return c1.getMrClientId().compareTo(c2.getMrClientId()); + } + }; + + /** + * Gets one page of DMaaP objects and supporting information via the Bus + * Controller REST client. On success, returns a JSON object as String with + * the following tags: + *
    + *
  • status: Integer; HTTP status code 200. + *
  • dmaapName: String, name returned by the remote DMaaP instance. + *
  • dcaeLocations: Array of string, locations returned by the remote + * DMaaP instance. + *
  • data: Array of the desired items; e.g., data router feeds. + *
  • totalPages: Integer, the number of pages required to display the + * complete list of items using the submitted page size + *
+ * + * This duplicates all of {@link #buildJsonSuccess(int, Object)}. + * + * @param dmaapAccess + * Access details for the DMaaP REST API + * @param option + * Specifies which item list type to get: data router feeds, etc. + * @param pageNum + * Page number of results + * @param viewPerPage + * Number of items per page + * @return JSON block as String, see above. + * @throws Exception + * On any error + */ + private String getItemListForPage(DmaapAccess dmaapAccess, DmaapDataItem option, int pageNum, int viewPerPage) + throws Exception { + DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); + // Get the instance so the page can display its name + DmaapObject dmaap = restClient.getDmaap(); + if (dmaap instanceof ErrorResponse) { + // Bad password is caught here. + ErrorResponse err = (ErrorResponse) dmaap; + throw new Exception(err.getMessage()); + } + // Get locations for editing + List dcaeLocations = restClient.getDcaeLocations(); + if (dcaeLocations.size() == 1 && dcaeLocations.get(0) instanceof ErrorResponse) { + // Should never happen - bad password is caught right above - but be + // careful. + ErrorResponse err = (ErrorResponse) dcaeLocations.get(0); + throw new Exception(err.getMessage()); + } + // Pass them back as String array + String[] dcaeLocs = new String[dcaeLocations.size()]; + for (int i = 0; i < dcaeLocs.length; ++i) { + DcaeLocation dcaeLoc = (DcaeLocation) dcaeLocations.get(i); + dcaeLocs[i] = dcaeLoc.getDcaeLocationName(); + } + // Get the requested item list + List itemList = null; + switch (option) { + case DR_FEED: + itemList = restClient.getFeeds(); + // size 1 may be error response + if (itemList.size() > 1) + Collections.sort(itemList, feedComparator); + break; + case DR_PUB: + itemList = restClient.getDRPubs(); + // size 1 may be error response + if (itemList.size() > 1) + Collections.sort(itemList, pubComparator); + break; + case DR_SUB: + itemList = restClient.getDRSubs(); + // size 1 may be error response + if (itemList.size() > 1) + Collections.sort(itemList, subComparator); + break; + case MR_TOPIC: + itemList = restClient.getTopics(); + // size 1 may be error response + if (itemList.size() > 1) + Collections.sort(itemList, topicComparator); + break; + case MR_CLIENT: + itemList = restClient.getMRClients(); + // size 1 may be error response + if (itemList.size() > 1) + Collections.sort(itemList, clientComparator); + break; + default: + throw new Exception("getItemListForPage: pgmr error, unimplemented case: " + option.name()); + } + + logger.debug("getItemListForPage: list size is {}", itemList.size()); + int pageCount = (int) Math.ceil((double) itemList.size() / viewPerPage); + @SuppressWarnings("unchecked") + List subList = shrinkListToPage(pageNum, viewPerPage, itemList); + itemList = subList; + // Build response here + Map model = new HashMap(); + model.put(STATUS_RESPONSE_KEY, new Integer(200)); + model.put(PROFILE_NAME_RESPONSE_KEY, dmaapAccess.getName()); + model.put(DMAAP_NAME_RESPONSE_KEY, ((Dmaap) dmaap).getDmaapName()); + model.put(DCAE_LOCATIONS_RESPONSE_KEY, dcaeLocs); + model.put(DATA_RESPONSE_KEY, itemList); + model.put(TOTAL_PAGES_RESPONSE_KEY, pageCount); + + // build the response + String outboundJson = null; + try { + outboundJson = mapper.writeValueAsString(model); + } catch (Exception ex) { + // should never happen + logger.error("getItemListForPage: failed to serialize model: ", ex); + throw new Exception("sendItemListForPage", ex); + } + + return outboundJson; + } + + /** + * Gets a page of the specified DMaaP items. This method traps errors and + * constructs an appropriate JSON block if an error happens. + * + * See {@link #getItemListForPage(DmaapAccess, DmaapDataItem, int, int)}. + * + * @param request + * Inbound request + * @param option + * DMaaP item type to get + * @return JSON with list of serialized objects, or an error. + */ + protected String getItemListForPageWrapper(HttpServletRequest request, DmaapDataItem option) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("getItemListForPageWrapper: Failed to get Login UID"); + DmaapAccess selected = getSelectedDmaapAccess(appUser.getLoginId()); + if (selected == null) // leap into exception handler + throw new Exception("No DMaaP access profiles are configured."); + int pageNum = Integer.parseInt(request.getParameter(PAGE_NUM_QUERY_PARAM)); + int viewPerPage = Integer.parseInt(request.getParameter(VIEW_PER_PAGE_QUERY_PARAM)); + outboundJson = getItemListForPage(selected, option, pageNum, viewPerPage); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to get DMaaP item type " + option.name(), ex); + } + return outboundJson; + } + + /** + * Adds an item of the specified type with the specified content. Constructs + * an object by deserializing the JSON block, but ignores any ID field that + * is supplied. + * + * On success, returns a JSON block as String with any data returned by the + * REST client. Throws an exception on any failure. + * + * @param dmaapAccess + * Access details for the DMaaP REST API + * @param userId + * The login ID of the user making the request + * @param itemType + * DMaaP item type to add + * @param itemContent + * JSON block to deserialize as an object + * @param scAddlStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return JSON object with result of the operation + * @throws Exception + * on any problem + */ + private String addDmaapItem(DmaapAccess dmaapAccess, String userId, DmaapDataItem itemType, String itemContent, + Integer scAddlStatus) throws Exception { + DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); + HttpStatusAndResponse hsr = null; + switch (itemType) { + case DR_FEED: + Feed feed = mapper.readValue(itemContent, Feed.class); + logger.debug("addDmaapItem: received feed: {} ", feed); + // Null out any ID to get an auto-generated ID + feed.setFeedId(null); + // Assign the owner to be the webapp user + feed.setOwner(userId); + hsr = restClient.postFeed(feed); + break; + case DR_PUB: + DR_Pub pub = mapper.readValue(itemContent, DR_Pub.class); + logger.debug("addDmaapItem: received pub: {} ", pub); + // Null out any ID to get an auto-generated ID + pub.setPubId(null); + hsr = restClient.postDRPub(pub); + break; + case DR_SUB: + DR_Sub sub = mapper.readValue(itemContent, DR_Sub.class); + logger.debug("addDmaapItem: received sub: {} ", sub); + // Null out any ID to get an auto-generated ID + sub.setSubId(null); + // Assign the owner to be the webapp user + sub.setOwner(userId); + hsr = restClient.postDRSub(sub); + break; + case MR_TOPIC: + Topic topic = mapper.readValue(itemContent, Topic.class); + logger.debug("addDmaapItem: received topic: {} ", topic); + // No ID on topic + topic.setOwner(userId); + hsr = restClient.postTopic(topic); + break; + case MR_CLIENT: + MR_Client client = mapper.readValue(itemContent, MR_Client.class); + logger.debug("addDmaapItem: received client: {} ", client); + client.setMrClientId(null); + hsr = restClient.postMRClient(client); + break; + default: + throw new Exception("addDmaapItem: pgmr error, unimplemented case: " + itemType.name()); + } + + // Build result here + String outboundJson = null; + if (hsr.getStatusCode() == HttpServletResponse.SC_OK + || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { + outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); + } else { + throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) + + " with content " + hsr.getResponseString()); + } + return outboundJson; + } + + /** + * Adds the specified DMaaP item that is read from the request body. This + * method traps errors and constructs an appropriate JSON block if an error + * happens. + * + * @param request + * Used to obtain user info from the active session + * @param itemType + * DMaaP item type to add + * @param scAddlStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return JSON block with success or failure object + */ + protected String addItem(HttpServletRequest request, DmaapDataItem itemType, Integer scAddlStatus) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("addDmaapItem: Failed to get Login ID"); + + DmaapAccess access = getSelectedDmaapAccess(appUser.getLoginId()); + if (access == null) // leap into exception handler + throw new Exception("No DMaaP access profiles are configured."); + String jsonContent = getBody(request); + outboundJson = addDmaapItem(access, appUser.getLoginId(), itemType, jsonContent, scAddlStatus); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to add DMaaP item " + itemType.name(), ex); + } + + return outboundJson; + } + + /** + * Updates an item of the specified type with the specified content. + * Constructs an object by deserializing the JSON block. + * + * On success, returns a JSON block as String with any data returned by the + * REST client. Throws an exception on any failure. + * + * @param dmaapAccess + * Access details for the DMaaP REST API + * @param userId + * The Login ID of the user making the request + * @param itemType + * DMaaP item type to update + * @param itemId + * Item identification + * @param itemContent + * JSON block to deserialize as an object + * @param scAddlStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return JSON object with result of the operation + * @throws Exception + * on any problem + */ + private String updateDmaapItem(DmaapAccess dmaapAccess, String userId, DmaapDataItem itemType, String itemId, + String itemContent, Integer scAddlStatus) throws Exception { + DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); + HttpStatusAndResponse hsr = null; + switch (itemType) { + case DR_FEED: + Feed feed = mapper.readValue(itemContent, Feed.class); + logger.debug("updateDmaapItem: received feed: {} ", feed); + // Ensure the owner is the webapp user + feed.setOwner(userId); + hsr = restClient.putFeed(feed); + break; + case DR_PUB: + DR_Pub pub = mapper.readValue(itemContent, DR_Pub.class); + logger.debug("updateDmaapItem: received pub: {} ", pub); + hsr = restClient.putDRPub(pub); + break; + case DR_SUB: + DR_Sub sub = mapper.readValue(itemContent, DR_Sub.class); + logger.debug("updateDmaapItem: received sub: {} ", sub); + // Ensure the owner is the webapp user + sub.setOwner(userId); + hsr = restClient.putDRSub(sub); + break; + case MR_TOPIC: + Topic topic = mapper.readValue(itemContent, Topic.class); + logger.debug("updateDmaapItem: received topic: {} ", topic); + // Ensure the owner is the webapp user + topic.setOwner(userId); + // DCAE backend may implement PUT someday. + if (true && userId != null) + throw new UnsupportedOperationException("put topic not supported (yet)"); + break; + case MR_CLIENT: + MR_Client client = mapper.readValue(itemContent, MR_Client.class); + logger.debug("updateDmaapItem: received client: {} ", client); + hsr = restClient.putMRClient(client); + break; + default: + throw new Exception("updateDmaapItem: pgmr error, unimplemented case: " + itemType.name()); + } + + // Build result here + String outboundJson = null; + if (hsr.getStatusCode() == HttpServletResponse.SC_OK + || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { + outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); + } else { + throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) + + " with content " + hsr.getResponseString()); + } + return outboundJson; + } + + /** + * Updates the specified DMaaP item that is read from the request body. This + * method traps errors and constructs an appropriate JSON block if an error + * happens. + * + * @param request + * Used to obtain user info from the active session + * @param itemType + * DMaaP item type to update + * @param itemId + * Item identification to update + * @param scUpdatelStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return JSON object with success or error information. + */ + protected String updateItem(HttpServletRequest request, DmaapDataItem itemType, String itemId, + Integer scUpdatelStatus) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("updateItem: Failed to get Login ID"); + DmaapAccess access = getSelectedDmaapAccess(appUser.getLoginId()); + if (access == null) // leap into exception handler + throw new Exception("No DMaaP access profiles are configured."); + String jsonContent = getBody(request); + outboundJson = updateDmaapItem(access, appUser.getLoginId(), itemType, itemId, jsonContent, + scUpdatelStatus); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to update DMaaP item " + itemType.name(), ex); + } + + return outboundJson; + } + + /** + * Deletes an item of the specified type with the specified ID. + * + * @param dmaapAccess + * Access details for the DMaaP REST API + * @param itemType + * DMaaP item type to delete + * @param itemId + * Item identification + * @param scAddlStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return On success, returns a JSON block as String with any data returned + * by the REST client. + * @throws Exception + * On any failure. + */ + private String deleteDmaapItem(DmaapAccess dmaapAccess, DmaapDataItem itemType, String itemId, Integer scAddlStatus) + throws Exception { + DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); + HttpStatusAndResponse hsr = null; + switch (itemType) { + case DR_FEED: + hsr = restClient.deleteFeed(itemId); + break; + case DR_PUB: + hsr = restClient.deleteDRPub(itemId); + break; + case DR_SUB: + hsr = restClient.deleteDRSub(itemId); + break; + case MR_TOPIC: + hsr = restClient.deleteTopic(itemId); + break; + case MR_CLIENT: + hsr = restClient.deleteMRClient(itemId); + break; + default: + throw new Exception("deleteDmaapItem: pgmr error, unimplemented case: " + itemType.name()); + } + + // Build result here + String outboundJson = null; + if (hsr.getStatusCode() == HttpServletResponse.SC_OK + || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { + outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); + } else { + throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) + + " with content " + hsr.getResponseString()); + } + return outboundJson; + } + + /** + * Deletes the specified DMaaP item. This method traps errors and constructs + * an appropriate JSON block if an error happens. + * + * @param request + * Used to obtain user info from the active session + * @param itemType + * DMaaP item type to delete + * @param itemId + * item ID to delete + * @param scAddlStatus + * HTTP status code 200 is always accepted. If this parameter is + * not null, the value is also considered a valid HTTP status + * code on success; e.g., 204. + * @return JSON object with success or error information. + */ + protected String deleteItem(HttpServletRequest request, DmaapDataItem itemType, String itemId, + Integer scAddlStatus) { + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("deleteItem: Failed to get Login ID"); + DmaapAccess selected = getSelectedDmaapAccess(appUser.getLoginId()); + if (selected == null) // leap into exception handler + throw new Exception("No DMaaP access profiles are configured."); + outboundJson = deleteDmaapItem(selected, itemType, itemId, scAddlStatus); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to delete DMaaP item " + itemType.name() + " ID " + itemId, ex); + } + return outboundJson; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java new file mode 100644 index 0000000..bd5c420 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java @@ -0,0 +1,356 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.dcae.dmaapbc.client.DmaapBcRestClient; +import org.onap.dcae.dmaapbc.dbcapp.domain.DmaapAccess; +import org.onap.dcae.dmaapbc.model.Dmaap; +import org.onap.dcae.dmaapbc.model.DmaapObject; +import org.onap.dcae.dmaapbc.model.ErrorResponse; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.slf4j.MDC; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * DMaaP Access controller: serves Ajax requests made by Angular on pages where + * the user adds, edits and deletes DMaaP access profiles. This controller must + * defend the database against rogue requests including SQL injection attacks. + */ +@Controller +@RequestMapping("/") +public class DmaapAccessController extends DbcappRestrictedBaseController { + + /** + * Logger that conforms with ECOMP guidelines + */ + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DmaapAccessController.class); + + private static final String DMAAP_ACCESS_PATH = "/dmaap_access"; + private static final String SELECT_DMAAP_ACCESS_PATH = "/select_dmaap_access"; + + /** + * For general use in these methods + */ + private final ObjectMapper mapper; + + /** + * Never forget that Spring autowires fields AFTER the constructor is + * called. + */ + public DmaapAccessController() { + mapper = new ObjectMapper(); + } + + /** + * Gets a list of DMaaP access profiles for this user from the database and + * returns them in a JSON array nested within a response object. Traps errors and constructs an appropriate JSON block if an error + * happens. + * + * See {@link #getOrInitDmaapAccessList(String)}. + * + * @param request + * HttpServletRequest + * @return JSON with access profiles, or an error JSON if the request fails. + */ + @RequestMapping(value = { DMAAP_ACCESS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getDmaapAccessList(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("getDmaapAccessList: Failed to get Login ID"); + List dbAccessList = getOrInitDmaapAccessList(appUser.getLoginId()); + // Wrap the list in the status indicator. + Map model = new HashMap(); + model.put(STATUS_RESPONSE_KEY, new Integer(200)); + model.put(DATA_RESPONSE_KEY, dbAccessList); + outboundJson = mapper.writeValueAsString(model); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to get DMaaP access profile list", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Adds a DMaaP access profile for the requesting user ID; ignores any + * values for row ID and user ID in the body. Traps errors and + * constructs an appropriate JSON block if an error happens. + * + * @param request + * HttpServletRequest + * @return Trivial JSON object indicating success or failure. + */ + @RequestMapping(value = { DMAAP_ACCESS_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addDmaapAccess(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("addDmaapAccess: Failed to get Login ID"); + + DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); + logger.debug("addDmaapAccess: received object: {} ", dmaapAccess); + + // Null out ID to get an auto-generated ID + dmaapAccess.setId(null); + // Overwrite any submitted user id + dmaapAccess.setUserId(appUser.getLoginId()); + // Encrypt password + if (dmaapAccess.getPassword() != null) + dmaapAccess.encryptPassword(dmaapAccess.getPassword()); + + // Create a new row + getDmaapAccessService().saveDmaapAccess(dmaapAccess); + + // Answer success + outboundJson = buildJsonSuccess(200, null); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to add DMaaP access profile", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Updates a DMaaP access profile if the row user ID matches the requesting + * user ID. Traps errors and + * constructs an appropriate JSON block if an error happens. + * + * @param id + * Path parameter with ID of the DMaaP access profile + * @param request + * HttpServletRequest + * @return Trivial JSON object indicating success or failure. + */ + @RequestMapping(value = { DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("updateDmaapAccess: Failed to get Login ID"); + + DmaapAccess domainObj = getDmaapAccessService().getDmaapAccess(id); + if (!appUser.getLoginId().equals(domainObj.getUserId())) + throw new Exception("updateDmaapAccess: mismatch of appUser and row user ID"); + + DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); + logger.debug("updateDmaapAccess: received object: {} ", dmaapAccess); + + // Use the path-parameter id; don't trust the one in the object + dmaapAccess.setId(id); + // Encrypt password if present + if (dmaapAccess.getPassword() != null) + dmaapAccess.encryptPassword(dmaapAccess.getPassword()); + + // Update the existing row + getDmaapAccessService().saveDmaapAccess(dmaapAccess); + + // Answer "OK" + outboundJson = buildJsonSuccess(200, null); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to update DMaaP access profile", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Deletes a DMaaP access profile if the row user ID matches the requesting + * user ID. Traps errors and + * constructs an appropriate JSON block if an error happens. + * + * @param id + * Path parameter with ID of the DMaaP access profile + * @param request + * HttpServletRequest + * @return Trivial JSON object indicating success or failure (altho this is + * slightly contrary to conventions for a DELETE method) + */ + @RequestMapping(value = { + DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("deleteDmaapAccess: Failed to get Login ID"); + // Validate that this user owns the row with the specified ID + DmaapAccess domainObj = getDmaapAccessService().getDmaapAccess(id); + if (!appUser.getLoginId().equals(domainObj.getUserId())) + throw new Exception("deleteDmaapAccess: mismatch of appUser and row user ID"); + + getDmaapAccessService().deleteDmaapAccess(id); + + // Answer "OK" + outboundJson = buildJsonSuccess(200, null); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to delete DMaaP access profile", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Gets the selected DMaaP access row for the requesting user. + * + * See {@link #getSelectedDmaapAccess(String)} + * + * @param request + * HttpServletRequest + * @return JSON object with one DmaapAccessProfile, or an error + */ + @RequestMapping(value = { SELECT_DMAAP_ACCESS_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getSelectedDmaapAccessProfile(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("getSelectedDmaapAccessProfile: Failed to get Login ID"); + DmaapAccess selected = super.getSelectedDmaapAccess(appUser.getLoginId()); + // clone and decrypt + DmaapAccess clear = new DmaapAccess(selected); + try { + clear.setPassword(clear.decryptPassword()); + } catch (Exception ex) { + // Should never happen + throw new RuntimeException("getSelectedDmaapAccessProfile: Failed to decrypt password", ex); + } + outboundJson = buildJsonSuccess(200, clear); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to get selected DMaaP access profile", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Marks the DMaaP access row as selected (first choice) for the requesting + * user if the row user ID matches the requesting user ID. As a side effect, + * removes selected marking from all other user rows. Returns status, + * additionally an error message on failure. Traps errors and + * constructs an appropriate JSON block if an error happens. + * + * Choice of PUT is fairly arbitrary - there is no body, but GET is for + * actions that do not change data. + * + * @param id + * Path parameter with ID of the DMaaP access profile + * @param request + * HttpServletRequest + * @return Trivial JSON object indicating success or failure. + */ + @RequestMapping(value = { + SELECT_DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String selectDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + User appUser = UserUtils.getUserSession(request); + if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) + throw new Exception("selectDmaapAccess: Failed to get Login UID"); + // A little inefficient in that it requires 3 database accesses; + // probably could be done in 1 with some sophisticated SQL. + List dmaapAccessList = getDmaapAccessService().getDmaapAccessList(appUser.getLoginId()); + for (DmaapAccess dmaap : dmaapAccessList) { + // Only write out the changed rows. + boolean changed = false; + if (id == dmaap.getId()) { + changed = !dmaap.getSelected(); + dmaap.setSelected(true); + } else { + changed = dmaap.getSelected(); + dmaap.setSelected(false); + } + if (changed) + getDmaapAccessService().saveDmaapAccess(dmaap); + } + + // Answer OK + outboundJson = buildJsonSuccess(200, null); + } catch (Exception ex) { + outboundJson = buildJsonError(500, "Failed to select a DMaaP access profile", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + + /** + * Tests the URL in the DMaaP access profile object. Traps errors and + * constructs an appropriate JSON block if an error happens. + * + * @param request + * HttpServletRequest + * @return JSON with a Dmaap object (which has name etc.) on success, error + * on failure. + */ + @RequestMapping(value = { "test_dmaap_access" }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String testDmaapAccess(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String outboundJson = null; + try { + DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); + logger.debug("testDmaapAccess: received object: {} ", dmaapAccess); + if (dmaapAccess.getDmaapUrl() == null || dmaapAccess.getDmaapUrl().trim().length() == 0) + throw new Exception("Null or empty URL"); + + DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); + // Get the instance so the page can display its name + DmaapObject dmaap = restClient.getDmaap(); + if (dmaap instanceof Dmaap) { + outboundJson = buildJsonSuccess(200, dmaap); + } else { + // Bad credentials lands here. + ErrorResponse err = (ErrorResponse) dmaap; + outboundJson = buildJsonError(500, "Test failed: " + err.getMessage(), null); + } + } catch (Exception ex) { + // This is entirely likely; e.e., unknown host exception on typo. + outboundJson = buildJsonError(500, "Invalid DMaaP URL", ex); + } + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return outboundJson; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java new file mode 100644 index 0000000..820cd5b --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java @@ -0,0 +1,142 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.dcae.dmaapbc.dbcapp.service.DmaapAccessService; +import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + +/** + * This controller responds to probes for application health, returning a JSON + * body to indicate current status. + */ +@RestController +@Configuration +@EnableAspectJAutoProxy +@RequestMapping("/") +public class HealthCheckController extends UnRestrictedBaseController { + + private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); + + private static final String HEALTH_CHECK_PATH = "/healthCheck"; + + @Autowired + private DmaapAccessService dmaapAccessService; + + /** + * Model for JSON response with health-check results. + */ + public class HealthStatus { + // Either 200 or 500 + public int statusCode; + // Additional detail in case of error, empty in case of success. + public String message; + + public HealthStatus(int code, String msg) { + this.statusCode = code; + this.message = msg; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int code) { + this.statusCode = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String msg) { + this.message = msg; + } + } + + /** + * Checks application health by making a trivial query to the database. + * + * @param request + * HttpServletRequest + * @return 200 if database access succeeds, 500 if it fails. + */ + @RequestMapping(value = { HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus healthCheck(HttpServletRequest request) { + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + HealthStatus healthStatus = null; + try { + logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); + dmaapAccessService.getDmaapAccessCount(); + healthStatus = new HealthStatus(200, "health check succeeded"); + } catch (Exception ex) { + logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex); + healthStatus = new HealthStatus(500, "health check failed: " + ex.toString()); + } + return healthStatus; + } + + /** + * This implementation does not support suspend/resume. + * + * @param request + * HttpServletRequest + * @return Trivial success + */ + @RequestMapping(value = { + HEALTH_CHECK_PATH + "/suspend" }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus healthCheckSuspend(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + HealthStatus response = new HealthStatus(200, "suspend not implemented"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * This implementation does not support suspend/resume. + * + * @param request + * HttpServletRequest + * @return Trivial success + */ + @RequestMapping(value = { + HEALTH_CHECK_PATH + "/resume" }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus healthCheckResume(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + HealthStatus response = new HealthStatus(200, "resume not implemented"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Answers ping request without checking the application health. + * + * @param request + * HttpServletRequest + * @return Trivial success + */ + @RequestMapping(value = { HEALTH_CHECK_PATH + "/ping" }, method = RequestMethod.GET, produces = "application/json") + public HealthStatus ping(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + HealthStatus response = new HealthStatus(200, "ping received"); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java new file mode 100644 index 0000000..70bc90a --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java @@ -0,0 +1,207 @@ +package org.onap.dcae.dmaapbc.dbcapp.controller; + +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.slf4j.MDC; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * Message Router controller: serves Ajax requests made by Angular scripts on + * pages that show topics and clients. + */ +@Controller +@RequestMapping("/") +public class MessageRouterController extends DbcappRestrictedBaseController { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MessageRouterController.class); + + private static final String TOPIC_PATH = "/mr_topic"; + private static final String CLIENT_PATH = "/mr_client"; + + public MessageRouterController() { + } + + /** + * Answers a request for one page of message router topics. See + * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} + * + * @param request + * HttpServletRequest + * @return One page of MR topics + */ + @RequestMapping(value = { TOPIC_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getMRTopicsByPage(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = getItemListForPageWrapper(request, DmaapDataItem.MR_TOPIC); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Answers a request for one page of message router clients. See + * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} + * + * @param request + * HttpServletRequest + * @return One page of MR clients + */ + @RequestMapping(value = { CLIENT_PATH }, method = RequestMethod.GET, produces = "application/json") + @ResponseBody + public String getMRClientsByPage(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = getItemListForPageWrapper(request, DmaapDataItem.MR_CLIENT); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Adds a topic with the specified information. Expects a JSON block in the + * request body - a Topic object. + * + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { TOPIC_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addTopic(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = addItem(request, DmaapDataItem.MR_TOPIC, HttpServletResponse.SC_CREATED); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Adds a client with the specified information. Expects a JSON block in the + * request body - a MR_Client object. + * + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { CLIENT_PATH }, method = RequestMethod.POST, produces = "application/json") + @ResponseBody + public String addMRClient(HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = addItem(request, DmaapDataItem.MR_CLIENT, HttpServletResponse.SC_CREATED); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Updates a topic with the specified information. Expects a JSON block in + * the request body - a Topic object. + * + * Writes a JSON object as an HTTP response; on success it has a "status" + * and possibly a "data" item; on failure, also has an "error" item. + * + * @param id + * ID of the topic to update + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { TOPIC_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateTopic(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = updateItem(request, DmaapDataItem.MR_TOPIC, Long.toString(id), null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Updates a client with the specified information. Expects a JSON block in + * the request body - a MR_Client object. + * + * Writes a JSON object as an HTTP response; on success it has a "status" + * and possibly a "data" item; on failure, also has an "error" item. + * + * @param id + * ID of the client to update + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { CLIENT_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") + @ResponseBody + public String updateMRClient(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = updateItem(request, DmaapDataItem.MR_CLIENT, Long.toString(id), null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Deletes a topic with the FQTN ID specified as a path parameter. + * + * FQTN is a string of dot-separated names. Spring, in its infinite wisdom, + * truncates extensions on dotted path parameters; e.g., "foo.json" becomes + * "foo". Avoid truncation here with the extra ":.+" incantation at the end. + * + * Writes a JSON object as an HTTP response; on success it only has "status" + * item; on failure, also has an "error" item. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { "/mr_topic/{id:.+}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteTopic(@PathVariable("id") String id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = deleteItem(request, DmaapDataItem.MR_TOPIC, id, 204); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + + /** + * Deletes a client with the mrClientId specified as a path parameter. + * + * Writes a JSON object as an HTTP response; on success it only has "status" + * item; on failure, also has an "error" item. + * + * @param id + * Path parameter with object ID + * @param request + * HttpServletRequest + * @return JSON success/failure response + */ + @RequestMapping(value = { "/mr_client/{id}" }, method = RequestMethod.DELETE, produces = "application/json") + @ResponseBody + public String deleteMRClient(@PathVariable("id") long id, HttpServletRequest request) { + MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); + String response = deleteItem(request, DmaapDataItem.MR_CLIENT, Long.toString(id), null); + MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); + logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); + return response; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java new file mode 100644 index 0000000..31b0fdd --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java @@ -0,0 +1,152 @@ +package org.onap.dcae.dmaapbc.dbcapp.domain; + +import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; + +/** + * Hold an access profile for a DMaaP REST endpoint. Represents one row in the + * DBCA_DMAAP table. + */ +public class DmaapAccess extends DomainVo { + + private static final long serialVersionUID = 6443219375733216340L; + + // parent class defines these fields: + // ID, created, modified, created_id, modified_id + + /** Login ID for user who owns this row */ + private String userId; + /** Nickname for this row */ + private String name; + /** REST API endpoint */ + private String dmaapUrl; + /** Credentials */ + private String mechId; + /** Credentials */ + private String password; + /** User's preferred access profile */ + private boolean selected; + + /** + * Standard POJO no-arg constructor + */ + public DmaapAccess() { + } + + /** + * Copy constructor + * + * @param copy + * Instance to copy + */ + public DmaapAccess(final DmaapAccess copy) { + // Unfortunately DomainVo doesn't provide a copy constructor; + // only the ID field is needed. + this.id = copy.id; + // Our fields + this.userId = copy.userId; + this.name = copy.name; + this.dmaapUrl = copy.dmaapUrl; + this.mechId = copy.mechId; + this.password = copy.password; + this.selected = copy.selected; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDmaapUrl() { + return dmaapUrl; + } + + public void setDmaapUrl(String dmaapUrl) { + this.dmaapUrl = dmaapUrl; + } + + public String getMechId() { + return mechId; + } + + public void setMechId(String mechId) { + this.mechId = mechId; + } + + /** + * Gets the encrypted password. Applications should use + * {@link #decryptPassword()}! + * + * @return The encrypted password + */ + public String getPassword() { + return password; + } + + /** + * Sets the encrypted password. Applications should use + * {@link #encryptPassword(String)}! + * + * @param password + * The encrypted password + */ + public void setPassword(String password) { + this.password = password; + } + + public boolean getSelected() { + return selected; + } + + public void setSelected(boolean selected) { + this.selected = selected; + } + + /** + * A getter that decrypts the value read from the database and returns the + * clear text. Has no side effects. + * + * @return Clear-text password. + * @throws Exception + * If the password cannot be decrypted + */ + public String decryptPassword() throws Exception { + if (password == null) + return null; + return CipherUtil.decrypt(password); + } + + /** + * A setter that encrypts the clear-text in preparation for storing in the + * database. + * + * @param clearText + * The clear-text password to be encrypted + * @throws Exception + * If the password cannot be encrypted + */ + public void encryptPassword(String clearText) throws Exception { + if (clearText == null) { + password = null; + return; + } + password = CipherUtil.encrypt(clearText); + } + + @Override + public String toString() { + return "DmaapAccess[id=" + id + ", url=" + dmaapUrl + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java new file mode 100644 index 0000000..24ba1ff --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java @@ -0,0 +1,32 @@ +package org.onap.dcae.dmaapbc.dbcapp.domain; + +import java.util.Map; + +/** + * Holds a set of String key-value pairs, the JSON version of a + * java.util.Attributes object read from a jar/war file. + */ +public class ManifestTransportModel { + + private Map manifest; + + /** + * Standard POJO no-arg constructor + */ + public ManifestTransportModel() { + } + + public Map getManifest() { + return manifest; + } + + public void setManifest(Map manifest) { + this.manifest = manifest; + } + + @Override + public String toString() { + return "Manifest[size=" + manifest.size() + "]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java new file mode 100644 index 0000000..b252858 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java @@ -0,0 +1,182 @@ +package org.onap.dcae.dmaapbc.dbcapp.rest; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.onap.dcae.dmaapbc.dbcapp.domain.DmaapAccess; +import org.onap.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; +import org.onap.dcae.dmaapbc.dbcapp.service.DmaapAccessService; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +/** + * Provides methods for accessing the DBC microservice via REST using basic HTTP + * authentication. + * + */ +public class DbcUsvcRestClient implements DmaapAccessService { + + public static final String endpointPath = "/dmaap_access"; + private final String baseUrl; + private final RestTemplate restTemplate; + + /** + * Builds a restTemplate that uses basic HTTP authentication for use by all + * methods in this class. + * + * @param webapiUrl + * URL of the web endpoint + * @param user + * user name + * @param pass + * password + */ + public DbcUsvcRestClient(String webapiUrl, String user, String pass) { + if (webapiUrl == null || user == null || pass == null) + throw new IllegalArgumentException("Nulls not permitted"); + + baseUrl = webapiUrl; + URL url = null; + try { + url = new URL(baseUrl); + } catch (MalformedURLException ex) { + throw new RuntimeException("Failed to parse URL", ex); + } + final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort()); + + // Build a client with a credentials provider + CredentialsProvider credsProvider = new BasicCredentialsProvider(); + credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); + HttpClientBuilder clientBuilder = HttpClientBuilder.create(); + CloseableHttpClient httpClient = clientBuilder.setDefaultCredentialsProvider(credsProvider).build(); + + // Create request factory with our superpower client + HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( + httpHost); + requestFactory.setHttpClient(httpClient); + + // Put the factory in the template + this.restTemplate = new RestTemplate(); + restTemplate.setRequestFactory(requestFactory); + } + + /** + * Gets the manifest from the micro service. + */ + @Override + public ManifestTransportModel getManifest() { + String url = baseUrl + "/manifest"; + ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, + ManifestTransportModel.class); + ManifestTransportModel response = daResponse.getBody(); + return response; + } + + /** + * Gets the count of DMaaP access profiles. + * + * @return Number of access profiles in the database. + */ + public int getDmaapAccessCount() { + String url = baseUrl + "/count_dmaap_access"; + ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, + DbcUsvcRestResponse.class); + DbcUsvcRestResponse response = daResponse.getBody(); + return response.getStatus(); + } + + /** + * Gets the DMaaP access profiles for the specified userId. + * + * @param userId + * User ID + * @return List of access profiles + */ + @Override + public List getDmaapAccessList(final String userId) { + String url = baseUrl + endpointPath + "?userId=" + userId; + ResponseEntity> daResponse = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + List daList = daResponse.getBody(); + return daList; + } + + /** + * Gets the specified DMaaP access profile. + */ + @Override + public DmaapAccess getDmaapAccess(Long dmaapId) { + String url = baseUrl + endpointPath + "?dmaapId=" + dmaapId; + ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, + new ParameterizedTypeReference() { + }); + DmaapAccess da = daResponse.getBody(); + return da; + } + + /** + * POSTs or PUTs the DMaaP access profile as needed, based on whether the + * object's ID field is set. If not set it creates a new row; if set, it + * updates a row in the remote service table. + * + * @param dmaapAccess + * Access profile + */ + @Override + public void saveDmaapAccess(final DmaapAccess dmaapAccess) { + if (dmaapAccess.getId() == null) { + String url = baseUrl + endpointPath; + restTemplate.postForObject(url, dmaapAccess, String.class); + } else { + String url = baseUrl + endpointPath + "/" + Long.toString(dmaapAccess.getId()); + restTemplate.put(url, dmaapAccess); + } + } + + /** + * Deletes the DMaaP access profile row in the remote service table with the + * specified id. + * + * @param id + * Access profile ID + */ + @Override + public void deleteDmaapAccess(final Long id) { + String url = baseUrl + endpointPath + "/" + Long.toString(id); + restTemplate.delete(url); + } + + /** + * Simple test + * + * @param args + * UserID + * @throws Exception + * On any failure + */ + public static void main(String[] args) throws Exception { + if (args.length != 1) + throw new IllegalArgumentException("Single argument expected: userid"); + DbcUsvcRestClient client = new DbcUsvcRestClient("http://localhost:8081/dbus", "dbus_user", "dbus_pass"); + final String userId = args[0]; + System.out.println("Requesting profiles for user " + userId); + List access = client.getDmaapAccessList(userId); + if (access == null) + System.err.println("Received null"); + else + for (DmaapAccess da : access) + System.out.println(da); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java new file mode 100644 index 0000000..e9284a6 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java @@ -0,0 +1,42 @@ +package org.onap.dcae.dmaapbc.dbcapp.rest; + +/** + * Models the responses sent by the micro service in JSON format. + */ +public class DbcUsvcRestResponse { + + private int status; + private String data, error, exception; + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getException() { + return exception; + } + + public void setException(String exception) { + this.exception = exception; + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000..14ddd93 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -0,0 +1,46 @@ +package org.onap.dcae.dmaapbc.dbcapp.rest; + +import java.net.URI; + +import org.apache.http.HttpHost; +import org.apache.http.client.AuthCache; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +/** + * Utility class to enable Basic HTTP Authentication with Spring REST templates. + * + * From: + * http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1/ + */ +public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { + + private HttpHost host; + + public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) { + super(); + this.host = host; + } + + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return createHttpContext(); + } + + private HttpContext createHttpContext() { + // Create AuthCache instance + AuthCache authCache = new BasicAuthCache(); + // Generate BASIC scheme object and add it to the local auth cache + BasicScheme basicAuth = new BasicScheme(); + authCache.put(host, basicAuth); + + // Add AuthCache to the execution context + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); + return localcontext; + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java new file mode 100644 index 0000000..38124a2 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java @@ -0,0 +1,63 @@ +package org.onap.dcae.dmaapbc.dbcapp.service; + +import java.util.List; + +import org.onap.dcae.dmaapbc.dbcapp.domain.DmaapAccess; +import org.onap.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; + +/** + * Defines methods to manipulate the database table with DmaapAccess domain + * objects. No method throws a checked exception, in keeping with the Spring + * philosophy of throwing unchecked exceptions. + */ +public interface DmaapAccessService { + + /** + * Gets build information. + * + * @return List of key-value pairs; implementations may return null. + */ + ManifestTransportModel getManifest(); + + /** + * Gets the number of Dmaap Access entries. + * + * @return Number of rows in the table. + */ + int getDmaapAccessCount(); + + /** + * Gets all DMaaP access rows in the table for the specified user. + * + * @param userId + * Login ID of the user + * @return List of DMaaP instance objects, which may be empty. + */ + List getDmaapAccessList(String userId); + + /** + * Gets the DMaaP access object with the specified row ID. + * + * @param dmaapId + * Access profile ID + * @return DMaap instance; null if none exists. + */ + DmaapAccess getDmaapAccess(Long dmaapId); + + /** + * Creates a new managed object (a new row in the table). + * + * @param dmaap + * DMaaP instance to create. + */ + void saveDmaapAccess(DmaapAccess dmaap); + + /** + * Deletes the DMaaP access row with the specified ID. + * + * @param dmaapId + * Access profile ID + */ + void deleteDmaapAccess(Long dmaapId); + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java new file mode 100644 index 0000000..96fb152 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java @@ -0,0 +1,97 @@ +package org.onap.dcae.dmaapbc.dbcapp.service; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.onap.dcae.dmaapbc.dbcapp.domain.DmaapAccess; +import org.onap.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * Hibernate-assisted methods to manipulate the DBCA_DMAAP table. + */ +@Service("dmaapAccessService") +@Transactional +public class DmaapAccessServiceImpl implements DmaapAccessService { + + @Autowired + private DataAccessService dataAccessService; + + public DataAccessService getDataAccessService() { + return dataAccessService; + } + + public void setDataAccessService(DataAccessService dataAccessService) { + this.dataAccessService = dataAccessService; + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#getManifest() + */ + @Override + public ManifestTransportModel getManifest() { + return null; + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccessCount() + */ + @SuppressWarnings("unchecked") + @Override + public int getDmaapAccessCount() { + List accesses = (List) getDataAccessService().getList(DmaapAccess.class, null); + return accesses.size(); + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccessList(java.lang.String) + */ + @SuppressWarnings("unchecked") + @Override + public List getDmaapAccessList(String userId) { + List restrictionsList = new ArrayList(); + Criterion criterion1 = Restrictions.eq("userId", userId); + restrictionsList.add(criterion1); + List accesses = (List) getDataAccessService().getList(DmaapAccess.class, null, + restrictionsList, null); + return accesses; + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccess(java.lang.Long) + */ + @Override + public DmaapAccess getDmaapAccess(Long dmaapId) { + return (DmaapAccess) getDataAccessService().getDomainObject(DmaapAccess.class, dmaapId, null); + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#saveDmaapAccess(org.onap.dmaapbc.dbcapp.domain.DmaapAccess) + */ + @Override + public void saveDmaapAccess(DmaapAccess dmaap) { + getDataAccessService().saveDomainObject(dmaap, null); + } + + /* + * (non-Javadoc) + * @see org.onap.dmaapbc.dbcapp.service.DmaapAccessService#deleteDmaapAccess(java.lang.Long) + */ + @Override + public void deleteDmaapAccess(Long dmaapId) { + DmaapAccess dmaapAccess = getDmaapAccess(dmaapId); + if (dmaapAccess != null) + getDataAccessService().deleteDomainObject(dmaapAccess, null); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/util/DbcappProperties.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/util/DbcappProperties.java new file mode 100644 index 0000000..c6db620 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/dbcapp/util/DbcappProperties.java @@ -0,0 +1,71 @@ +package org.onap.dcae.dmaapbc.dbcapp.util; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; + +/** + * Publishes a list of constants and methods to access the properties that are + * read by Spring from the specified configuration file(s). + * + * Should be used like this (and never in a constructor): + * + *
+ * @Autowired
+ * DbcappProperties properties;
+ * 
+ */ +@Configuration +@PropertySource(value = { "${container.classpath:}/WEB-INF/dbcapp/dbcapp.properties" }) +public class DbcappProperties { + + public static final String DMAAP_REST_URL_LIST = "dmaap.rest.url.list"; + public static final String DMAAP_MECHID_NAME = "dmaap.mechid.name"; + public static final String DMAAP_MECHID_PASSWORD = "dmaap.mechid.password"; + public static final String PROFILE_ACCESS_METHOD = "profile.access.method"; + public static final String PROFILE_USVC_URL = "profile.microservice.url"; + public static final String PROFILE_USVC_USER = "profile.microservice.user.name"; + public static final String PROFILE_USVC_PASS = "profile.microservice.user.password"; + public static final String DMAAP_PII_TYPE_LIST = "dmaap.pii.type.list"; + + private Environment environment; + + public DbcappProperties() { + } + + protected Environment getEnvironment() { + return environment; + } + + @Autowired + public void setEnvironment(final Environment environment) { + this.environment = environment; + } + + public boolean containsProperty(String key) { + return environment.containsProperty(key); + } + + public String getProperty(String key) { + return environment.getRequiredProperty(key); + } + + /** + * Gets the values for a comma-separated list property value as a String + * array. + * + * @param key + * Property key + * @return Array of values with leading and trailing whitespace removed; + * null if key is not found. + */ + public String[] getCsvListProperty(final String key) { + String listVal = getProperty(key); + if (listVal == null) + return null; + String[] vals = listVal.split("\\s*,\\s*"); + return vals; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Node.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Node.java new file mode 100644 index 0000000..66e6a21 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Node.java @@ -0,0 +1,87 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP Data Router node. + */ +public class DR_Node extends DmaapObject { + + private String fqdn; + /** dcaeLocation where node VM is deployed */ + private String dcaeLocationName; + /** + * name for this VM (sometimes this is a local VM name and may be different + * than FQDN) + */ + private String hostName; + /** version of Node software package */ + private String version; + + public DR_Node() { + } + + public DR_Node(String lastMod, Dmaap_Status status, String fqdn, String dcaeLocationName, String hostName, + String version) { + super(lastMod, status); + this.fqdn = fqdn; + this.dcaeLocationName = dcaeLocationName; + this.hostName = hostName; + this.version = version; + } + + public String getFqdn() { + return fqdn; + } + + public void setFqdn(String fqdn) { + this.fqdn = fqdn; + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getHostName() { + return hostName; + } + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @Override + public String toString() { + return "DR_Node[fqdn=" + fqdn + ", dcaeLocationName=" + dcaeLocationName + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Pub.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Pub.java new file mode 100644 index 0000000..cce2ae7 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Pub.java @@ -0,0 +1,96 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP Data Router publisher. + */ +public class DR_Pub extends DmaapObject { + + /** dcaeLocation tag where this publisher is deployed */ + private String dcaeLocationName; + /** name used for basic authentication to DR */ + private String username; + /** password used for basic authentication to DR */ + private String userpwd; + /** tag of feed for which this publisher is a source */ + private String feedId; + /** unique id of a DCAE publisher (generated by Data Router PROV) */ + private String pubId; + + public DR_Pub() { + } + + public DR_Pub(Dmaap_Status status, String lastMod, String dcaeLocationName, String username, String userpwd, + String feedId, String pubId) { + super(lastMod, status); + this.dcaeLocationName = dcaeLocationName; + this.username = username; + this.userpwd = userpwd; + this.feedId = feedId; + this.pubId = pubId; + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUserpwd() { + return userpwd; + } + + public void setUserpwd(String userpwd) { + this.userpwd = userpwd; + } + + public String getFeedId() { + return feedId; + } + + public void setFeedId(String feedId) { + this.feedId = feedId; + } + + public String getPubId() { + return pubId; + } + + public void setPubId(String pubId) { + this.pubId = pubId; + } + + @Override + public String toString() { + return "DR_Pub[dcaeLocationName=" + dcaeLocationName + ", feedId=" + feedId + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Sub.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Sub.java new file mode 100644 index 0000000..b74b4ee --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DR_Sub.java @@ -0,0 +1,152 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP Data Router subscriber. + */ +public class DR_Sub extends DmaapObject { + + /** Tag where this publisher is deployed */ + private String dcaeLocationName; + /** name used for basic authentication from DR */ + private String username; + /** password used for basic authentication from DR */ + private String userpwd; + /** tag of feed for which this publisher is a source */ + private String feedId; + /** URL used by DR to deliver files to this subscriber */ + private String deliveryURL; + /** URL for accessing the transaction log for this susbcriber */ + private String logURL; + /** unique ID for a subscriber in this DR environment */ + private String subId; + /** TODO */ + private boolean suspended; + /** TODO */ + private boolean use100; + /** TODO */ + private String owner; + + public DR_Sub() { + } + + public DR_Sub(String lastMod, Dmaap_Status status, String dcaeLocationName, String username, String userpwd, + String feedId, String deliveryURL, String logURL, String subId, boolean suspended, boolean use100, + String owner) { + super(lastMod, status); + this.dcaeLocationName = dcaeLocationName; + this.username = username; + this.userpwd = userpwd; + this.feedId = feedId; + this.deliveryURL = deliveryURL; + this.logURL = logURL; + this.subId = subId; + this.suspended = suspended; + this.use100 = use100; + this.owner = owner; + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUserpwd() { + return userpwd; + } + + public void setUserpwd(String userpwd) { + this.userpwd = userpwd; + } + + public String getFeedId() { + return feedId; + } + + public void setFeedId(String feedId) { + this.feedId = feedId; + } + + public String getDeliveryURL() { + return deliveryURL; + } + + public void setDeliveryURL(String deliveryURL) { + this.deliveryURL = deliveryURL; + } + + public String getLogURL() { + return logURL; + } + + public void setLogURL(String logURL) { + this.logURL = logURL; + } + + public String getSubId() { + return subId; + } + + public void setSubId(String subId) { + this.subId = subId; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public boolean isSuspended() { + return suspended; + } + + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } + + public boolean isUse100() { + return use100; + } + + public void setUse100(boolean use100) { + this.use100 = use100; + } + + @Override + public String toString() { + return "DR_Sub[dcaeLocationName=" + dcaeLocationName + ", feedId=" + feedId + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DcaeLocation.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DcaeLocation.java new file mode 100644 index 0000000..400044d --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DcaeLocation.java @@ -0,0 +1,96 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP DCAE location. + */ +public class DcaeLocation extends DmaapObject { + + public enum Dcae_Status { + EMPTY, NEW, STAGED, VALID, INVALID + } + + /** + * network location code used to identify the location. + */ + private String clli; + /** + * indicator of DCAE layer. Either opendcae-central or opendcae-local-ntc + */ + private String dcaeLayer; + /** + * unique name of this dcaeLocation. Value should match what DCAE Controller + * uses. + */ + private String dcaeLocationName; + /** determines where within the OpenStack deployment the edge exists */ + private String openStackAvailabilityZone; + + public DcaeLocation() { + } + + public DcaeLocation(String lastMod, Dmaap_Status status, String clli, String dcaeLayer, String dcaeLocationName, + String openStackAvailabilityZone) { + super(lastMod, status); + this.clli = clli; + this.dcaeLayer = dcaeLayer; + this.dcaeLocationName = dcaeLocationName; + this.openStackAvailabilityZone = openStackAvailabilityZone; + } + + public String getClli() { + return clli; + } + + public void setClli(String clli) { + this.clli = clli; + } + + public String getDcaeLayer() { + return dcaeLayer; + } + + public void setDcaeLayer(String dcaeLayer) { + this.dcaeLayer = dcaeLayer; + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getOpenStackAvailabilityZone() { + return openStackAvailabilityZone; + } + + public void setOpenStackAvailabilityZone(String openStackAvailabilityZone) { + this.openStackAvailabilityZone = openStackAvailabilityZone; + } + + @Override + public String toString() { + return "DcaeLocation[dcaeLocationName=" + dcaeLocationName + ", dcaeLayer=" + dcaeLayer + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Dmaap.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Dmaap.java new file mode 100644 index 0000000..f30a843 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Dmaap.java @@ -0,0 +1,141 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP instance. + */ +public class Dmaap extends DmaapObject { + + /** the version of DMaaP BC software */ + private String version; + /** the root portion of the topic namespace */ + private String topicNsRoot; + /** + * a unique identifier for this instance. + */ + private String dmaapName; + /** URL for DR Provisioning Server */ + private String drProvUrl; + /** + * topic name used by MR Bridge Admin to communicate which topics to + * replicate + */ + private String bridgeAdminTopic; + /** used by DCAE Controller to upload event logs */ + private String loggingUrl; + /** used by DCAE Controller to authenticate inter-node messages */ + private String nodeKey; + /** used by DCAE Controller to set up ssh access to VMs */ + private String accessKeyOwner; + + public Dmaap() { + } + + public Dmaap(String lastMod, Dmaap_Status status, String version, String topicNsRoot, String dmaapName, + String drProvUrl, String loggingUrl, String nodeKey, String accessKeyOwner) { + super(lastMod, status); + this.version = version; + this.topicNsRoot = topicNsRoot; + this.dmaapName = dmaapName; + this.drProvUrl = drProvUrl; + this.loggingUrl = loggingUrl; + this.nodeKey = nodeKey; + this.accessKeyOwner = accessKeyOwner; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTopicNsRoot() { + return topicNsRoot; + } + + public void setTopicNsRoot(String topicNsRoot) { + this.topicNsRoot = topicNsRoot; + } + + public String getDmaapName() { + return dmaapName; + } + + public void setDmaapName(String dmaapName) { + this.dmaapName = dmaapName; + } + + public String getDrProvUrl() { + return drProvUrl; + } + + public void setDrProvUrl(String drProvUrl) { + this.drProvUrl = drProvUrl; + } + + public String getLogginUrl() { + return loggingUrl; + } + + public void setLogginUrl(String logginUrl) { + this.loggingUrl = logginUrl; + } + + public String getNodeKey() { + return nodeKey; + } + + public void setNodeKey(String nodeKey) { + this.nodeKey = nodeKey; + } + + public String getAccessKeyOwner() { + return accessKeyOwner; + } + + public void setAccessKeyOwner(String accessKeyOwner) { + this.accessKeyOwner = accessKeyOwner; + } + + public String getLoggingUrl() { + return loggingUrl; + } + + public void setLoggingUrl(String loggingUrl) { + this.loggingUrl = loggingUrl; + } + + public String getBridgeAdminTopic() { + return bridgeAdminTopic; + } + + public void setBridgeAdminTopic(String bridgeAdminTopic) { + this.bridgeAdminTopic = bridgeAdminTopic; + } + + @Override + public String toString() { + return "Dmaap[dmaapName=" + dmaapName + ", version=" + version + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DmaapObject.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DmaapObject.java new file mode 100644 index 0000000..15fdd1f --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/DmaapObject.java @@ -0,0 +1,70 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Parent class for all DMaaP BC models. + */ +public abstract class DmaapObject { + + public enum Dmaap_Status { + EMPTY, NEW, STAGED, VALID, INVALID, DELETED + } + + /** time stamp when object was last modified */ + private String lastMod; + /** indicator of health of this object using values common in this API */ + private Dmaap_Status status; + /** TODO */ + private String type; + + public DmaapObject() { + } + + public DmaapObject(String lastMod, Dmaap_Status status) { + this.lastMod = lastMod; + this.status = status; + } + + public String getLastMod() { + return lastMod; + } + + public void setLastMod(String lastMod) { + this.lastMod = lastMod; + } + + public Dmaap_Status getStatus() { + return status; + } + + public void setStatus(Dmaap_Status status) { + this.status = status; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/ErrorResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/ErrorResponse.java new file mode 100644 index 0000000..9ac67d2 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/ErrorResponse.java @@ -0,0 +1,65 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP Bus Controller error response. + * + * This inherits some fields (e.g., lastMod and status) that are not used. + */ +public class ErrorResponse extends DmaapObject { + + private Integer code; + private String message; + private String fields; + + public ErrorResponse() { + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getFields() { + return fields; + } + + public void setFields(String fields) { + this.fields = fields; + } + + @Override + public String toString() { + return "ErrorResponse[code=" + code + ", message=" + message + ", fields=" + fields + "]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Feed.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Feed.java new file mode 100644 index 0000000..9d58228 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Feed.java @@ -0,0 +1,193 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * Bean that models a DMaaP Data Router feed. + */ +public class Feed extends DmaapObject { + + public enum Feed_Status { + EMPTY, NEW, STAGED, VALID, INVALID, DELETED + } + + /** unique id assigned by the DR PROV server for this feed */ + private String feedId; + /** name of feed. Combined with feedVersion must be unique */ + private String feedName; + /** version of feed. Combined with feedName must be unique */ + private String feedVersion; + /** description */ + private String feedDescription; + /** ASPR classification */ + private String asprClassification; + /** provisioning URL for adding subscribers to this feed */ + private String subscribeURL; + /** URL publisher use to connect to DR */ + private String publishURL; + /** URL for transaction log for this feed */ + private String logURL; + /** indicator of whether the feed is suspended */ + private boolean suspended; + /** what identity owns this feed */ + private String owner; + /** id of format description of feed content */ + private String formatUuid; + /** a set of publishers for this feed */ + private List pubs; + /** a set of subscribers for this feed */ + private List subs; + + public Feed() { + this.pubs = new ArrayList(); + this.subs = new ArrayList(); + } + + public Feed(Dmaap_Status status, String lastMod, String feedName, String feedVersion, String feedDescription, + String asprClassification, String subscribeURL, String publishURL, String logURL, boolean suspended, + String owner, String formatUuid) { + super(lastMod, status); + this.feedName = feedName; + this.feedVersion = feedVersion; + this.feedDescription = feedDescription; + this.asprClassification = asprClassification; + this.subscribeURL = subscribeURL; + this.publishURL = publishURL; + this.logURL = logURL; + this.suspended = suspended; + this.owner = owner; + this.formatUuid = formatUuid; + this.pubs = new ArrayList(); + this.subs = new ArrayList(); + } + + public String getFeedId() { + return feedId; + } + + public void setFeedId(String feedId) { + this.feedId = feedId; + } + + public String getFeedName() { + return feedName; + } + + public void setFeedName(String feedName) { + this.feedName = feedName; + } + + public String getFeedVersion() { + return feedVersion; + } + + public void setFeedVersion(String feedVersion) { + this.feedVersion = feedVersion; + } + + public String getFeedDescription() { + return feedDescription; + } + + public void setFeedDescription(String feedDescription) { + this.feedDescription = feedDescription; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getAsprClassification() { + return asprClassification; + } + + public void setAsprClassification(String asprClassification) { + this.asprClassification = asprClassification; + } + + public String getSubscribeURL() { + return subscribeURL; + } + + public void setSubscribeURL(String subscribeURL) { + this.subscribeURL = subscribeURL; + } + + public String getPublishURL() { + return publishURL; + } + + public void setPublishURL(String publishURL) { + this.publishURL = publishURL; + } + + public String getLogURL() { + return logURL; + } + + public void setLogURL(String logURL) { + this.logURL = logURL; + } + + public boolean isSuspended() { + return suspended; + } + + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } + + public String getFormatUuid() { + return formatUuid; + } + + public void setFormatUuid(String formatUuid) { + this.formatUuid = formatUuid; + } + + public List getPubs() { + return pubs; + } + + public void setPubs(List pubs) { + this.pubs = pubs; + } + + public List getSubs() { + return subs; + } + + public void setSubs(List subs) { + this.subs = subs; + } + + @Override + public String toString() { + return "Feed[feedId=" + feedId + ", feedName=" + feedName + ", feedVersion=" + feedVersion + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Client.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Client.java new file mode 100644 index 0000000..7fcee37 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Client.java @@ -0,0 +1,110 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +/** + * Bean that models a DMaaP Message Router client. + */ +public class MR_Client extends DmaapObject { + + /** dcaeLocation tag where this client is deployed */ + private String dcaeLocationName; + /** fully qualified topic name */ + private String fqtn; + /** + * name of role of client which will be + * granted the AAF permission associated with any action + */ + private String clientRole; + /** an array of actions. Current possibilities are view, pub, sub */ + private String[] action; + /** unique handle for this client, generated by DMaaP Bus Controller */ + private String mrClientId; + /** TODO */ + private String topicURL; + + public MR_Client() { + } + + public MR_Client(String lastMod, Dmaap_Status status, String dcaeLocationName, String fqtn, String clientRole, + String[] action, String mrClientId, String topicURL) { + super(lastMod, status); + this.dcaeLocationName = dcaeLocationName; + this.fqtn = fqtn; + this.clientRole = clientRole; + this.action = action; + this.mrClientId = mrClientId; + this.topicURL = topicURL; + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getFqtn() { + return fqtn; + } + + public void setFqtn(String fqtn) { + this.fqtn = fqtn; + } + + public String getClientRole() { + return clientRole; + } + + public void setClientRole(String clientRole) { + this.clientRole = clientRole; + } + + public String[] getAction() { + return action; + } + + public void setAction(String[] action) { + this.action = action; + } + + public String getMrClientId() { + return mrClientId; + } + + public void setMrClientId(String mrClientId) { + this.mrClientId = mrClientId; + } + + public String getTopicURL() { + return topicURL; + } + + public void setTopicURL(String topicURL) { + this.topicURL = topicURL; + } + + @Override + public String toString() { + return "MR_Client[dcaeLocationName=" + dcaeLocationName + ", fqtn=" + fqtn + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Cluster.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Cluster.java new file mode 100644 index 0000000..90327ab --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/MR_Cluster.java @@ -0,0 +1,108 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +import java.util.List; + +/** + * Bean that models a DMaaP Message Router cluster. + */ +public class MR_Cluster extends DmaapObject { + + /** dcaeLocation where cluster VMs are deployed */ + private String dcaeLocationName; + /** DNS name used by MR clients for this cluster */ + private String fqdn; + /** an array of hosts that are part of the MR Cluster. */ + private List hosts; + /** TODO */ + private String topicPort; + /** TODO */ + private String topicProtocol; + + public MR_Cluster() { + } + + /** + * @param status + * Status + * @param lastMod + * Last modification + * @param dcaeLocationName + * dcaeLocation where cluster VMs are deployed + * @param fqdn + * DNS name used by MR clients for this cluster + * @param hosts + * an array of hosts that are part of the MR Cluster + */ + public MR_Cluster(Dmaap_Status status, String lastMod, String dcaeLocationName, String fqdn, final String[] hosts) { + super(lastMod, status); + this.dcaeLocationName = dcaeLocationName; + this.fqdn = fqdn; + for (String h : hosts) + this.hosts.add(h); + } + + public String getDcaeLocationName() { + return dcaeLocationName; + } + + public void setDcaeLocationName(String dcaeLocationName) { + this.dcaeLocationName = dcaeLocationName; + } + + public String getFqdn() { + return fqdn; + } + + public void setFqdn(String fqdn) { + this.fqdn = fqdn; + } + + public List getHosts() { + return hosts; + } + + public void setHosts(List hosts) { + this.hosts = hosts; + } + + public String getTopicPort() { + return topicPort; + } + + public void setTopicPort(String topicPort) { + this.topicPort = topicPort; + } + + public String getTopicProtocol() { + return topicProtocol; + } + + public void setTopicProtocol(String topicProtocol) { + this.topicProtocol = topicProtocol; + } + + @Override + public String toString() { + return "MR_Cluster[dcaeLocationName=" + dcaeLocationName + ", fqdn=" + fqdn + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Topic.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Topic.java new file mode 100644 index 0000000..d2965fd --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/dcae/dmaapbc/model/Topic.java @@ -0,0 +1,144 @@ +/*- + * ================================================================================ + * DCAE DMaaP Bus Controller Models + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.dcae.dmaapbc.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * Bean that models a DMaaP Message Router topic. + */ +public class Topic extends DmaapObject { + + /** fully qualified topic name (topic_ns_root.environment.topic_name) */ + private String fqtn; + /** application supplied value for topicName */ + private String topicName; + /** description of topic */ + private String topicDescription; + /** what identity owns this topic */ + private String owner; + /** flag to MR indicating whether transactions are enabled for this topic */ + private String tnxEnabled; + /** id of format description of feed content */ + private String formatUuid; + /** indicates what replication pattern, if any, is desired */ + private String replicationCase; + /** name of a specific Global MR host */ + private String globalMrURL; + /** a set of publishers and subscribers for this topic */ + private List clients; + + public Topic() { + this.clients = new ArrayList(); + } + + public Topic(String lastMod, Dmaap_Status status, String fqtn, String topicName, String topicDescription, + String owner, String tnxEnabled, String formatUuid, String replicationCase, String globalMrURL) { + super(lastMod, status); + this.fqtn = fqtn; + this.topicName = topicName; + this.topicDescription = topicDescription; + this.owner = owner; + this.tnxEnabled = tnxEnabled; + this.formatUuid = formatUuid; + this.replicationCase = replicationCase; + this.globalMrURL = globalMrURL; + this.clients = new ArrayList(); + } + + public String getFqtn() { + return fqtn; + } + + public void setFqtn(String fqtn) { + this.fqtn = fqtn; + } + + public String getTopicName() { + return topicName; + } + + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + public String getTopicDescription() { + return topicDescription; + } + + public void setTopicDescription(String topicDescription) { + this.topicDescription = topicDescription; + } + + public String getTnxEnabled() { + return tnxEnabled; + } + + public void setTnxEnabled(String tnxEnabled) { + this.tnxEnabled = tnxEnabled; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getFormatUuid() { + return formatUuid; + } + + public void setFormatUuid(String formatUuid) { + this.formatUuid = formatUuid; + } + + public List getClients() { + return clients; + } + + public void setClients(List clients) { + this.clients = clients; + } + + public String getReplicationCase() { + return replicationCase; + } + + public void setReplicationCase(String replicationCase) { + this.replicationCase = replicationCase; + } + + public String getGlobalMrURL() { + return globalMrURL; + } + + public void setGlobalMrURL(String globalMrURL) { + this.globalMrURL = globalMrURL; + } + + @Override + public String toString() { + return "Topic[fqtn=" + fqtn + ", topicName=" + topicName + ", ...]"; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/model/Result.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/model/Result.java new file mode 100644 index 0000000..22b50a8 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/model/Result.java @@ -0,0 +1,18 @@ +package org.onap.fusionapp.model; + +public class Result { + private String result; + + public Result(String result) { + this.result = result; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java new file mode 100644 index 0000000..1892553 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/service/AdminAuthExtension.java @@ -0,0 +1,13 @@ +package org.onap.fusionapp.service; + +import org.openecomp.portalsdk.core.domain.User; + +//@Service("adminAuthExtension") +//@Transactional +public class AdminAuthExtension { + + public void saveUserExtension(User user){ + //app's developer implement their own logic here, like updating app's related tables + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java new file mode 100644 index 0000000..9dc77c4 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/onap/fusionapp/util/CustomLoggingFilter.java @@ -0,0 +1,37 @@ +package org.onap.fusionapp.util; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.filter.Filter; +import ch.qos.logback.core.spi.FilterReply; + +/** + * Custom Filter class bind with logback.xml configuration file to strip out + * certain log messages coming out of special packages or classes. + * + */ +public class CustomLoggingFilter extends Filter { + + /** + * Custom Filter is added to strip out the continuous U-EB logging messages + * But make sure we log the ERROR and WARNING Level messages. + * + * @param event + * Logging event + */ + @Override + public FilterReply decide(ILoggingEvent event) { + try { + if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) + && (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) + && (event.getLoggerName().contains("com.att.nsa") + || event.getLoggerName().contains("org.apache.http"))) { + return FilterReply.DENY; + } else { + return FilterReply.NEUTRAL; + } + } catch (Exception e) { + return FilterReply.NEUTRAL; + } + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/DmaapBcRestClient.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/DmaapBcRestClient.java deleted file mode 100644 index 39d28dd..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/DmaapBcRestClient.java +++ /dev/null @@ -1,1495 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller REST Client - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.client; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.client.utils.URIBuilder; -import org.openecomp.dcae.dmaapbc.model.DR_Node; -import org.openecomp.dcae.dmaapbc.model.DR_Pub; -import org.openecomp.dcae.dmaapbc.model.DR_Sub; -import org.openecomp.dcae.dmaapbc.model.DcaeLocation; -import org.openecomp.dcae.dmaapbc.model.Dmaap; -import org.openecomp.dcae.dmaapbc.model.DmaapObject; -import org.openecomp.dcae.dmaapbc.model.ErrorResponse; -import org.openecomp.dcae.dmaapbc.model.Feed; -import org.openecomp.dcae.dmaapbc.model.MR_Client; -import org.openecomp.dcae.dmaapbc.model.MR_Cluster; -import org.openecomp.dcae.dmaapbc.model.Topic; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Provides methods to communicate with the DMaaP Bus Controller REST API. This - * hides all JSON; instead it accepts and returns Java objects. - */ -public class DmaapBcRestClient extends SimpleRestClientBase { - - private static Logger logger = LoggerFactory.getLogger(DmaapBcRestClient.class); - - // Omit leading and trailing slashes here - private static final String DCAELOCATIONS = "dcaeLocations"; - private static final String DMAAP = "dmaap"; - private static final String DR_NODES = "dr_nodes"; - private static final String DR_PUBS = "dr_pubs"; - private static final String DR_SUBS = "dr_subs"; - private static final String FEEDS = "feeds"; - private static final String TOPICS = "topics"; - private static final String MR_CLUSTERS = "mr_clusters"; - private static final String MR_CLIENTS = "mr_clients"; - - /** - * Reusable JSON (de)serializer - */ - private final ObjectMapper mapper; - - /** - * URL of the DMAAP REST endpoint - */ - private final String dmaapRestUrl; - - /** - * Constructor that configures the client for the specified endpoint using - * no authentication. - * - * @param dmaapRestUrl - * URL of the endpoint - */ - public DmaapBcRestClient(final String dmaapRestUrl) { - super(); - this.dmaapRestUrl = dmaapRestUrl; - this.mapper = new ObjectMapper(); - // Don't serialize null-value fields in objects - this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - /** - * Constructor that onfigures the client for the specified endpoint using - * the specified username and password for basic HTTP authentication. - * - * @param dmaapRestUrl - * URL of the endpoint - * @param username - * User name - * @param password - * Password - */ - public DmaapBcRestClient(final String dmaapRestUrl, final String username, final String password) { - super(username, password); - this.dmaapRestUrl = dmaapRestUrl; - this.mapper = new ObjectMapper(); - // Don't serialize null-value fields in objects - this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - /** - * Configures the behavior of the JSON deserializer used to build business - * objects (e.g., a Feed) from REST responses. - * - * @param failOnUnknownProperties - * If true, rejects JSON responses with unexpected fields - * (default behavior); if false, ignores unexpected fields. - */ - public void setFailOnUnknownProperties(boolean failOnUnknownProperties) { - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); - } - - /** - * Gets the DMaaP endpoint URL that is used by methods in this class. - * - * @return dmaapEndpointUrl - */ - public String getDmaapRestUrl() { - return this.dmaapRestUrl; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of DCAE locations. - * - * @return List of DmaapObject: list contains DcaeLocation object(s) on - * success; a single ErrorResponse object if the remote site rejects - * the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getDcaeLocations() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DCAELOCATIONS)); - logger.debug("getDcaeLocations: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDcaeLocations: unexpected null response"); - - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getDcaeLocations: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets the DCAE location with the specified name. - * - * @param locName - * name of the location to get - * @return DmaapObject: a DcaeLocation object on success; an ErrorResponse - * object if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getDcaeLocation(final String locName) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DCAELOCATIONS, locName)); - logger.debug("getDcaeLocation: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDcaeLocation: unexpected null response"); - - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); - } catch (Exception ex) { - logger.debug("getDcaeLocation: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a DCAE location in DMaaP. - * - * @param dcaeLoc - * DcaeLocation to be created - * @return Status and response: expect 200 and a DcaeLocation on success; a - * code and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postDcaeLocation(DcaeLocation dcaeLoc) throws Exception { - String jsonBody = mapper.writeValueAsString(dcaeLoc); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DCAELOCATIONS), jsonBody); - if (hsr == null) - throw new Exception("postDcaeLocation: unexpected null response"); - logger.debug("postDcaeLocation: resp is {}", hsr); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postDcaeLocation: null response body"); - return response; - } - try { - DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDcaeLocation: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the DCAE location with the specified name. - * - * @param locName - * Name of the location to delete - * @return Status and response: expect 204 and a DcaeLocation on success; a - * code and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteDcaeLocation(final String locName) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DCAELOCATIONS, locName)); - logger.debug("deleteDcaeLocation: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteDcaeLocation: unexpected null response"); - // Returns a loc on success, error message string on error. - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteDcaeLocation: null response body"); - return response; - } - try { - DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteDcaeLocation: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a DCAE location. - * - * @param dcaeLoc - * DCAE Location to be updated - * @return Status and response; expect 200 and a DcaeLocation on success, a - * string error on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putDcaeLocation(DcaeLocation dcaeLoc) throws Exception { - String jsonBody = mapper.writeValueAsString(dcaeLoc); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DCAELOCATIONS, dcaeLoc.getDcaeLocationName()), - jsonBody); - logger.debug("putDcaeLocation: resp is {}", hsr); - if (hsr == null) - throw new Exception("putDcaeLocation: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putDcaeLocation: null response body"); - return response; - } - try { - DcaeLocation resp = mapper.readValue(hsr.getResponseString(), DcaeLocation.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putDcaeLocation: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets the DMAAP instance for this DCAE deployment. - * - * @return DmaapObject: a Dmaap object on success; an ErrorResponse object - * if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getDmaap() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DMAAP)); - logger.debug("getDmaap: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDmaap: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), Dmaap.class); - } catch (Exception ex) { - logger.debug("getDmaap: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a new DMaaP set system wide configuration settings for the - * dcaeEnvironment - * - * @param dmaap - * Dmaap properties - * @return Status and response: expect 200 and a Dmaap on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postDmaap(Dmaap dmaap) throws Exception { - String jsonBody = mapper.writeValueAsString(dmaap); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DMAAP), jsonBody); - if (hsr == null) - throw new Exception("postDmaap: unexpected null response"); - logger.debug("postDmaap: resp is {}", hsr); - // Returns ? on success, error message string on error. - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postDmaap: null response body"); - return response; - } - try { - Dmaap resp = mapper.readValue(hsr.getResponseString(), Dmaap.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDmaap: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates DMaaP system wide configuration settings for the dcaeEnvironment. - * - * @param dmaap - * Dmaap properties - * @return Status and response; expect 200 and a DR_Pub on success; a code - * and and ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putDmaap(Dmaap dmaap) throws Exception { - String jsonBody = mapper.writeValueAsString(dmaap); - // Oddly, this PUT has no ID parameter in the URL - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DMAAP), jsonBody); - if (hsr == null) - throw new Exception("putDmaap: unexpected null response"); - logger.debug("putDmaap: resp is {}", hsr); - // Returns ? on success, error message string on error. - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putDmaap: null response body"); - return response; - } - try { - Dmaap resp = mapper.readValue(hsr.getResponseString(), Dmaap.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putDmaap: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - // NO DELETE_DMAAP METHOD - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of data router nodes. - * - * @return List of DmaapObject: list contains DR_Node object(s) on success; - * a single ErrorResponse object if the remote site rejects the - * request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getDRNodes() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_NODES)); - logger.debug("getDRNodes: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRNodes: unexpected null response"); - - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getDRNodes: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets a data router node with the specified ID. - * - * @param fqdn - * Name of the node to get - * @return DmaapObject: a DR_Node object on success; an ErrorResponse object - * if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getDRNode(final String fqdn) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_NODES, fqdn)); - logger.debug("getDRNode: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRNode: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), DR_Node.class); - } catch (Exception ex) { - logger.debug("getDRNode: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a data router node. - * - * @param drNode - * Node to be created - * @return Status and response: expect 200 and a DR_Node on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postDRNode(DR_Node drNode) throws Exception { - String jsonBody = mapper.writeValueAsString(drNode); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_NODES), jsonBody); - logger.debug("postDRNode: resp is {}", hsr); - if (hsr == null) - throw new Exception("postDRNode: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postDRNode: null response body"); - return response; - } - try { - DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDRNode: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a data router node. - * - * @param drNode - * Node to be updated - * @return Status and response: expect 200 and a DR_Node on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putDRNode(DR_Node drNode) throws Exception { - String jsonBody = mapper.writeValueAsString(drNode); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_NODES, drNode.getFqdn()), jsonBody); - logger.debug("putDRNode: resp is {}", hsr); - if (hsr == null) - throw new Exception("putDRNode: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putDRNode: null response body"); - return response; - } - try { - DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDRNode: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the data router node with the specified FQDN. - * - * @param fqdn - * Name of the node to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteDRNode(final String fqdn) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_NODES, fqdn)); - logger.debug("deleteDRNode: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteDRNode: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteDRNode: null response body"); - return response; - } - try { - DR_Node resp = mapper.readValue(hsr.getResponseString(), DR_Node.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteDRNode: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of data router publishers. - * - * @return List of DmaapObject: list contains DR_Pub object(s) on success; a - * single ErrorResponse object if the remote site rejects the - * request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getDRPubs() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_PUBS)); - logger.debug("getDRPubs: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRPubs: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getDRPubs: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets a data router publisher with the specified ID. - * - * @param pubId - * ID of the publisher to get - * @return DmaapObject: a DR_Pub object on success; an ErrorResponse object - * if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getDRPub(final String pubId) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_PUBS, pubId)); - logger.debug("getDRPub: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRPub: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), DR_Pub.class); - } catch (Exception ex) { - logger.debug("getDRPub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a data router publisher. - * - * @param drPub - * Data router publisher properties - * @return Status and response: expect 200 and a DR_Pub on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postDRPub(DR_Pub drPub) throws Exception { - String jsonBody = mapper.writeValueAsString(drPub); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_PUBS), jsonBody); - logger.debug("postDRPub: resp is {}", hsr); - if (hsr == null) - throw new Exception("postDRPub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postDRPub: null response body"); - return response; - } - try { - DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDRPub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a data router publisher. - * - * @param drPub - * Publisher to be updated - * @return Status and response: expect 200 and a DR_Pub on success, a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putDRPub(DR_Pub drPub) throws Exception { - String jsonBody = mapper.writeValueAsString(drPub); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_PUBS, drPub.getPubId()), jsonBody); - logger.debug("putDRPub: resp is {}", hsr); - if (hsr == null) - throw new Exception("putDRPub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putDRPub: null response body"); - return response; - } - try { - DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDRPub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the data router publisher with the specified ID. - * - * @param pubId - * ID of the publisher to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteDRPub(final String pubId) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_PUBS, pubId)); - logger.debug("deleteDRPub: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteDRPub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteDRPub: null response body"); - return response; - } - try { - DR_Pub resp = mapper.readValue(hsr.getResponseString(), DR_Pub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteDRPub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of data router subscribers. - * - * @return List of DmaapObject: list contains DR_Sub object(s) on success; a - * single ErrorResponse object if the remote site rejects the - * request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getDRSubs() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_SUBS)); - logger.debug("getDRSubs: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRSubs: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getDRSubs: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets a data router subscriber with the specified ID. - * - * @param subId - * ID of the subscriber to get - * @return DmaapObject: a DR_Sub object on success; an ErrorResponse object - * if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getDRSub(final String subId) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(DR_SUBS, subId)); - logger.debug("getDRPub: resp is {}", hsr); - if (hsr == null) - throw new Exception("getDRSub: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), DR_Sub.class); - } catch (Exception ex) { - logger.debug("getDRSub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a data router subscriber. - * - * @param drSub - * Data router subscriber properties - * @return Status and response: expect 200 and a DR_Sub on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postDRSub(DR_Sub drSub) throws Exception { - String jsonBody = mapper.writeValueAsString(drSub); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(DR_SUBS), jsonBody); - logger.debug("postDRSub: resp is {}", hsr); - if (hsr == null) - throw new Exception("postDRSub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postDRSub: null response body"); - return response; - } - try { - DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postDRSub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a data router subscriber. - * - * @param drSub - * Subscriber to be updated - * @return Status and response; expect 200 and a DR_Sub on success, a string - * error on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putDRSub(DR_Sub drSub) throws Exception { - String jsonBody = mapper.writeValueAsString(drSub); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(DR_SUBS, drSub.getSubId()), jsonBody); - logger.debug("putDRSub: resp is {}", hsr); - if (hsr == null) - throw new Exception("putDRSub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putDRSub: null response body"); - return response; - } - try { - DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putDRSub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the data router subscriber with the specified ID. - * - * @param subId - * ID of the subscriber to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteDRSub(final String subId) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(DR_SUBS, subId)); - logger.debug("deleteDRSub: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteDRSub: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteDRSub: null response body"); - return response; - } - try { - DR_Sub resp = mapper.readValue(hsr.getResponseString(), DR_Sub.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteDRSub: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of data router feeds. - * - * @return List of DmaapObject: list contains DcaeLocation object(s) on - * success; a single ErrorResponse object if the remote site rejects - * the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getFeeds() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(FEEDS)); - logger.debug("getFeeds: resp is {}", hsr); - if (hsr == null) - throw new Exception("getFeeds: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getFeeds: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets a data router feed with the specified ID. - * - * @param feedId - * ID of the feed to get - * @return DmaapObject: a Feed object on success; an ErrorResponse object if - * the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getFeed(final String feedId) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(FEEDS, feedId)); - logger.debug("getFeed: resp is {}", hsr); - if (hsr == null) - throw new Exception("getFeed: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), Feed.class); - } catch (Exception ex) { - logger.debug("getFeed: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a feed and adds any specified pubs and subs. - * - * @param feed - * Data router feed properties - * @return Status and response: expect 200 and a Feed on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postFeed(Feed feed) throws Exception { - String jsonBody = mapper.writeValueAsString(feed); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(FEEDS), jsonBody); - logger.debug("postFeed: resp is {}", hsr); - if (hsr == null) - throw new Exception("postFeed: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postFeed: null response body"); - return response; - } - try { - Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postFeed: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a data router feed. - * - * @param feed - * Feed to be updated - * @return Status and response: expect 200 and a Feed on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putFeed(Feed feed) throws Exception { - String jsonBody = mapper.writeValueAsString(feed); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(FEEDS, feed.getFeedId()), jsonBody); - logger.debug("putFeed: resp is {}", hsr); - if (hsr == null) - throw new Exception("putFeed: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putFeed: null response body"); - return response; - } - try { - Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putFeed: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the data router feed with the specified ID. - * - * @param feedId - * ID of the feed to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteFeed(final String feedId) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(FEEDS, feedId)); - logger.debug("deleteFeed: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteFeed: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteFeed: null response body"); - return response; - } - try { - Feed resp = mapper.readValue(hsr.getResponseString(), Feed.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteFeed: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of message router topics. - * - * @return List of DmaapObject: list contains Topic object(s) on success; a - * single ErrorResponse object if the remote site rejects the - * request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getTopics() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(TOPICS)); - logger.debug("getTopics: resp is {}", hsr); - if (hsr == null) - throw new Exception("getTopics: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getTopics: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets the message router topic with the specified FQTN. - * - * @param fqtn - * Fully qualified topic name - * @return DmaapObject: a Topic object on success; an ErrorResponse object - * if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getTopic(final String fqtn) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(TOPICS, fqtn)); - logger.debug("getTopic: resp is {}", hsr); - if (hsr == null) - throw new Exception("getTopic: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), Topic.class); - } catch (Exception ex) { - logger.debug("getTopic: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a topic and grants appropriate permissions to specified pubs and - * subs. - * - * @param topic - * Message router topic properties - * @return Status and response: expect 200 and a Topic on success; a code - * and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postTopic(Topic topic) throws Exception { - String jsonBody = mapper.writeValueAsString(topic); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(TOPICS), jsonBody); - logger.debug("postTopic: resp is {}", hsr); - if (hsr == null) - throw new Exception("postTopic: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postTopic: null response body"); - return response; - } - try { - Topic resp = mapper.readValue(hsr.getResponseString(), Topic.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postTopic: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the message router topic with the specified FQTN. - * - * @param fqtn - * Fully qualified topic name to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteTopic(final String fqtn) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(TOPICS, fqtn)); - logger.debug("deleteTopic: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteTopic: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteTopic: null response body"); - return response; - } - try { - Topic resp = mapper.readValue(hsr.getResponseString(), Topic.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteTopic: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of message router clients. - * - * @return List of DmaapObject: list contains MR_Client object(s) on - * success; a single ErrorResponse object if the remote site rejects - * the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getMRClients() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLIENTS)); - logger.debug("getMRClients: resp is {}", hsr); - if (hsr == null) - throw new Exception("getMRClients: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getMRClients: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets the message router client with the specified ID. - * - * @param mrClientId - * ID of the client to get - * @return DmaapObject: a MR_Client object on success; an ErrorResponse - * object if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getMRClient(final String mrClientId) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLIENTS, mrClientId)); - logger.debug("getMRClient: resp is {}", hsr); - if (hsr == null) - throw new Exception("getMRClient: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), MR_Client.class); - } catch (Exception ex) { - logger.debug("getMRClient: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a message router client. - * - * @param mrClient - * Message router client properties - * @return Status and response: expect 200 and a MR_Client on success; a - * code and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postMRClient(MR_Client mrClient) throws Exception { - String jsonBody = mapper.writeValueAsString(mrClient); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(MR_CLIENTS), jsonBody); - logger.debug("postMRClient: resp is {}", hsr); - if (hsr == null) - throw new Exception("postMRClient: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postMRClient: null response body"); - return response; - } - try { - MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postMRClient: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a message router client. - * - * @param mrClient - * client to be updated - * @return Status and response; expect 200 and a MR_Client on success, a - * string error on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putMRClient(MR_Client mrClient) throws Exception { - String jsonBody = mapper.writeValueAsString(mrClient); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(MR_CLIENTS, mrClient.getMrClientId()), - jsonBody); - logger.debug("putMRClient: resp is {}", hsr); - if (hsr == null) - throw new Exception("putMRClient: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putMRClient: null response body"); - return response; - } - try { - MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putMRClient: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the message router client with the specified ID. - * - * @param mrClientId - * ID of the client to delete - * @return Status and response; expect 204 and a null on success, a string - * error on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteMRClient(final String mrClientId) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(MR_CLIENTS, mrClientId)); - logger.debug("deleteMRClient: resp is {}", hsr); - if (hsr == null) - throw new Exception("deleteMRClient: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteMRClient: null response body"); - return response; - } - try { - MR_Client resp = mapper.readValue(hsr.getResponseString(), MR_Client.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteMRClient: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Gets a list of message router clusters. - * - * @return List of DmaapObject: list contains MR_Cluster object(s) on - * success; a single ErrorResponse object if the remote site rejects - * the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public List getMRClusters() throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLUSTERS)); - logger.debug("getMRClusters: resp is {}", hsr); - if (hsr == null) - throw new Exception("getMRClusters: unexpected null response"); - List responseList = null; - try { - TypeReference> typeRef = new TypeReference>() { - }; - responseList = mapper.readValue(hsr.getResponseString(), typeRef); - } catch (Exception ex) { - logger.debug("getDcaeLocations: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - responseList = new ArrayList(); - responseList.add(errResp); - } - return responseList; - } - - /** - * Gets the message router cluster with the specified location name. - * - * @param dcaeLocName - * name of the cluster to get - * @return DmaapObject: a MR_Cluster object on success; an ErrorResponse - * object if the remote site rejects the request. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public DmaapObject getMRCluster(final String dcaeLocName) throws Exception { - HttpStatusAndResponse hsr = getRestContent(buildDmaapUri(MR_CLUSTERS, dcaeLocName)); - logger.debug("getMRCluster: resp is {}", hsr); - if (hsr == null) - throw new Exception("getMRCluster: unexpected null response"); - DmaapObject response = null; - try { - response = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); - } catch (Exception ex) { - logger.debug("getMRCluster: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - response = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - } - return response; - } - - /** - * Creates a message router cluster. - * - * @param mrCluster - * Message router cluster properties - * @return Status and response: expect 200 and a MR_Cluster on success; a - * code and an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse postMRCluster(MR_Cluster mrCluster) throws Exception { - String jsonBody = mapper.writeValueAsString(mrCluster); - HttpStatusAndResponse hsr = postRestContent(buildDmaapUri(MR_CLUSTERS), jsonBody); - logger.debug("postMRCluster: resp is {}", hsr); - if (hsr == null) - throw new Exception("postMRCluster: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("postMRCluster: null response body"); - return response; - } - try { - MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("postMRCluster: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Updates a message router cluster. - * - * @param mrCluster - * cluster to be updated - * @return Status and response; expect 200 and a MR_Cluster on success, a - * string error on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse putMRCluster(MR_Cluster mrCluster) throws Exception { - String jsonBody = mapper.writeValueAsString(mrCluster); - HttpStatusAndResponse hsr = putRestContent(buildDmaapUri(MR_CLUSTERS, mrCluster.getDcaeLocationName()), - jsonBody); - logger.debug("putMRCluster: resp is {}", hsr); - if (hsr == null) - throw new Exception("putMRCluster: unexpected null response"); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("putMRCluster: null response body"); - return response; - } - try { - MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("putMRCluster: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - /** - * Deletes the message router cluster with the specified location name. - * - * @param dcaeLocName - * Location name of the cluster to delete - * @return Status and response: expect 204 and a null on success; a code and - * an ErrorResponse on failure. - * @throws Exception - * if host cannot be reached, response cannot be parsed, etc. - */ - public HttpStatusAndResponse deleteMRCluster(final String dcaeLocName) throws Exception { - HttpStatusAndResponse hsr = deleteRestContent(buildDmaapUri(MR_CLUSTERS, dcaeLocName)); - if (hsr == null) - throw new Exception("deleteMRCluster: unexpected null response"); - logger.debug("deleteMRCluster: resp is {}", hsr); - HttpStatusAndResponse response = new HttpStatusAndResponse(hsr.getStatusCode(), null); - if (hsr.getResponse() == null) { - logger.debug("deleteMRCluster: null response body"); - return response; - } - try { - MR_Cluster resp = mapper.readValue(hsr.getResponseString(), MR_Cluster.class); - response.setResponse(resp); - } catch (Exception ex) { - logger.debug("deleteMRCluster: trying to parse response as error: {}", ex.toString()); - // If this parse fails, let the exception be thrown - ErrorResponse errResp = mapper.readValue(hsr.getResponseString(), ErrorResponse.class); - response.setResponse(errResp); - } - return response; - } - - ///////////////////////////////////////////////////////////////////// - - /** - * Builds the URI for the DMaaP REST endpoint using configuration and the - * specified task and path parameter(s). Deals with extra or missing slashes - * to allow for some flexibility in the config file. - * - * @param requestPath - * Last part of endpoint path - * @param pathParam - * Additional path parameters in order; ignored if null or empty - * @return REST endpoint URI - * @throws Exception - * if the RESAT URL property is not found - */ - private URI buildDmaapUri(String task, String... pathParam) throws Exception { - if (dmaapRestUrl == null || dmaapRestUrl.length() == 0) - throw new Exception("buildUrlPath: unconfigured, must set dmaapEndpointUrl"); - StringBuilder sb = new StringBuilder(); - // Clean the base of any trailing slashes - sb.append(trimSlashes(dmaapRestUrl)); - sb.append('/'); - // task is controlled in this file, don't clean it. - sb.append(task); - if (pathParam != null) { - for (String pp : pathParam) { - sb.append('/'); - // path comes from the user, definitely clean it. - sb.append(trimSlashes(pp)); - } - } - String urlPath = sb.toString(); - URIBuilder uriBuilder = new URIBuilder(urlPath); - return uriBuilder.build(); - } - - /** - * Strips the specified string of leading and trailing forward-slash - * characters. - * - * @param s - * String to trim - * @return String without any leading or trailing '/' characters. - */ - private String trimSlashes(String s) { - while (s.length() > 0 && s.charAt(0) == '/') - s = s.substring(1, s.length()); - while (s.length() > 0 && s.charAt(s.length() - 1) == '/') - s = s.substring(0, s.length() - 1); - return s; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/HttpStatusAndResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/HttpStatusAndResponse.java deleted file mode 100644 index a9b1585..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/HttpStatusAndResponse.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller REST Client - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.client; - -/** - * Holds the status code and body that result from accessing an HTTP URL. - */ -public class HttpStatusAndResponse { - - private int statusCode; - private ResponseType response; - - public HttpStatusAndResponse(int status, ResponseType resp) { - this.statusCode = status; - this.response = resp; - } - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(final int code) { - this.statusCode = code; - } - - public ResponseType getResponse() { - return response; - } - - public void setResponse(ResponseType response) { - this.response = response; - } - - /** - * Convenience method to avoid testing for null and calling .toString() - * - * @return String version of the response object; null if the object is - * null. - */ - public String getResponseString() { - return response == null ? null : response.toString(); - } - - @Override - public String toString() { - return "HttpStatusAndResponse[" + Integer.toString(statusCode) + ";" - + (response == null ? "" : response.toString()) + "]"; - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/IRestClientConstants.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/IRestClientConstants.java deleted file mode 100644 index 1db390b..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/IRestClientConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller REST Client - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.client; - -public interface IRestClientConstants { - - /** - * Default configuration file to be found on classpath - */ - public static final String PROPERTY_FILE_NAME = "bc-rest-client.properties"; - - /** - * Base URL of the Bus Controller REST service API - */ - public static final String DMAAP_BUS_CONTROLLER_REST_URL = "dmaap_bus_controller_rest_url"; - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/SimpleRestClientBase.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/SimpleRestClientBase.java deleted file mode 100644 index 7868d8c..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/client/SimpleRestClientBase.java +++ /dev/null @@ -1,291 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller REST Client - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.client; - -import java.io.IOException; -import java.net.URI; - -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.AuthCache; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.config.RequestConfig.Builder; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Provides a basic client to access a REST endpoint, optionally using HTTP - * basic authentication. - * - * Caveat: If HTTPS access is used and the server uses a self-signed - * certificate, the local trust store must be extended appropriately. The client - * throws exceptions if the JVM cannot validate the server certificate. - */ -public class SimpleRestClientBase { - - private static Logger logger = LoggerFactory.getLogger(SimpleRestClientBase.class); - - /** - * Credentials for HTTP basic authentication (optional). - */ - private final String username; - private final String password; - - /** - * Timeouts (optional) - */ - private Integer connectTimeoutMs = null; - private Integer connectionRequestTimeoutMs = null; - private Integer socketTimeoutMs = null; - - /** - * Constructs a client that does not use any authentication and uses Apache - * HTTPD client default values for timeouts. - */ - public SimpleRestClientBase() { - this(null, null, null, null, null); - } - - /** - * Convenience constructor to build a client that uses the specified - * username and password for basic HTTP authentication on all requests. In - * other words, this client pre-emptively sends the "Basic" header instead - * of first trying the request without, failing, negotiating, then sending - * with credentials. - * - * @param username - * User name for basic HTTP authentication. - * @param password - * Password for basic HTTP authentication. - */ - public SimpleRestClientBase(final String username, final String password) { - this(username, password, null, null, null); - } - - /** - * Convenience constructor to build a client that uses the specified - * timeouts on all requests. - * - * @param connectTimeoutMs - * Connection timeout, in milliseconds - * @param connectionRequestTimeoutMs - * Connection request timeout, in milliseconds - * @param socketTimeoutMs - * Socket timeout, in milliseconds - */ - public SimpleRestClientBase(final Integer connectTimeoutMs, final Integer connectionRequestTimeoutMs, - final Integer socketTimeoutMs) { - this(null, null, connectTimeoutMs, connectionRequestTimeoutMs, socketTimeoutMs); - } - - /** - * Constructs a client with the specified credentials and timeout values. - * - * @param username - * User name for basic HTTP authentication; ignored if null - * @param password - * Password for basic HTTP authentication; ignored if null - * @param connectTimeoutMs - * ignored if null - * @param connectionRequestTimeoutMs - * ignored if null - * @param socketTimeoutMs - * ignored if null - */ - public SimpleRestClientBase(final String username, final String password, final Integer connectTimeoutMs, - final Integer connectionRequestTimeoutMs, final Integer socketTimeoutMs) { - this.username = username; - this.password = password; - this.connectTimeoutMs = null; - this.connectionRequestTimeoutMs = null; - this.socketTimeoutMs = null; - } - - /** - * Constructs and sends a GET request for the URI. - * - * @param uri - * REST endpoint - * @return Result of the get - * @throws Exception - * On any error - */ - public HttpStatusAndResponse getRestContent(final URI uri) throws Exception { - HttpGet httpGet = new HttpGet(uri); - return doRestRequest(httpGet); - } - - /** - * Constructs and sends a POST request using the specified body. - * - * @param uri - * REST endpoint - * @param json - * Content to post - * @return Result of the post; null if an error happens - * @throws Exception - * On any error - */ - public HttpStatusAndResponse postRestContent(final URI uri, final String json) throws Exception { - HttpPost httpPost = new HttpPost(uri); - StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); - httpPost.setEntity(postEntity); - return doRestRequest(httpPost); - } - - /** - * Constructs and sends a PUT request using the specified body. - * - * @param uri - * REST endpoint - * @param json - * Content to put - * @return Result of the put; null if an error happens - * @throws Exception - * On any error - */ - public HttpStatusAndResponse putRestContent(final URI uri, final String json) throws Exception { - HttpPut httpPut = new HttpPut(uri); - StringEntity postEntity = new StringEntity(json, ContentType.create("application/json", Consts.UTF_8)); - httpPut.setEntity(postEntity); - return doRestRequest(httpPut); - } - - /** - * Constructs and sends a DELETE request for the URI. - * - * @param uri - * REST endpoint - * @return Result of the get - * @throws Exception - * On any error - */ - public HttpStatusAndResponse deleteRestContent(final URI uri) throws Exception { - HttpDelete httpDel = new HttpDelete(uri); - return doRestRequest(httpDel); - } - - /** - * Executes the specified request and gathers the response. - * - * @param request - * HttpGet, HttpPost, etc. - * @return Status code and response body - * @throws ClientProtocolException - * On HTTP protocol error - * @throws IOException - * On read/write error - */ - private HttpStatusAndResponse doRestRequest(final HttpRequestBase request) - throws ClientProtocolException, IOException { - - // Set up authentication if needed - final HttpClientContext context = HttpClientContext.create(); - if (this.username != null || this.password != null) { - UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials(AuthScope.ANY, credentials); - context.setCredentialsProvider(credentialsProvider); - - HttpHost host = new HttpHost(request.getURI().getHost(), request.getURI().getPort(), - request.getURI().getScheme()); - AuthCache authCache = new BasicAuthCache(); - authCache.put(host, new BasicScheme()); - context.setAuthCache(authCache); - } - final Builder requestConfigBuilder = RequestConfig.custom(); - if (connectionRequestTimeoutMs != null) - requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeoutMs); - if (connectTimeoutMs != null) - requestConfigBuilder.setConnectTimeout(connectTimeoutMs); - if (socketTimeoutMs != null) - requestConfigBuilder.setSocketTimeout(socketTimeoutMs); - RequestConfig requestConfig = requestConfigBuilder.build(); - final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); - CloseableHttpResponse response = null; - String responseJson = null; - try { - response = httpClient.execute(request, context); - // Some methods return non-200 on success - logger.debug("doRestRequest: status is {}", response.getStatusLine()); - HttpEntity entity = response.getEntity(); - // This is common; don't warn - if (entity == null) { - logger.debug("doRestRequest: Entity is null"); - } else { - // entity content length is never set; - // this naively tries to read everything. - responseJson = EntityUtils.toString(entity); - EntityUtils.consume(entity); - // Don't give back empty string; - // it has no more meaning than null. - if (responseJson.length() == 0) - responseJson = null; - } - } finally { - if (response != null) - response.close(); - } - if (response == null) - return null; - return new HttpStatusAndResponse(response.getStatusLine().getStatusCode(), responseJson); - } - - /** - * Basic test invocation. - * - * @param args - * Expect 1 argument, the URL of a REST endpoint. - * @throws Exception - * if anything goes wrong - */ - public static void main(String[] args) throws Exception { - if (args.length != 1) - throw new IllegalArgumentException("Expect 1 argument: REST URL for GET"); - SimpleRestClientBase client = new SimpleRestClientBase(); - URIBuilder uriBuilder = new URIBuilder(args[0]); - URI uri = uriBuilder.build(); - HttpStatusAndResponse hsr = client.getRestContent(uri); - System.out.println("Response code is " + hsr.getStatusCode()); - System.out.println(hsr.getResponseString()); - System.out.println("main ends."); - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java deleted file mode 100644 index 8748f29..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataBusHomeController.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.ModelAndView; - -/** - * This controller maps requests for the DMaaP-BC-App's landing page, which is - * an Angular single-page application. - */ -@Controller -@RequestMapping("/") -public class DataBusHomeController extends DbcappRestrictedBaseController { - - public static final String APP_NAME = "dmaap-bc-app"; - public static final DateFormat logDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - /** - * At one time I published the landing page as simply "/dbc", but it can - * also be accessed with a default suffix; e.g., "/dbc.htm". - * - * @return View name key, which is resolved to a file using an Apache tiles - * "definitions.xml" file. - */ - @RequestMapping(value = { "/dbc" }, method = RequestMethod.GET) - public ModelAndView dbcDefaultController() { - // a model is only useful for JSP; this app is angular. - return new ModelAndView("dbc_home_tdkey"); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataRouterController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataRouterController.java deleted file mode 100644 index cb6aa93..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DataRouterController.java +++ /dev/null @@ -1,321 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.dcae.dmaapbc.dbcapp.util.DbcappProperties; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -/** - * Data Router controller: serves Ajax requests made by Angular scripts on pages - * that show feeds, publishers and subscribers. - */ -@Controller -@RequestMapping("/") -public class DataRouterController extends DbcappRestrictedBaseController { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DataRouterController.class); - - /** - * Application properties - NOT available to constructor. - */ - @Autowired - private DbcappProperties appProperties; - - private static final String FEED_PATH = "/dr_feed"; - private static final String PUB_PATH = "/dr_pub"; - private static final String SUB_PATH = "/dr_sub"; - - public DataRouterController() { - } - - /** - * Answers a request for one page of data router feeds. - * - * @param request - * HttpServletRequest - * @return Result of - * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} - */ - @RequestMapping(value = { FEED_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDRFeedsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = getItemListForPageWrapper(request, DmaapDataItem.DR_FEED); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Answers a request for one page of data router publishers. - * - * @param request - * HttpServletRequest - * @return Result of - * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} - */ - @RequestMapping(value = { PUB_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDRPubsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = getItemListForPageWrapper(request, DmaapDataItem.DR_PUB); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Answers a request for one page of data router subscribers. - * - * @param request - * HttpServletRequest - * @return Result of - * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} - */ - @RequestMapping(value = { SUB_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDRSubsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = getItemListForPageWrapper(request, DmaapDataItem.DR_SUB); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Adds a feed with the specified information. Expects a JSON block in the - * request body - a Feed object. - * - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { FEED_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addDRFeed(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = addItem(request, DmaapDataItem.DR_FEED, null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Adds a publisher with the specified information. Expects a JSON block in - * the request body - a DR_Pub object. - * - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { PUB_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addDRPub(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = addItem(request, DmaapDataItem.DR_PUB, HttpServletResponse.SC_CREATED); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Adds a subscriber with the specified information. Expects a JSON block in - * the request body - a DR_Sub object. - * - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { SUB_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addDRSub(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = addItem(request, DmaapDataItem.DR_SUB, HttpServletResponse.SC_CREATED); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Updates a feed with the specified information. Expects a JSON block in - * the request body - a Feed object. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { FEED_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateFeed(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = updateItem(request, DmaapDataItem.DR_FEED, Long.toString(id), null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Updates a publisher with the specified information. Expects a JSON block - * in the request body - a DR_Pub object. - * - * The pubId may have a dot in it. Spring, in its infinite wisdom, truncates - * extensions on dotted path parameters; e.g., "foo.json" becomes "foo". - * Avoid truncation here with the extra ":.+" incantation at the end. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { PUB_PATH + "/{id:.+}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateDRPub(@PathVariable("id") String id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = updateItem(request, DmaapDataItem.DR_PUB, id, null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Updates a subscriber with the specified information. Expects a JSON block - * in the request body - a DR_Sub object. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return a JSON object; on success it has a "status" and possibly a "data" - * item; on failure, also has an "error" item. - */ - @RequestMapping(value = { SUB_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateDRSub(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = updateItem(request, DmaapDataItem.DR_SUB, Long.toString(id), null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Deletes a feed with the ID specified as a path parameter. On successful - * delete the endpoint returns 204 (confusingly). - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return A JSON object as an HTTP response; on success it only has - * "status" item; on failure, also has an "error" item. - */ - @RequestMapping(value = { FEED_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDRFeed(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = deleteItem(request, DmaapDataItem.DR_FEED, Long.toString(id), 204); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Deletes the publisher with the ID specified as a path parameter. - * - * The pubId may have a dot in it. Spring, in its infinite wisdom, truncates - * extensions on dotted path parameters; e.g., "foo.json" becomes "foo". - * Avoid truncation here with the extra ":.+" incantation at the end. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return a JSON object; on success it only has "status" item; on failure, - * also has an "error" item. - */ - @RequestMapping(value = { PUB_PATH + "/{id:.+}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDRPub(@PathVariable("id") String id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = deleteItem(request, DmaapDataItem.DR_PUB, id, null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Deletes the subscriber with the ID specified as a path parameter. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return A JSON object; on success it only has "status" item; on failure, - * also has an "error" item. - */ - @RequestMapping(value = { SUB_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDRSub(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = deleteItem(request, DmaapDataItem.DR_SUB, Long.toString(id), 204); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Answers a request for data router feed classification labels, such as - * "Customer Proprietary", which are read from properties. - * - * @param request - * HttpServletRequest - * @return List of string values - */ - @RequestMapping(value = { FEED_PATH + "_pii_types" }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public List getDRFeedPiiType(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - ArrayList response = new ArrayList<>(); - String[] propKeys = appProperties.getCsvListProperty(DbcappProperties.DMAAP_PII_TYPE_LIST); - for (String key : propKeys) - response.add(appProperties.getProperty(key)); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java deleted file mode 100644 index 517af09..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DbcappRestrictedBaseController.java +++ /dev/null @@ -1,968 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.dcae.dmaapbc.client.DmaapBcRestClient; -import org.openecomp.dcae.dmaapbc.client.HttpStatusAndResponse; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.DmaapAccess; -import org.openecomp.dcae.dmaapbc.dbcapp.rest.DbcUsvcRestClient; -import org.openecomp.dcae.dmaapbc.dbcapp.service.DmaapAccessService; -import org.openecomp.dcae.dmaapbc.dbcapp.util.DbcappProperties; -import org.openecomp.dcae.dmaapbc.model.DR_Pub; -import org.openecomp.dcae.dmaapbc.model.DR_Sub; -import org.openecomp.dcae.dmaapbc.model.DcaeLocation; -import org.openecomp.dcae.dmaapbc.model.Dmaap; -import org.openecomp.dcae.dmaapbc.model.DmaapObject; -import org.openecomp.dcae.dmaapbc.model.ErrorResponse; -import org.openecomp.dcae.dmaapbc.model.Feed; -import org.openecomp.dcae.dmaapbc.model.MR_Client; -import org.openecomp.dcae.dmaapbc.model.Topic; -import org.openecomp.portalsdk.core.controller.RestrictedBaseController; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * This base class provides utility methods to child controllers. All of the - * requests are forwarded on to a remote REST API, so there's a large degree of - * commonality among the implementations. Combining them kept the lines-of-code - * count down, at the expense of some complexity. - */ -public class DbcappRestrictedBaseController extends RestrictedBaseController { - - /** - * Query parameter for desired page number - */ - protected static final String PAGE_NUM_QUERY_PARAM = "pageNum"; - - /** - * Query parameter for desired items per page - */ - protected static final String VIEW_PER_PAGE_QUERY_PARAM = "viewPerPage"; - - /** - * Tag for status code in JSON responses - ALWAYS PRESENT. - */ - protected static final String STATUS_RESPONSE_KEY = "status"; - - /** - * Tag for data in JSON responses. - */ - protected static final String DATA_RESPONSE_KEY = "data"; - - /** - * Tag for error message in JSON responses; absent on success. - */ - protected static final String ERROR_RESPONSE_KEY = "error"; - - /** - * Tag for response integer, pages required to display complete result list - */ - protected static final String TOTAL_PAGES_RESPONSE_KEY = "totalPages"; - - /** - * Tag for DMaaP name obtained from REST client. - */ - protected static final String PROFILE_NAME_RESPONSE_KEY = "profileName"; - - /** - * Tag for DMaaP name obtained from REST client. - */ - protected static final String DMAAP_NAME_RESPONSE_KEY = "dmaapName"; - - /** - * Tag for DCAE location name list obtained from REST client. - */ - protected static final String DCAE_LOCATIONS_RESPONSE_KEY = "dcaeLocations"; - - /** - * Logger that conforms with ECOMP guidelines - */ - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DbcappRestrictedBaseController.class); - - /** - * For general use in these methods and subclasses - */ - protected final ObjectMapper mapper = new ObjectMapper(); - - /** - * DAO accesses the profiles via a local database. REST accesses the - * profiles via a remote REST service. - */ - public enum AccessMethod { - DAO, REST - }; - - /** - * Enum for selecting an item type. - */ - public enum DmaapDataItem { - DR_FEED, DR_PUB, DR_SUB, MR_TOPIC, MR_CLIENT; - } - - /** - * Application properties - NOT available to constructor. - */ - @Autowired - private DbcappProperties appProperties; - - /** - * Database access - which might not be used. - */ - @Autowired - private DmaapAccessService dmaapAccessDaoServiceAuto; - - /** - * Read from application properties. - */ - private String mechIdName, mechIdPass; - - /** - * This is set by {@link #getDmaapAccessService()} to the DAO or REST - * implementation as configured in properties. - */ - private DmaapAccessService dmaapAccessService; - - /** - * Hello Spring, here's your no-arg constructor. - */ - public DbcappRestrictedBaseController() { - // Do not serialize null values - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - } - - /** - * Access method for subclasses. - * - * @return DbcappProperties object that was autowired by Spring. - */ - protected DbcappProperties getAppProperties() { - return appProperties; - } - - /** - * Lazy initialization. As a side effect, caches mech ID and password. - * - * @return Either DAO or REST client that implements the access service - * interface. - */ - protected DmaapAccessService getDmaapAccessService() { - if (dmaapAccessService != null) - return dmaapAccessService; - - // Get the application's mechid - mechIdName = appProperties.getProperty(DbcappProperties.DMAAP_MECHID_NAME); - // This is encrypted - String cipher = appProperties.getProperty(DbcappProperties.DMAAP_MECHID_PASSWORD); - if (mechIdName == null || cipher == null) - throw new RuntimeException("Failed to get MECH_ID name and/or password from properties"); - try { - mechIdPass = CipherUtil.decrypt(cipher); - } catch (Exception ex) { - throw new RuntimeException("Failed to decrypt password from config file", ex); - } - - String accessMethod = appProperties.getProperty(DbcappProperties.PROFILE_ACCESS_METHOD); - if (accessMethod == null) - throw new RuntimeException("Failed to get property " + DbcappProperties.PROFILE_ACCESS_METHOD); - AccessMethod profileAccessMethod = AccessMethod.valueOf(accessMethod.toUpperCase()); - if (AccessMethod.DAO == profileAccessMethod) { - // Spring auto-wired this field - dmaapAccessService = dmaapAccessDaoServiceAuto; - } else { - String url = appProperties.getProperty(DbcappProperties.PROFILE_USVC_URL); - String user = appProperties.getProperty(DbcappProperties.PROFILE_USVC_USER); - String pass = appProperties.getProperty(DbcappProperties.PROFILE_USVC_PASS); - if (url == null || user == null || pass == null) - throw new RuntimeException("getDmaapAccessService: missing property: one of url, user, pass"); - String clearText = null; - try { - clearText = CipherUtil.decrypt(pass); - } catch (Exception ex) { - throw new RuntimeException("getDmaapAccessService: failed to decrypt password from config"); - } - dmaapAccessService = new DbcUsvcRestClient(url, user, clearText); - } - return dmaapAccessService; - } - - /** - * Creates a REST client with appropriate credentials, the user/pass from - * the access profile if present, otherwise with the default mech ID and - * password. - * - * @param dmaapAccess - * Profile - * @return REST client. - */ - protected DmaapBcRestClient getDmaapBcRestClient(DmaapAccess dmaapAccess) { - DmaapBcRestClient restClient = null; - if (dmaapAccess.getMechId() == null || dmaapAccess.getMechId().length() == 0) - restClient = new DmaapBcRestClient(dmaapAccess.getDmaapUrl(), mechIdName, mechIdPass); - else - restClient = new DmaapBcRestClient(dmaapAccess.getDmaapUrl(), dmaapAccess.getMechId(), - dmaapAccess.getPassword()); - return restClient; - } - - /** - * Pulls out of the specified list the appropriate items for the page of - * results specified by the page number and view-per-page parameters. - * - * @param pageNum - * Page number requested by user - * @param viewPerPage - * Number of items per page - * @param itemList - * List of items available - * @return List of items to display - */ - @SuppressWarnings("rawtypes") - private static List shrinkListToPage(final int pageNum, final int viewPerPage, final List itemList) { - // user-friendly page numbers index from 1 - int firstIndexOnThisPage = viewPerPage * (pageNum - 1); - int firstIndexOnNextPage = viewPerPage * pageNum; - int fromIndex = firstIndexOnThisPage < itemList.size() ? firstIndexOnThisPage : itemList.size(); - int toIndex = firstIndexOnNextPage < itemList.size() ? firstIndexOnNextPage : itemList.size(); - // answers empty list if from==to - return itemList.subList(fromIndex, toIndex); - } - - /** - * Gets the body of a HTTP request assuming UTF-8 encoding. - * - * @param request - * HttpServletRequest - * @return String version of request body - * @throws IOException - * If the read fails - */ - protected static String getBody(HttpServletRequest request) throws IOException { - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader bufferedReader = null; - try { - InputStream inputStream = request.getInputStream(); - if (inputStream != null) { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); - char[] charBuffer = new char[512]; - int bytesRead = -1; - while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { - stringBuilder.append(charBuffer, 0, bytesRead); - } - } else { - stringBuilder.append(""); - } - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (IOException ex) { - throw ex; - } - } - - } - return stringBuilder.toString(); - } - - /** - * Builds a JSON success response from the specified inputs. - * - * @param statusCode - * e.g., 200 for OK - * @param dataPojo - * Plain old Java object to serialize as JSON; ignored if null. - * @throws JsonProcessingException - * If the POJO cannot be serialized - * @return JSON block with items "status" : 200 and "data" : (data..) - */ - protected String buildJsonSuccess(int statusCode, Object dataPojo) throws JsonProcessingException { - Map model = new HashMap(); - model.put(STATUS_RESPONSE_KEY, statusCode); - if (dataPojo != null) - model.put(DATA_RESPONSE_KEY, dataPojo); - String json = mapper.writeValueAsString(model); - return json; - } - - /** - * Builds a JSON error response from the specified inputs. - * - * @param statusCode - * e.g., 500 for internal server error - * @param errMsg - * Information about the operation that failed - * @param exception - * Converted to string; ignored if null. - * @return JSON block with tags "status" and "error". - */ - protected String buildJsonError(int statusCode, String errMsg, Exception exception) { - Map model = new HashMap(); - model.put(STATUS_RESPONSE_KEY, new Integer(500)); - if (exception == null) { - model.put(ERROR_RESPONSE_KEY, errMsg); - } else { - final int enough = 512; - String exString = exception.toString(); - String exceptionMsg = exString.length() > enough ? exString.substring(0, enough) : exString; - model.put(ERROR_RESPONSE_KEY, errMsg + ": " + exceptionMsg); - } - String json = null; - try { - json = mapper.writeValueAsString(model); - } catch (JsonProcessingException ex) { - // serializing the trivial map should never fail - String err = "buildJsonError: failed to serialize"; - logger.error(EELFLoggerDelegate.errorLogger, err, ex); - throw new RuntimeException(err, ex); - } - return json; - } - - /** - * Gets a list of DMaaP access profiles for this user from the database. The - * profiles have passwords in the clear - this method decrypts the database - * entries. - * - * Initializes the list for new users and/or configuration changes. Checks - * the database list against the configured list of URLs, and creates new - * rows for any configured URLs not present for the user. Most environments - * are expected to have exactly one valid URL, and the webapp uses a fixed - * MechID to authenticate itself to the DMaaP bus controller, so this - * approach means new users can start without any setup of URLs. - * - * @param userId - * User ID - * @return List of DmaapAccess objects - * @throws Exception - * If the URL list is not available in properties - */ - protected List getOrInitDmaapAccessList(String userId) throws Exception { - String[] configUrls = getAppProperties().getCsvListProperty(DbcappProperties.DMAAP_REST_URL_LIST); - if (configUrls == null || configUrls.length == 0) - throw new Exception("getOrInitDmaapAccessList: Failed to get DMAAP REST URL list"); - // Update this list to track which URLs are in the database. - List configUrlList = new ArrayList(configUrls.length); - for (String c : configUrls) { - // Validate URL to detect config botches - URL url = new URL(c); - configUrlList.add(url.toExternalForm()); - } - - List dbAccessList = getDmaapAccessService().getDmaapAccessList(userId); - - // Check the database entries against the configuration. Also - // build a list of non-DAO objects with clear-text passwords. - List clearList = new ArrayList(dbAccessList.size()); - for (DmaapAccess dmaapAccess : dbAccessList) { - // drop this URL from the list. - // If it's not known to config, complain because that's a bogus row. - if (!configUrlList.remove(dmaapAccess.getDmaapUrl())) - logger.warn(EELFLoggerDelegate.errorLogger, "getOrInitDmaapAccessList: detected extra URL {}", - dmaapAccess.getDmaapUrl()); - // Return cleartext in JSON - DmaapAccess clone = new DmaapAccess(dmaapAccess); - clone.setPassword(clone.decryptPassword()); - clearList.add(clone); - } - - // Create new rows for any configured URLs not found for this user. - for (int i = 0; i < configUrlList.size(); ++i) { - String missUrl = configUrlList.get(i); - logger.debug(EELFLoggerDelegate.debugLogger, "getOrInitDmaapAccessList: adding missing URL {}", missUrl); - DmaapAccess newDmaapAccess = new DmaapAccess(); - // Create a semi-reasonable name for the table - newDmaapAccess.setName("dmaap-" + Integer.toString(i + 1)); - newDmaapAccess.setUserId(userId); - newDmaapAccess.setDmaapUrl(missUrl); - // Write to db. - getDmaapAccessService().saveDmaapAccess(newDmaapAccess); - // Add to response, which assumes the write was successful. - clearList.add(newDmaapAccess); - } - - return clearList; - } - - /** - * Gets the user's selected DMaaP access profile. - * - * @param userId - * User ID - * @return DmaapAccess object that is currently selected, or the first one - * found if none are selected; null if no access profiles are - * configured. - * @throws Exception - * If the profile is not found - */ - protected DmaapAccess getSelectedDmaapAccess(String userId) throws Exception { - List profiles = getOrInitDmaapAccessList(userId); - if (profiles.size() == 0) { - logger.debug("getSelectedDmaapAccess: no rows found, returning null"); - return null; - } - - // Return the first one by default if nothing is selected. - DmaapAccess selected = profiles.get(0); - for (DmaapAccess da : profiles) - if (da.getSelected()) - selected = da; - - return selected; - } - - /** - * Supports sorting a list of feeds by the first column displayed: ID - */ - private static Comparator feedComparator = new Comparator() { - @Override - public int compare(DmaapObject o1, DmaapObject o2) { - Feed f1 = (Feed) o1; - Feed f2 = (Feed) o2; - // sort these numbers lexicographically, same as the front end - // table. - return f1.getFeedId().compareTo(f2.getFeedId()); - } - }; - - /** - * Supports sorting a list of publishers by the first column displayed: pub - * ID - */ - private static Comparator pubComparator = new Comparator() { - @Override - public int compare(DmaapObject o1, DmaapObject o2) { - DR_Pub p1 = (DR_Pub) o1; - DR_Pub p2 = (DR_Pub) o2; - return p1.getPubId().compareTo(p2.getPubId()); - } - }; - - /** - * Supports sorting a list of subscribers by the first column displayed: sub - * ID - */ - private static Comparator subComparator = new Comparator() { - @Override - public int compare(DmaapObject o1, DmaapObject o2) { - DR_Sub s1 = (DR_Sub) o1; - DR_Sub s2 = (DR_Sub) o2; - // sort these numbers lexicographically, same as the front end - // table. - return s1.getSubId().compareTo(s2.getSubId()); - } - }; - - /** - * Supports sorting a list of topics by the first column displayed: FQTN - */ - private static Comparator topicComparator = new Comparator() { - @Override - public int compare(DmaapObject o1, DmaapObject o2) { - Topic t1 = (Topic) o1; - Topic t2 = (Topic) o2; - return t1.getFqtn().compareTo(t2.getFqtn()); - } - }; - - /** - * Supports sorting a list of clients by the first column displayed: client - * ID. - */ - private static Comparator clientComparator = new Comparator() { - @Override - public int compare(DmaapObject o1, DmaapObject o2) { - MR_Client c1 = (MR_Client) o1; - MR_Client c2 = (MR_Client) o2; - // sort these numbers lexicographically, same as the front end - // table. - return c1.getMrClientId().compareTo(c2.getMrClientId()); - } - }; - - /** - * Gets one page of DMaaP objects and supporting information via the Bus - * Controller REST client. On success, returns a JSON object as String with - * the following tags: - *
    - *
  • status: Integer; HTTP status code 200. - *
  • dmaapName: String, name returned by the remote DMaaP instance. - *
  • dcaeLocations: Array of string, locations returned by the remote - * DMaaP instance. - *
  • data: Array of the desired items; e.g., data router feeds. - *
  • totalPages: Integer, the number of pages required to display the - * complete list of items using the submitted page size - *
- * - * This duplicates all of {@link #buildJsonSuccess(int, Object)}. - * - * @param dmaapAccess - * Access details for the DMaaP REST API - * @param option - * Specifies which item list type to get: data router feeds, etc. - * @param pageNum - * Page number of results - * @param viewPerPage - * Number of items per page - * @return JSON block as String, see above. - * @throws Exception - * On any error - */ - private String getItemListForPage(DmaapAccess dmaapAccess, DmaapDataItem option, int pageNum, int viewPerPage) - throws Exception { - DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); - // Get the instance so the page can display its name - DmaapObject dmaap = restClient.getDmaap(); - if (dmaap instanceof ErrorResponse) { - // Bad password is caught here. - ErrorResponse err = (ErrorResponse) dmaap; - throw new Exception(err.getMessage()); - } - // Get locations for editing - List dcaeLocations = restClient.getDcaeLocations(); - if (dcaeLocations.size() == 1 && dcaeLocations.get(0) instanceof ErrorResponse) { - // Should never happen - bad password is caught right above - but be - // careful. - ErrorResponse err = (ErrorResponse) dcaeLocations.get(0); - throw new Exception(err.getMessage()); - } - // Pass them back as String array - String[] dcaeLocs = new String[dcaeLocations.size()]; - for (int i = 0; i < dcaeLocs.length; ++i) { - DcaeLocation dcaeLoc = (DcaeLocation) dcaeLocations.get(i); - dcaeLocs[i] = dcaeLoc.getDcaeLocationName(); - } - // Get the requested item list - List itemList = null; - switch (option) { - case DR_FEED: - itemList = restClient.getFeeds(); - // size 1 may be error response - if (itemList.size() > 1) - Collections.sort(itemList, feedComparator); - break; - case DR_PUB: - itemList = restClient.getDRPubs(); - // size 1 may be error response - if (itemList.size() > 1) - Collections.sort(itemList, pubComparator); - break; - case DR_SUB: - itemList = restClient.getDRSubs(); - // size 1 may be error response - if (itemList.size() > 1) - Collections.sort(itemList, subComparator); - break; - case MR_TOPIC: - itemList = restClient.getTopics(); - // size 1 may be error response - if (itemList.size() > 1) - Collections.sort(itemList, topicComparator); - break; - case MR_CLIENT: - itemList = restClient.getMRClients(); - // size 1 may be error response - if (itemList.size() > 1) - Collections.sort(itemList, clientComparator); - break; - default: - throw new Exception("getItemListForPage: pgmr error, unimplemented case: " + option.name()); - } - - logger.debug("getItemListForPage: list size is {}", itemList.size()); - int pageCount = (int) Math.ceil((double) itemList.size() / viewPerPage); - @SuppressWarnings("unchecked") - List subList = shrinkListToPage(pageNum, viewPerPage, itemList); - itemList = subList; - // Build response here - Map model = new HashMap(); - model.put(STATUS_RESPONSE_KEY, new Integer(200)); - model.put(PROFILE_NAME_RESPONSE_KEY, dmaapAccess.getName()); - model.put(DMAAP_NAME_RESPONSE_KEY, ((Dmaap) dmaap).getDmaapName()); - model.put(DCAE_LOCATIONS_RESPONSE_KEY, dcaeLocs); - model.put(DATA_RESPONSE_KEY, itemList); - model.put(TOTAL_PAGES_RESPONSE_KEY, pageCount); - - // build the response - String outboundJson = null; - try { - outboundJson = mapper.writeValueAsString(model); - } catch (Exception ex) { - // should never happen - logger.error("getItemListForPage: failed to serialize model: ", ex); - throw new Exception("sendItemListForPage", ex); - } - - return outboundJson; - } - - /** - * Gets a page of the specified DMaaP items. This method traps errors and - * constructs an appropriate JSON block if an error happens. - * - * See {@link #getItemListForPage(DmaapAccess, DmaapDataItem, int, int)}. - * - * @param request - * Inbound request - * @param option - * DMaaP item type to get - * @return JSON with list of serialized objects, or an error. - */ - protected String getItemListForPageWrapper(HttpServletRequest request, DmaapDataItem option) { - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("getItemListForPageWrapper: Failed to get Login UID"); - DmaapAccess selected = getSelectedDmaapAccess(appUser.getLoginId()); - if (selected == null) // leap into exception handler - throw new Exception("No DMaaP access profiles are configured."); - int pageNum = Integer.parseInt(request.getParameter(PAGE_NUM_QUERY_PARAM)); - int viewPerPage = Integer.parseInt(request.getParameter(VIEW_PER_PAGE_QUERY_PARAM)); - outboundJson = getItemListForPage(selected, option, pageNum, viewPerPage); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to get DMaaP item type " + option.name(), ex); - } - return outboundJson; - } - - /** - * Adds an item of the specified type with the specified content. Constructs - * an object by deserializing the JSON block, but ignores any ID field that - * is supplied. - * - * On success, returns a JSON block as String with any data returned by the - * REST client. Throws an exception on any failure. - * - * @param dmaapAccess - * Access details for the DMaaP REST API - * @param userId - * The login ID of the user making the request - * @param itemType - * DMaaP item type to add - * @param itemContent - * JSON block to deserialize as an object - * @param scAddlStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return JSON object with result of the operation - * @throws Exception - * on any problem - */ - private String addDmaapItem(DmaapAccess dmaapAccess, String userId, DmaapDataItem itemType, String itemContent, - Integer scAddlStatus) throws Exception { - DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); - HttpStatusAndResponse hsr = null; - switch (itemType) { - case DR_FEED: - Feed feed = mapper.readValue(itemContent, Feed.class); - logger.debug("addDmaapItem: received feed: {} ", feed); - // Null out any ID to get an auto-generated ID - feed.setFeedId(null); - // Assign the owner to be the webapp user - feed.setOwner(userId); - hsr = restClient.postFeed(feed); - break; - case DR_PUB: - DR_Pub pub = mapper.readValue(itemContent, DR_Pub.class); - logger.debug("addDmaapItem: received pub: {} ", pub); - // Null out any ID to get an auto-generated ID - pub.setPubId(null); - hsr = restClient.postDRPub(pub); - break; - case DR_SUB: - DR_Sub sub = mapper.readValue(itemContent, DR_Sub.class); - logger.debug("addDmaapItem: received sub: {} ", sub); - // Null out any ID to get an auto-generated ID - sub.setSubId(null); - // Assign the owner to be the webapp user - sub.setOwner(userId); - hsr = restClient.postDRSub(sub); - break; - case MR_TOPIC: - Topic topic = mapper.readValue(itemContent, Topic.class); - logger.debug("addDmaapItem: received topic: {} ", topic); - // No ID on topic - topic.setOwner(userId); - hsr = restClient.postTopic(topic); - break; - case MR_CLIENT: - MR_Client client = mapper.readValue(itemContent, MR_Client.class); - logger.debug("addDmaapItem: received client: {} ", client); - client.setMrClientId(null); - hsr = restClient.postMRClient(client); - break; - default: - throw new Exception("addDmaapItem: pgmr error, unimplemented case: " + itemType.name()); - } - - // Build result here - String outboundJson = null; - if (hsr.getStatusCode() == HttpServletResponse.SC_OK - || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { - outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); - } else { - throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) - + " with content " + hsr.getResponseString()); - } - return outboundJson; - } - - /** - * Adds the specified DMaaP item that is read from the request body. This - * method traps errors and constructs an appropriate JSON block if an error - * happens. - * - * @param request - * Used to obtain user info from the active session - * @param itemType - * DMaaP item type to add - * @param scAddlStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return JSON block with success or failure object - */ - protected String addItem(HttpServletRequest request, DmaapDataItem itemType, Integer scAddlStatus) { - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("addDmaapItem: Failed to get Login ID"); - - DmaapAccess access = getSelectedDmaapAccess(appUser.getLoginId()); - if (access == null) // leap into exception handler - throw new Exception("No DMaaP access profiles are configured."); - String jsonContent = getBody(request); - outboundJson = addDmaapItem(access, appUser.getLoginId(), itemType, jsonContent, scAddlStatus); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to add DMaaP item " + itemType.name(), ex); - } - - return outboundJson; - } - - /** - * Updates an item of the specified type with the specified content. - * Constructs an object by deserializing the JSON block. - * - * On success, returns a JSON block as String with any data returned by the - * REST client. Throws an exception on any failure. - * - * @param dmaapAccess - * Access details for the DMaaP REST API - * @param userId - * The Login ID of the user making the request - * @param itemType - * DMaaP item type to update - * @param itemId - * Item identification - * @param itemContent - * JSON block to deserialize as an object - * @param scAddlStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return JSON object with result of the operation - * @throws Exception - * on any problem - */ - private String updateDmaapItem(DmaapAccess dmaapAccess, String userId, DmaapDataItem itemType, String itemId, - String itemContent, Integer scAddlStatus) throws Exception { - DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); - HttpStatusAndResponse hsr = null; - switch (itemType) { - case DR_FEED: - Feed feed = mapper.readValue(itemContent, Feed.class); - logger.debug("updateDmaapItem: received feed: {} ", feed); - // Ensure the owner is the webapp user - feed.setOwner(userId); - hsr = restClient.putFeed(feed); - break; - case DR_PUB: - DR_Pub pub = mapper.readValue(itemContent, DR_Pub.class); - logger.debug("updateDmaapItem: received pub: {} ", pub); - hsr = restClient.putDRPub(pub); - break; - case DR_SUB: - DR_Sub sub = mapper.readValue(itemContent, DR_Sub.class); - logger.debug("updateDmaapItem: received sub: {} ", sub); - // Ensure the owner is the webapp user - sub.setOwner(userId); - hsr = restClient.putDRSub(sub); - break; - case MR_TOPIC: - Topic topic = mapper.readValue(itemContent, Topic.class); - logger.debug("updateDmaapItem: received topic: {} ", topic); - // Ensure the owner is the webapp user - topic.setOwner(userId); - // DCAE backend may implement PUT someday. - if (true && userId != null) - throw new UnsupportedOperationException("put topic not supported (yet)"); - break; - case MR_CLIENT: - MR_Client client = mapper.readValue(itemContent, MR_Client.class); - logger.debug("updateDmaapItem: received client: {} ", client); - hsr = restClient.putMRClient(client); - break; - default: - throw new Exception("updateDmaapItem: pgmr error, unimplemented case: " + itemType.name()); - } - - // Build result here - String outboundJson = null; - if (hsr.getStatusCode() == HttpServletResponse.SC_OK - || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { - outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); - } else { - throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) - + " with content " + hsr.getResponseString()); - } - return outboundJson; - } - - /** - * Updates the specified DMaaP item that is read from the request body. This - * method traps errors and constructs an appropriate JSON block if an error - * happens. - * - * @param request - * Used to obtain user info from the active session - * @param itemType - * DMaaP item type to update - * @param itemId - * Item identification to update - * @param scUpdatelStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return JSON object with success or error information. - */ - protected String updateItem(HttpServletRequest request, DmaapDataItem itemType, String itemId, - Integer scUpdatelStatus) { - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("updateItem: Failed to get Login ID"); - DmaapAccess access = getSelectedDmaapAccess(appUser.getLoginId()); - if (access == null) // leap into exception handler - throw new Exception("No DMaaP access profiles are configured."); - String jsonContent = getBody(request); - outboundJson = updateDmaapItem(access, appUser.getLoginId(), itemType, itemId, jsonContent, - scUpdatelStatus); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to update DMaaP item " + itemType.name(), ex); - } - - return outboundJson; - } - - /** - * Deletes an item of the specified type with the specified ID. - * - * @param dmaapAccess - * Access details for the DMaaP REST API - * @param itemType - * DMaaP item type to delete - * @param itemId - * Item identification - * @param scAddlStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return On success, returns a JSON block as String with any data returned - * by the REST client. - * @throws Exception - * On any failure. - */ - private String deleteDmaapItem(DmaapAccess dmaapAccess, DmaapDataItem itemType, String itemId, Integer scAddlStatus) - throws Exception { - DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); - HttpStatusAndResponse hsr = null; - switch (itemType) { - case DR_FEED: - hsr = restClient.deleteFeed(itemId); - break; - case DR_PUB: - hsr = restClient.deleteDRPub(itemId); - break; - case DR_SUB: - hsr = restClient.deleteDRSub(itemId); - break; - case MR_TOPIC: - hsr = restClient.deleteTopic(itemId); - break; - case MR_CLIENT: - hsr = restClient.deleteMRClient(itemId); - break; - default: - throw new Exception("deleteDmaapItem: pgmr error, unimplemented case: " + itemType.name()); - } - - // Build result here - String outboundJson = null; - if (hsr.getStatusCode() == HttpServletResponse.SC_OK - || (scAddlStatus != null && hsr.getStatusCode() == scAddlStatus)) { - outboundJson = buildJsonSuccess(hsr.getStatusCode(), hsr.getResponseString()); - } else { - throw new Exception("Unexpected HTTP response code " + Integer.toString(hsr.getStatusCode()) - + " with content " + hsr.getResponseString()); - } - return outboundJson; - } - - /** - * Deletes the specified DMaaP item. This method traps errors and constructs - * an appropriate JSON block if an error happens. - * - * @param request - * Used to obtain user info from the active session - * @param itemType - * DMaaP item type to delete - * @param itemId - * item ID to delete - * @param scAddlStatus - * HTTP status code 200 is always accepted. If this parameter is - * not null, the value is also considered a valid HTTP status - * code on success; e.g., 204. - * @return JSON object with success or error information. - */ - protected String deleteItem(HttpServletRequest request, DmaapDataItem itemType, String itemId, - Integer scAddlStatus) { - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("deleteItem: Failed to get Login ID"); - DmaapAccess selected = getSelectedDmaapAccess(appUser.getLoginId()); - if (selected == null) // leap into exception handler - throw new Exception("No DMaaP access profiles are configured."); - outboundJson = deleteDmaapItem(selected, itemType, itemId, scAddlStatus); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to delete DMaaP item " + itemType.name() + " ID " + itemId, ex); - } - return outboundJson; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java deleted file mode 100644 index 5f81a74..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/DmaapAccessController.java +++ /dev/null @@ -1,356 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.dcae.dmaapbc.client.DmaapBcRestClient; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.DmaapAccess; -import org.openecomp.dcae.dmaapbc.model.Dmaap; -import org.openecomp.dcae.dmaapbc.model.DmaapObject; -import org.openecomp.dcae.dmaapbc.model.ErrorResponse; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.openecomp.portalsdk.core.web.support.UserUtils; -import org.slf4j.MDC; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * DMaaP Access controller: serves Ajax requests made by Angular on pages where - * the user adds, edits and deletes DMaaP access profiles. This controller must - * defend the database against rogue requests including SQL injection attacks. - */ -@Controller -@RequestMapping("/") -public class DmaapAccessController extends DbcappRestrictedBaseController { - - /** - * Logger that conforms with ECOMP guidelines - */ - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(DmaapAccessController.class); - - private static final String DMAAP_ACCESS_PATH = "/dmaap_access"; - private static final String SELECT_DMAAP_ACCESS_PATH = "/select_dmaap_access"; - - /** - * For general use in these methods - */ - private final ObjectMapper mapper; - - /** - * Never forget that Spring autowires fields AFTER the constructor is - * called. - */ - public DmaapAccessController() { - mapper = new ObjectMapper(); - } - - /** - * Gets a list of DMaaP access profiles for this user from the database and - * returns them in a JSON array nested within a response object. Traps errors and constructs an appropriate JSON block if an error - * happens. - * - * See {@link #getOrInitDmaapAccessList(String)}. - * - * @param request - * HttpServletRequest - * @return JSON with access profiles, or an error JSON if the request fails. - */ - @RequestMapping(value = { DMAAP_ACCESS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getDmaapAccessList(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("getDmaapAccessList: Failed to get Login ID"); - List dbAccessList = getOrInitDmaapAccessList(appUser.getLoginId()); - // Wrap the list in the status indicator. - Map model = new HashMap(); - model.put(STATUS_RESPONSE_KEY, new Integer(200)); - model.put(DATA_RESPONSE_KEY, dbAccessList); - outboundJson = mapper.writeValueAsString(model); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to get DMaaP access profile list", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Adds a DMaaP access profile for the requesting user ID; ignores any - * values for row ID and user ID in the body. Traps errors and - * constructs an appropriate JSON block if an error happens. - * - * @param request - * HttpServletRequest - * @return Trivial JSON object indicating success or failure. - */ - @RequestMapping(value = { DMAAP_ACCESS_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addDmaapAccess(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("addDmaapAccess: Failed to get Login ID"); - - DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); - logger.debug("addDmaapAccess: received object: {} ", dmaapAccess); - - // Null out ID to get an auto-generated ID - dmaapAccess.setId(null); - // Overwrite any submitted user id - dmaapAccess.setUserId(appUser.getLoginId()); - // Encrypt password - if (dmaapAccess.getPassword() != null) - dmaapAccess.encryptPassword(dmaapAccess.getPassword()); - - // Create a new row - getDmaapAccessService().saveDmaapAccess(dmaapAccess); - - // Answer success - outboundJson = buildJsonSuccess(200, null); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to add DMaaP access profile", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Updates a DMaaP access profile if the row user ID matches the requesting - * user ID. Traps errors and - * constructs an appropriate JSON block if an error happens. - * - * @param id - * Path parameter with ID of the DMaaP access profile - * @param request - * HttpServletRequest - * @return Trivial JSON object indicating success or failure. - */ - @RequestMapping(value = { DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("updateDmaapAccess: Failed to get Login ID"); - - DmaapAccess domainObj = getDmaapAccessService().getDmaapAccess(id); - if (!appUser.getLoginId().equals(domainObj.getUserId())) - throw new Exception("updateDmaapAccess: mismatch of appUser and row user ID"); - - DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); - logger.debug("updateDmaapAccess: received object: {} ", dmaapAccess); - - // Use the path-parameter id; don't trust the one in the object - dmaapAccess.setId(id); - // Encrypt password if present - if (dmaapAccess.getPassword() != null) - dmaapAccess.encryptPassword(dmaapAccess.getPassword()); - - // Update the existing row - getDmaapAccessService().saveDmaapAccess(dmaapAccess); - - // Answer "OK" - outboundJson = buildJsonSuccess(200, null); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to update DMaaP access profile", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Deletes a DMaaP access profile if the row user ID matches the requesting - * user ID. Traps errors and - * constructs an appropriate JSON block if an error happens. - * - * @param id - * Path parameter with ID of the DMaaP access profile - * @param request - * HttpServletRequest - * @return Trivial JSON object indicating success or failure (altho this is - * slightly contrary to conventions for a DELETE method) - */ - @RequestMapping(value = { - DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("deleteDmaapAccess: Failed to get Login ID"); - // Validate that this user owns the row with the specified ID - DmaapAccess domainObj = getDmaapAccessService().getDmaapAccess(id); - if (!appUser.getLoginId().equals(domainObj.getUserId())) - throw new Exception("deleteDmaapAccess: mismatch of appUser and row user ID"); - - getDmaapAccessService().deleteDmaapAccess(id); - - // Answer "OK" - outboundJson = buildJsonSuccess(200, null); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to delete DMaaP access profile", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Gets the selected DMaaP access row for the requesting user. - * - * See {@link #getSelectedDmaapAccess(String)} - * - * @param request - * HttpServletRequest - * @return JSON object with one DmaapAccessProfile, or an error - */ - @RequestMapping(value = { SELECT_DMAAP_ACCESS_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getSelectedDmaapAccessProfile(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("getSelectedDmaapAccessProfile: Failed to get Login ID"); - DmaapAccess selected = super.getSelectedDmaapAccess(appUser.getLoginId()); - // clone and decrypt - DmaapAccess clear = new DmaapAccess(selected); - try { - clear.setPassword(clear.decryptPassword()); - } catch (Exception ex) { - // Should never happen - throw new RuntimeException("getSelectedDmaapAccessProfile: Failed to decrypt password", ex); - } - outboundJson = buildJsonSuccess(200, clear); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to get selected DMaaP access profile", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Marks the DMaaP access row as selected (first choice) for the requesting - * user if the row user ID matches the requesting user ID. As a side effect, - * removes selected marking from all other user rows. Returns status, - * additionally an error message on failure. Traps errors and - * constructs an appropriate JSON block if an error happens. - * - * Choice of PUT is fairly arbitrary - there is no body, but GET is for - * actions that do not change data. - * - * @param id - * Path parameter with ID of the DMaaP access profile - * @param request - * HttpServletRequest - * @return Trivial JSON object indicating success or failure. - */ - @RequestMapping(value = { - SELECT_DMAAP_ACCESS_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String selectDmaapAccess(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - User appUser = UserUtils.getUserSession(request); - if (appUser == null || appUser.getLoginId() == null || appUser.getLoginId().length() == 0) - throw new Exception("selectDmaapAccess: Failed to get Login UID"); - // A little inefficient in that it requires 3 database accesses; - // probably could be done in 1 with some sophisticated SQL. - List dmaapAccessList = getDmaapAccessService().getDmaapAccessList(appUser.getLoginId()); - for (DmaapAccess dmaap : dmaapAccessList) { - // Only write out the changed rows. - boolean changed = false; - if (id == dmaap.getId()) { - changed = !dmaap.getSelected(); - dmaap.setSelected(true); - } else { - changed = dmaap.getSelected(); - dmaap.setSelected(false); - } - if (changed) - getDmaapAccessService().saveDmaapAccess(dmaap); - } - - // Answer OK - outboundJson = buildJsonSuccess(200, null); - } catch (Exception ex) { - outboundJson = buildJsonError(500, "Failed to select a DMaaP access profile", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - - /** - * Tests the URL in the DMaaP access profile object. Traps errors and - * constructs an appropriate JSON block if an error happens. - * - * @param request - * HttpServletRequest - * @return JSON with a Dmaap object (which has name etc.) on success, error - * on failure. - */ - @RequestMapping(value = { "test_dmaap_access" }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String testDmaapAccess(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String outboundJson = null; - try { - DmaapAccess dmaapAccess = mapper.readValue(request.getReader(), DmaapAccess.class); - logger.debug("testDmaapAccess: received object: {} ", dmaapAccess); - if (dmaapAccess.getDmaapUrl() == null || dmaapAccess.getDmaapUrl().trim().length() == 0) - throw new Exception("Null or empty URL"); - - DmaapBcRestClient restClient = getDmaapBcRestClient(dmaapAccess); - // Get the instance so the page can display its name - DmaapObject dmaap = restClient.getDmaap(); - if (dmaap instanceof Dmaap) { - outboundJson = buildJsonSuccess(200, dmaap); - } else { - // Bad credentials lands here. - ErrorResponse err = (ErrorResponse) dmaap; - outboundJson = buildJsonError(500, "Test failed: " + err.getMessage(), null); - } - } catch (Exception ex) { - // This is entirely likely; e.e., unknown host exception on typo. - outboundJson = buildJsonError(500, "Invalid DMaaP URL", ex); - } - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return outboundJson; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java deleted file mode 100644 index 5754244..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/HealthCheckController.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.dcae.dmaapbc.dbcapp.service.DmaapAccessService; -import org.openecomp.portalsdk.core.controller.UnRestrictedBaseController; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * This controller responds to probes for application health, returning a JSON - * body to indicate current status. - */ -@RestController -@Configuration -@EnableAspectJAutoProxy -@RequestMapping("/") -public class HealthCheckController extends UnRestrictedBaseController { - - private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HealthCheckController.class); - - private static final String HEALTH_CHECK_PATH = "/healthCheck"; - - @Autowired - private DmaapAccessService dmaapAccessService; - - /** - * Model for JSON response with health-check results. - */ - public class HealthStatus { - // Either 200 or 500 - public int statusCode; - // Additional detail in case of error, empty in case of success. - public String message; - - public HealthStatus(int code, String msg) { - this.statusCode = code; - this.message = msg; - } - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int code) { - this.statusCode = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String msg) { - this.message = msg; - } - } - - /** - * Checks application health by making a trivial query to the database. - * - * @param request - * HttpServletRequest - * @return 200 if database access succeeds, 500 if it fails. - */ - @RequestMapping(value = { HEALTH_CHECK_PATH }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus healthCheck(HttpServletRequest request) { - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - HealthStatus healthStatus = null; - try { - logger.debug(EELFLoggerDelegate.debugLogger, "Performing health check"); - dmaapAccessService.getDmaapAccessCount(); - healthStatus = new HealthStatus(200, "health check succeeded"); - } catch (Exception ex) { - logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex); - healthStatus = new HealthStatus(500, "health check failed: " + ex.toString()); - } - return healthStatus; - } - - /** - * This implementation does not support suspend/resume. - * - * @param request - * HttpServletRequest - * @return Trivial success - */ - @RequestMapping(value = { - HEALTH_CHECK_PATH + "/suspend" }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus healthCheckSuspend(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - HealthStatus response = new HealthStatus(200, "suspend not implemented"); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * This implementation does not support suspend/resume. - * - * @param request - * HttpServletRequest - * @return Trivial success - */ - @RequestMapping(value = { - HEALTH_CHECK_PATH + "/resume" }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus healthCheckResume(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - HealthStatus response = new HealthStatus(200, "resume not implemented"); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Answers ping request without checking the application health. - * - * @param request - * HttpServletRequest - * @return Trivial success - */ - @RequestMapping(value = { HEALTH_CHECK_PATH + "/ping" }, method = RequestMethod.GET, produces = "application/json") - public HealthStatus ping(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - HealthStatus response = new HealthStatus(200, "ping received"); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java deleted file mode 100644 index 9d889dd..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/controller/MessageRouterController.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.controller; - -import java.util.Date; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.slf4j.MDC; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -/** - * Message Router controller: serves Ajax requests made by Angular scripts on - * pages that show topics and clients. - */ -@Controller -@RequestMapping("/") -public class MessageRouterController extends DbcappRestrictedBaseController { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MessageRouterController.class); - - private static final String TOPIC_PATH = "/mr_topic"; - private static final String CLIENT_PATH = "/mr_client"; - - public MessageRouterController() { - } - - /** - * Answers a request for one page of message router topics. See - * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} - * - * @param request - * HttpServletRequest - * @return One page of MR topics - */ - @RequestMapping(value = { TOPIC_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getMRTopicsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = getItemListForPageWrapper(request, DmaapDataItem.MR_TOPIC); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Answers a request for one page of message router clients. See - * {@link #getItemListForPageWrapper(HttpServletRequest, DmaapDataItem)} - * - * @param request - * HttpServletRequest - * @return One page of MR clients - */ - @RequestMapping(value = { CLIENT_PATH }, method = RequestMethod.GET, produces = "application/json") - @ResponseBody - public String getMRClientsByPage(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = getItemListForPageWrapper(request, DmaapDataItem.MR_CLIENT); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Adds a topic with the specified information. Expects a JSON block in the - * request body - a Topic object. - * - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { TOPIC_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addTopic(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = addItem(request, DmaapDataItem.MR_TOPIC, HttpServletResponse.SC_CREATED); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Adds a client with the specified information. Expects a JSON block in the - * request body - a MR_Client object. - * - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { CLIENT_PATH }, method = RequestMethod.POST, produces = "application/json") - @ResponseBody - public String addMRClient(HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = addItem(request, DmaapDataItem.MR_CLIENT, HttpServletResponse.SC_CREATED); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Updates a topic with the specified information. Expects a JSON block in - * the request body - a Topic object. - * - * Writes a JSON object as an HTTP response; on success it has a "status" - * and possibly a "data" item; on failure, also has an "error" item. - * - * @param id - * ID of the topic to update - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { TOPIC_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateTopic(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = updateItem(request, DmaapDataItem.MR_TOPIC, Long.toString(id), null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Updates a client with the specified information. Expects a JSON block in - * the request body - a MR_Client object. - * - * Writes a JSON object as an HTTP response; on success it has a "status" - * and possibly a "data" item; on failure, also has an "error" item. - * - * @param id - * ID of the client to update - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { CLIENT_PATH + "/{id}" }, method = RequestMethod.PUT, produces = "application/json") - @ResponseBody - public String updateMRClient(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = updateItem(request, DmaapDataItem.MR_CLIENT, Long.toString(id), null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Deletes a topic with the FQTN ID specified as a path parameter. - * - * FQTN is a string of dot-separated names. Spring, in its infinite wisdom, - * truncates extensions on dotted path parameters; e.g., "foo.json" becomes - * "foo". Avoid truncation here with the extra ":.+" incantation at the end. - * - * Writes a JSON object as an HTTP response; on success it only has "status" - * item; on failure, also has an "error" item. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { "/mr_topic/{id:.+}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteTopic(@PathVariable("id") String id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = deleteItem(request, DmaapDataItem.MR_TOPIC, id, 204); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - - /** - * Deletes a client with the mrClientId specified as a path parameter. - * - * Writes a JSON object as an HTTP response; on success it only has "status" - * item; on failure, also has an "error" item. - * - * @param id - * Path parameter with object ID - * @param request - * HttpServletRequest - * @return JSON success/failure response - */ - @RequestMapping(value = { "/mr_client/{id}" }, method = RequestMethod.DELETE, produces = "application/json") - @ResponseBody - public String deleteMRClient(@PathVariable("id") long id, HttpServletRequest request) { - MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, DataBusHomeController.APP_NAME); - String response = deleteItem(request, DmaapDataItem.MR_CLIENT, Long.toString(id), null); - MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, DataBusHomeController.logDateFormat.format(new Date())); - logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI()); - return response; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java deleted file mode 100644 index 3edd3ba..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/DmaapAccess.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.domain; - -import org.openecomp.portalsdk.core.domain.support.DomainVo; -import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; - -/** - * Hold an access profile for a DMaaP REST endpoint. Represents one row in the - * DBCA_DMAAP table. - */ -public class DmaapAccess extends DomainVo { - - private static final long serialVersionUID = 6443219375733216340L; - - // parent class defines these fields: - // ID, created, modified, created_id, modified_id - - /** Login ID for user who owns this row */ - private String userId; - /** Nickname for this row */ - private String name; - /** REST API endpoint */ - private String dmaapUrl; - /** Credentials */ - private String mechId; - /** Credentials */ - private String password; - /** User's preferred access profile */ - private boolean selected; - - /** - * Standard POJO no-arg constructor - */ - public DmaapAccess() { - } - - /** - * Copy constructor - * - * @param copy - * Instance to copy - */ - public DmaapAccess(final DmaapAccess copy) { - // Unfortunately DomainVo doesn't provide a copy constructor; - // only the ID field is needed. - this.id = copy.id; - // Our fields - this.userId = copy.userId; - this.name = copy.name; - this.dmaapUrl = copy.dmaapUrl; - this.mechId = copy.mechId; - this.password = copy.password; - this.selected = copy.selected; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDmaapUrl() { - return dmaapUrl; - } - - public void setDmaapUrl(String dmaapUrl) { - this.dmaapUrl = dmaapUrl; - } - - public String getMechId() { - return mechId; - } - - public void setMechId(String mechId) { - this.mechId = mechId; - } - - /** - * Gets the encrypted password. Applications should use - * {@link #decryptPassword()}! - * - * @return The encrypted password - */ - public String getPassword() { - return password; - } - - /** - * Sets the encrypted password. Applications should use - * {@link #encryptPassword(String)}! - * - * @param password - * The encrypted password - */ - public void setPassword(String password) { - this.password = password; - } - - public boolean getSelected() { - return selected; - } - - public void setSelected(boolean selected) { - this.selected = selected; - } - - /** - * A getter that decrypts the value read from the database and returns the - * clear text. Has no side effects. - * - * @return Clear-text password. - * @throws Exception - * If the password cannot be decrypted - */ - public String decryptPassword() throws Exception { - if (password == null) - return null; - return CipherUtil.decrypt(password); - } - - /** - * A setter that encrypts the clear-text in preparation for storing in the - * database. - * - * @param clearText - * The clear-text password to be encrypted - * @throws Exception - * If the password cannot be encrypted - */ - public void encryptPassword(String clearText) throws Exception { - if (clearText == null) { - password = null; - return; - } - password = CipherUtil.encrypt(clearText); - } - - @Override - public String toString() { - return "DmaapAccess[id=" + id + ", url=" + dmaapUrl + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java deleted file mode 100644 index a98f14d..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/domain/ManifestTransportModel.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.domain; - -import java.util.Map; - -/** - * Holds a set of String key-value pairs, the JSON version of a - * java.util.Attributes object read from a jar/war file. - */ -public class ManifestTransportModel { - - private Map manifest; - - /** - * Standard POJO no-arg constructor - */ - public ManifestTransportModel() { - } - - public Map getManifest() { - return manifest; - } - - public void setManifest(Map manifest) { - this.manifest = manifest; - } - - @Override - public String toString() { - return "Manifest[size=" + manifest.size() + "]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java deleted file mode 100644 index 3700c3d..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestClient.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.rest; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import org.apache.http.HttpHost; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.DmaapAccess; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; -import org.openecomp.dcae.dmaapbc.dbcapp.service.DmaapAccessService; -import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; -import org.springframework.web.client.RestTemplate; - -/** - * Provides methods for accessing the DBC microservice via REST using basic HTTP - * authentication. - * - */ -public class DbcUsvcRestClient implements DmaapAccessService { - - public static final String endpointPath = "/dmaap_access"; - private final String baseUrl; - private final RestTemplate restTemplate; - - /** - * Builds a restTemplate that uses basic HTTP authentication for use by all - * methods in this class. - * - * @param webapiUrl - * URL of the web endpoint - * @param user - * user name - * @param pass - * password - */ - public DbcUsvcRestClient(String webapiUrl, String user, String pass) { - if (webapiUrl == null || user == null || pass == null) - throw new IllegalArgumentException("Nulls not permitted"); - - baseUrl = webapiUrl; - URL url = null; - try { - url = new URL(baseUrl); - } catch (MalformedURLException ex) { - throw new RuntimeException("Failed to parse URL", ex); - } - final HttpHost httpHost = new HttpHost(url.getHost(), url.getPort()); - - // Build a client with a credentials provider - CredentialsProvider credsProvider = new BasicCredentialsProvider(); - credsProvider.setCredentials(new AuthScope(httpHost), new UsernamePasswordCredentials(user, pass)); - HttpClientBuilder clientBuilder = HttpClientBuilder.create(); - CloseableHttpClient httpClient = clientBuilder.setDefaultCredentialsProvider(credsProvider).build(); - - // Create request factory with our superpower client - HttpComponentsClientHttpRequestFactoryBasicAuth requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth( - httpHost); - requestFactory.setHttpClient(httpClient); - - // Put the factory in the template - this.restTemplate = new RestTemplate(); - restTemplate.setRequestFactory(requestFactory); - } - - /** - * Gets the manifest from the micro service. - */ - @Override - public ManifestTransportModel getManifest() { - String url = baseUrl + "/manifest"; - ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, - ManifestTransportModel.class); - ManifestTransportModel response = daResponse.getBody(); - return response; - } - - /** - * Gets the count of DMaaP access profiles. - * - * @return Number of access profiles in the database. - */ - public int getDmaapAccessCount() { - String url = baseUrl + "/count_dmaap_access"; - ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, - DbcUsvcRestResponse.class); - DbcUsvcRestResponse response = daResponse.getBody(); - return response.getStatus(); - } - - /** - * Gets the DMaaP access profiles for the specified userId. - * - * @param userId - * User ID - * @return List of access profiles - */ - @Override - public List getDmaapAccessList(final String userId) { - String url = baseUrl + endpointPath + "?userId=" + userId; - ResponseEntity> daResponse = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference>() { - }); - List daList = daResponse.getBody(); - return daList; - } - - /** - * Gets the specified DMaaP access profile. - */ - @Override - public DmaapAccess getDmaapAccess(Long dmaapId) { - String url = baseUrl + endpointPath + "?dmaapId=" + dmaapId; - ResponseEntity daResponse = restTemplate.exchange(url, HttpMethod.GET, null, - new ParameterizedTypeReference() { - }); - DmaapAccess da = daResponse.getBody(); - return da; - } - - /** - * POSTs or PUTs the DMaaP access profile as needed, based on whether the - * object's ID field is set. If not set it creates a new row; if set, it - * updates a row in the remote service table. - * - * @param dmaapAccess - * Access profile - */ - @Override - public void saveDmaapAccess(final DmaapAccess dmaapAccess) { - if (dmaapAccess.getId() == null) { - String url = baseUrl + endpointPath; - restTemplate.postForObject(url, dmaapAccess, String.class); - } else { - String url = baseUrl + endpointPath + "/" + Long.toString(dmaapAccess.getId()); - restTemplate.put(url, dmaapAccess); - } - } - - /** - * Deletes the DMaaP access profile row in the remote service table with the - * specified id. - * - * @param id - * Access profile ID - */ - @Override - public void deleteDmaapAccess(final Long id) { - String url = baseUrl + endpointPath + "/" + Long.toString(id); - restTemplate.delete(url); - } - - /** - * Simple test - * - * @param args - * UserID - * @throws Exception - * On any failure - */ - public static void main(String[] args) throws Exception { - if (args.length != 1) - throw new IllegalArgumentException("Single argument expected: userid"); - DbcUsvcRestClient client = new DbcUsvcRestClient("http://localhost:8081/dbus", "dbus_user", "dbus_pass"); - final String userId = args[0]; - System.out.println("Requesting profiles for user " + userId); - List access = client.getDmaapAccessList(userId); - if (access == null) - System.err.println("Received null"); - else - for (DmaapAccess da : access) - System.out.println(da); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java deleted file mode 100644 index 98cfc20..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/DbcUsvcRestResponse.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.rest; - -/** - * Models the responses sent by the micro service in JSON format. - */ -public class DbcUsvcRestResponse { - - private int status; - private String data, error, exception; - - public int getStatus() { - return status; - } - - public void setStatus(int status) { - this.status = status; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - - public String getError() { - return error; - } - - public void setError(String error) { - this.error = error; - } - - public String getException() { - return exception; - } - - public void setException(String exception) { - this.exception = exception; - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java deleted file mode 100644 index 432d61c..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/rest/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.rest; - -import java.net.URI; - -import org.apache.http.HttpHost; -import org.apache.http.client.AuthCache; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; - -/** - * Utility class to enable Basic HTTP Authentication with Spring REST templates. - * - * From: - * http://www.baeldung.com/2012/04/16/how-to-use-resttemplate-with-basic-authentication-in-spring-3-1/ - */ -public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { - - private HttpHost host; - - public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) { - super(); - this.host = host; - } - - protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { - return createHttpContext(); - } - - private HttpContext createHttpContext() { - // Create AuthCache instance - AuthCache authCache = new BasicAuthCache(); - // Generate BASIC scheme object and add it to the local auth cache - BasicScheme basicAuth = new BasicScheme(); - authCache.put(host, basicAuth); - - // Add AuthCache to the execution context - BasicHttpContext localcontext = new BasicHttpContext(); - localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); - return localcontext; - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java deleted file mode 100644 index c4d85bf..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessService.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.service; - -import java.util.List; - -import org.openecomp.dcae.dmaapbc.dbcapp.domain.DmaapAccess; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; - -/** - * Defines methods to manipulate the database table with DmaapAccess domain - * objects. No method throws a checked exception, in keeping with the Spring - * philosophy of throwing unchecked exceptions. - */ -public interface DmaapAccessService { - - /** - * Gets build information. - * - * @return List of key-value pairs; implementations may return null. - */ - ManifestTransportModel getManifest(); - - /** - * Gets the number of Dmaap Access entries. - * - * @return Number of rows in the table. - */ - int getDmaapAccessCount(); - - /** - * Gets all DMaaP access rows in the table for the specified user. - * - * @param userId - * Login ID of the user - * @return List of DMaaP instance objects, which may be empty. - */ - List getDmaapAccessList(String userId); - - /** - * Gets the DMaaP access object with the specified row ID. - * - * @param dmaapId - * Access profile ID - * @return DMaap instance; null if none exists. - */ - DmaapAccess getDmaapAccess(Long dmaapId); - - /** - * Creates a new managed object (a new row in the table). - * - * @param dmaap - * DMaaP instance to create. - */ - void saveDmaapAccess(DmaapAccess dmaap); - - /** - * Deletes the DMaaP access row with the specified ID. - * - * @param dmaapId - * Access profile ID - */ - void deleteDmaapAccess(Long dmaapId); - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java deleted file mode 100644 index bca8458..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/service/DmaapAccessServiceImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.service; - -import java.util.ArrayList; -import java.util.List; - -import org.hibernate.criterion.Criterion; -import org.hibernate.criterion.Restrictions; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.DmaapAccess; -import org.openecomp.dcae.dmaapbc.dbcapp.domain.ManifestTransportModel; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - * Hibernate-assisted methods to manipulate the DBCA_DMAAP table. - */ -@Service("dmaapAccessService") -@Transactional -public class DmaapAccessServiceImpl implements DmaapAccessService { - - @Autowired - private DataAccessService dataAccessService; - - public DataAccessService getDataAccessService() { - return dataAccessService; - } - - public void setDataAccessService(DataAccessService dataAccessService) { - this.dataAccessService = dataAccessService; - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#getManifest() - */ - @Override - public ManifestTransportModel getManifest() { - return null; - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccessCount() - */ - @SuppressWarnings("unchecked") - @Override - public int getDmaapAccessCount() { - List accesses = (List) getDataAccessService().getList(DmaapAccess.class, null); - return accesses.size(); - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccessList(java.lang.String) - */ - @SuppressWarnings("unchecked") - @Override - public List getDmaapAccessList(String userId) { - List restrictionsList = new ArrayList(); - Criterion criterion1 = Restrictions.eq("userId", userId); - restrictionsList.add(criterion1); - List accesses = (List) getDataAccessService().getList(DmaapAccess.class, null, - restrictionsList, null); - return accesses; - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#getDmaapAccess(java.lang.Long) - */ - @Override - public DmaapAccess getDmaapAccess(Long dmaapId) { - return (DmaapAccess) getDataAccessService().getDomainObject(DmaapAccess.class, dmaapId, null); - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#saveDmaapAccess(org.openecomp.dmaapbc.dbcapp.domain.DmaapAccess) - */ - @Override - public void saveDmaapAccess(DmaapAccess dmaap) { - getDataAccessService().saveDomainObject(dmaap, null); - } - - /* - * (non-Javadoc) - * @see org.openecomp.dmaapbc.dbcapp.service.DmaapAccessService#deleteDmaapAccess(java.lang.Long) - */ - @Override - public void deleteDmaapAccess(Long dmaapId) { - DmaapAccess dmaapAccess = getDmaapAccess(dmaapId); - if (dmaapAccess != null) - getDataAccessService().deleteDomainObject(dmaapAccess, null); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/util/DbcappProperties.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/util/DbcappProperties.java deleted file mode 100644 index b08e007..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/dbcapp/util/DbcappProperties.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.openecomp.dcae.dmaapbc.dbcapp.util; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; -import org.springframework.core.env.Environment; - -/** - * Publishes a list of constants and methods to access the properties that are - * read by Spring from the specified configuration file(s). - * - * Should be used like this (and never in a constructor): - * - *
- * @Autowired
- * DbcappProperties properties;
- * 
- */ -@Configuration -@PropertySource(value = { "${container.classpath:}/WEB-INF/dbcapp/dbcapp.properties" }) -public class DbcappProperties { - - public static final String DMAAP_REST_URL_LIST = "dmaap.rest.url.list"; - public static final String DMAAP_MECHID_NAME = "dmaap.mechid.name"; - public static final String DMAAP_MECHID_PASSWORD = "dmaap.mechid.password"; - public static final String PROFILE_ACCESS_METHOD = "profile.access.method"; - public static final String PROFILE_USVC_URL = "profile.microservice.url"; - public static final String PROFILE_USVC_USER = "profile.microservice.user.name"; - public static final String PROFILE_USVC_PASS = "profile.microservice.user.password"; - public static final String DMAAP_PII_TYPE_LIST = "dmaap.pii.type.list"; - - private Environment environment; - - public DbcappProperties() { - } - - protected Environment getEnvironment() { - return environment; - } - - @Autowired - public void setEnvironment(final Environment environment) { - this.environment = environment; - } - - public boolean containsProperty(String key) { - return environment.containsProperty(key); - } - - public String getProperty(String key) { - return environment.getRequiredProperty(key); - } - - /** - * Gets the values for a comma-separated list property value as a String - * array. - * - * @param key - * Property key - * @return Array of values with leading and trailing whitespace removed; - * null if key is not found. - */ - public String[] getCsvListProperty(final String key) { - String listVal = getProperty(key); - if (listVal == null) - return null; - String[] vals = listVal.split("\\s*,\\s*"); - return vals; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Node.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Node.java deleted file mode 100644 index 87ad86e..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Node.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP Data Router node. - */ -public class DR_Node extends DmaapObject { - - private String fqdn; - /** dcaeLocation where node VM is deployed */ - private String dcaeLocationName; - /** - * name for this VM (sometimes this is a local VM name and may be different - * than FQDN) - */ - private String hostName; - /** version of Node software package */ - private String version; - - public DR_Node() { - } - - public DR_Node(String lastMod, Dmaap_Status status, String fqdn, String dcaeLocationName, String hostName, - String version) { - super(lastMod, status); - this.fqdn = fqdn; - this.dcaeLocationName = dcaeLocationName; - this.hostName = hostName; - this.version = version; - } - - public String getFqdn() { - return fqdn; - } - - public void setFqdn(String fqdn) { - this.fqdn = fqdn; - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - @Override - public String toString() { - return "DR_Node[fqdn=" + fqdn + ", dcaeLocationName=" + dcaeLocationName + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Pub.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Pub.java deleted file mode 100644 index fe0aeca..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Pub.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP Data Router publisher. - */ -public class DR_Pub extends DmaapObject { - - /** dcaeLocation tag where this publisher is deployed */ - private String dcaeLocationName; - /** name used for basic authentication to DR */ - private String username; - /** password used for basic authentication to DR */ - private String userpwd; - /** tag of feed for which this publisher is a source */ - private String feedId; - /** unique id of a DCAE publisher (generated by Data Router PROV) */ - private String pubId; - - public DR_Pub() { - } - - public DR_Pub(Dmaap_Status status, String lastMod, String dcaeLocationName, String username, String userpwd, - String feedId, String pubId) { - super(lastMod, status); - this.dcaeLocationName = dcaeLocationName; - this.username = username; - this.userpwd = userpwd; - this.feedId = feedId; - this.pubId = pubId; - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getUserpwd() { - return userpwd; - } - - public void setUserpwd(String userpwd) { - this.userpwd = userpwd; - } - - public String getFeedId() { - return feedId; - } - - public void setFeedId(String feedId) { - this.feedId = feedId; - } - - public String getPubId() { - return pubId; - } - - public void setPubId(String pubId) { - this.pubId = pubId; - } - - @Override - public String toString() { - return "DR_Pub[dcaeLocationName=" + dcaeLocationName + ", feedId=" + feedId + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Sub.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Sub.java deleted file mode 100644 index 45adf9c..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DR_Sub.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP Data Router subscriber. - */ -public class DR_Sub extends DmaapObject { - - /** Tag where this publisher is deployed */ - private String dcaeLocationName; - /** name used for basic authentication from DR */ - private String username; - /** password used for basic authentication from DR */ - private String userpwd; - /** tag of feed for which this publisher is a source */ - private String feedId; - /** URL used by DR to deliver files to this subscriber */ - private String deliveryURL; - /** URL for accessing the transaction log for this susbcriber */ - private String logURL; - /** unique ID for a subscriber in this DR environment */ - private String subId; - /** TODO */ - private boolean suspended; - /** TODO */ - private boolean use100; - /** TODO */ - private String owner; - - public DR_Sub() { - } - - public DR_Sub(String lastMod, Dmaap_Status status, String dcaeLocationName, String username, String userpwd, - String feedId, String deliveryURL, String logURL, String subId, boolean suspended, boolean use100, - String owner) { - super(lastMod, status); - this.dcaeLocationName = dcaeLocationName; - this.username = username; - this.userpwd = userpwd; - this.feedId = feedId; - this.deliveryURL = deliveryURL; - this.logURL = logURL; - this.subId = subId; - this.suspended = suspended; - this.use100 = use100; - this.owner = owner; - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getUserpwd() { - return userpwd; - } - - public void setUserpwd(String userpwd) { - this.userpwd = userpwd; - } - - public String getFeedId() { - return feedId; - } - - public void setFeedId(String feedId) { - this.feedId = feedId; - } - - public String getDeliveryURL() { - return deliveryURL; - } - - public void setDeliveryURL(String deliveryURL) { - this.deliveryURL = deliveryURL; - } - - public String getLogURL() { - return logURL; - } - - public void setLogURL(String logURL) { - this.logURL = logURL; - } - - public String getSubId() { - return subId; - } - - public void setSubId(String subId) { - this.subId = subId; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public boolean isSuspended() { - return suspended; - } - - public void setSuspended(boolean suspended) { - this.suspended = suspended; - } - - public boolean isUse100() { - return use100; - } - - public void setUse100(boolean use100) { - this.use100 = use100; - } - - @Override - public String toString() { - return "DR_Sub[dcaeLocationName=" + dcaeLocationName + ", feedId=" + feedId + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DcaeLocation.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DcaeLocation.java deleted file mode 100644 index c0a79c1..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DcaeLocation.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP DCAE location. - */ -public class DcaeLocation extends DmaapObject { - - public enum Dcae_Status { - EMPTY, NEW, STAGED, VALID, INVALID - } - - /** - * network location code used to identify the location. - */ - private String clli; - /** - * indicator of DCAE layer. Either opendcae-central or opendcae-local-ntc - */ - private String dcaeLayer; - /** - * unique name of this dcaeLocation. Value should match what DCAE Controller - * uses. - */ - private String dcaeLocationName; - /** determines where within the OpenStack deployment the edge exists */ - private String openStackAvailabilityZone; - - public DcaeLocation() { - } - - public DcaeLocation(String lastMod, Dmaap_Status status, String clli, String dcaeLayer, String dcaeLocationName, - String openStackAvailabilityZone) { - super(lastMod, status); - this.clli = clli; - this.dcaeLayer = dcaeLayer; - this.dcaeLocationName = dcaeLocationName; - this.openStackAvailabilityZone = openStackAvailabilityZone; - } - - public String getClli() { - return clli; - } - - public void setClli(String clli) { - this.clli = clli; - } - - public String getDcaeLayer() { - return dcaeLayer; - } - - public void setDcaeLayer(String dcaeLayer) { - this.dcaeLayer = dcaeLayer; - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getOpenStackAvailabilityZone() { - return openStackAvailabilityZone; - } - - public void setOpenStackAvailabilityZone(String openStackAvailabilityZone) { - this.openStackAvailabilityZone = openStackAvailabilityZone; - } - - @Override - public String toString() { - return "DcaeLocation[dcaeLocationName=" + dcaeLocationName + ", dcaeLayer=" + dcaeLayer + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Dmaap.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Dmaap.java deleted file mode 100644 index fd00557..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Dmaap.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP instance. - */ -public class Dmaap extends DmaapObject { - - /** the version of DMaaP BC software */ - private String version; - /** the root portion of the topic namespace */ - private String topicNsRoot; - /** - * a unique identifier for this instance. - */ - private String dmaapName; - /** URL for DR Provisioning Server */ - private String drProvUrl; - /** - * topic name used by MR Bridge Admin to communicate which topics to - * replicate - */ - private String bridgeAdminTopic; - /** used by DCAE Controller to upload event logs */ - private String loggingUrl; - /** used by DCAE Controller to authenticate inter-node messages */ - private String nodeKey; - /** used by DCAE Controller to set up ssh access to VMs */ - private String accessKeyOwner; - - public Dmaap() { - } - - public Dmaap(String lastMod, Dmaap_Status status, String version, String topicNsRoot, String dmaapName, - String drProvUrl, String loggingUrl, String nodeKey, String accessKeyOwner) { - super(lastMod, status); - this.version = version; - this.topicNsRoot = topicNsRoot; - this.dmaapName = dmaapName; - this.drProvUrl = drProvUrl; - this.loggingUrl = loggingUrl; - this.nodeKey = nodeKey; - this.accessKeyOwner = accessKeyOwner; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getTopicNsRoot() { - return topicNsRoot; - } - - public void setTopicNsRoot(String topicNsRoot) { - this.topicNsRoot = topicNsRoot; - } - - public String getDmaapName() { - return dmaapName; - } - - public void setDmaapName(String dmaapName) { - this.dmaapName = dmaapName; - } - - public String getDrProvUrl() { - return drProvUrl; - } - - public void setDrProvUrl(String drProvUrl) { - this.drProvUrl = drProvUrl; - } - - public String getLogginUrl() { - return loggingUrl; - } - - public void setLogginUrl(String logginUrl) { - this.loggingUrl = logginUrl; - } - - public String getNodeKey() { - return nodeKey; - } - - public void setNodeKey(String nodeKey) { - this.nodeKey = nodeKey; - } - - public String getAccessKeyOwner() { - return accessKeyOwner; - } - - public void setAccessKeyOwner(String accessKeyOwner) { - this.accessKeyOwner = accessKeyOwner; - } - - public String getLoggingUrl() { - return loggingUrl; - } - - public void setLoggingUrl(String loggingUrl) { - this.loggingUrl = loggingUrl; - } - - public String getBridgeAdminTopic() { - return bridgeAdminTopic; - } - - public void setBridgeAdminTopic(String bridgeAdminTopic) { - this.bridgeAdminTopic = bridgeAdminTopic; - } - - @Override - public String toString() { - return "Dmaap[dmaapName=" + dmaapName + ", version=" + version + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DmaapObject.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DmaapObject.java deleted file mode 100644 index 977bf78..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/DmaapObject.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Parent class for all DMaaP BC models. - */ -public abstract class DmaapObject { - - public enum Dmaap_Status { - EMPTY, NEW, STAGED, VALID, INVALID, DELETED - } - - /** time stamp when object was last modified */ - private String lastMod; - /** indicator of health of this object using values common in this API */ - private Dmaap_Status status; - /** TODO */ - private String type; - - public DmaapObject() { - } - - public DmaapObject(String lastMod, Dmaap_Status status) { - this.lastMod = lastMod; - this.status = status; - } - - public String getLastMod() { - return lastMod; - } - - public void setLastMod(String lastMod) { - this.lastMod = lastMod; - } - - public Dmaap_Status getStatus() { - return status; - } - - public void setStatus(Dmaap_Status status) { - this.status = status; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/ErrorResponse.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/ErrorResponse.java deleted file mode 100644 index 2cdb182..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/ErrorResponse.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP Bus Controller error response. - * - * This inherits some fields (e.g., lastMod and status) that are not used. - */ -public class ErrorResponse extends DmaapObject { - - private Integer code; - private String message; - private String fields; - - public ErrorResponse() { - } - - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getFields() { - return fields; - } - - public void setFields(String fields) { - this.fields = fields; - } - - @Override - public String toString() { - return "ErrorResponse[code=" + code + ", message=" + message + ", fields=" + fields + "]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Feed.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Feed.java deleted file mode 100644 index f56aa54..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Feed.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -import java.util.ArrayList; -import java.util.List; - -/** - * Bean that models a DMaaP Data Router feed. - */ -public class Feed extends DmaapObject { - - public enum Feed_Status { - EMPTY, NEW, STAGED, VALID, INVALID, DELETED - } - - /** unique id assigned by the DR PROV server for this feed */ - private String feedId; - /** name of feed. Combined with feedVersion must be unique */ - private String feedName; - /** version of feed. Combined with feedName must be unique */ - private String feedVersion; - /** description */ - private String feedDescription; - /** ASPR classification */ - private String asprClassification; - /** provisioning URL for adding subscribers to this feed */ - private String subscribeURL; - /** URL publisher use to connect to DR */ - private String publishURL; - /** URL for transaction log for this feed */ - private String logURL; - /** indicator of whether the feed is suspended */ - private boolean suspended; - /** what identity owns this feed */ - private String owner; - /** id of format description of feed content */ - private String formatUuid; - /** a set of publishers for this feed */ - private List pubs; - /** a set of subscribers for this feed */ - private List subs; - - public Feed() { - this.pubs = new ArrayList(); - this.subs = new ArrayList(); - } - - public Feed(Dmaap_Status status, String lastMod, String feedName, String feedVersion, String feedDescription, - String asprClassification, String subscribeURL, String publishURL, String logURL, boolean suspended, - String owner, String formatUuid) { - super(lastMod, status); - this.feedName = feedName; - this.feedVersion = feedVersion; - this.feedDescription = feedDescription; - this.asprClassification = asprClassification; - this.subscribeURL = subscribeURL; - this.publishURL = publishURL; - this.logURL = logURL; - this.suspended = suspended; - this.owner = owner; - this.formatUuid = formatUuid; - this.pubs = new ArrayList(); - this.subs = new ArrayList(); - } - - public String getFeedId() { - return feedId; - } - - public void setFeedId(String feedId) { - this.feedId = feedId; - } - - public String getFeedName() { - return feedName; - } - - public void setFeedName(String feedName) { - this.feedName = feedName; - } - - public String getFeedVersion() { - return feedVersion; - } - - public void setFeedVersion(String feedVersion) { - this.feedVersion = feedVersion; - } - - public String getFeedDescription() { - return feedDescription; - } - - public void setFeedDescription(String feedDescription) { - this.feedDescription = feedDescription; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getAsprClassification() { - return asprClassification; - } - - public void setAsprClassification(String asprClassification) { - this.asprClassification = asprClassification; - } - - public String getSubscribeURL() { - return subscribeURL; - } - - public void setSubscribeURL(String subscribeURL) { - this.subscribeURL = subscribeURL; - } - - public String getPublishURL() { - return publishURL; - } - - public void setPublishURL(String publishURL) { - this.publishURL = publishURL; - } - - public String getLogURL() { - return logURL; - } - - public void setLogURL(String logURL) { - this.logURL = logURL; - } - - public boolean isSuspended() { - return suspended; - } - - public void setSuspended(boolean suspended) { - this.suspended = suspended; - } - - public String getFormatUuid() { - return formatUuid; - } - - public void setFormatUuid(String formatUuid) { - this.formatUuid = formatUuid; - } - - public List getPubs() { - return pubs; - } - - public void setPubs(List pubs) { - this.pubs = pubs; - } - - public List getSubs() { - return subs; - } - - public void setSubs(List subs) { - this.subs = subs; - } - - @Override - public String toString() { - return "Feed[feedId=" + feedId + ", feedName=" + feedName + ", feedVersion=" + feedVersion + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Client.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Client.java deleted file mode 100644 index a1abc70..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Client.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -/** - * Bean that models a DMaaP Message Router client. - */ -public class MR_Client extends DmaapObject { - - /** dcaeLocation tag where this client is deployed */ - private String dcaeLocationName; - /** fully qualified topic name */ - private String fqtn; - /** - * name of role of client which will be - * granted the AAF permission associated with any action - */ - private String clientRole; - /** an array of actions. Current possibilities are view, pub, sub */ - private String[] action; - /** unique handle for this client, generated by DMaaP Bus Controller */ - private String mrClientId; - /** TODO */ - private String topicURL; - - public MR_Client() { - } - - public MR_Client(String lastMod, Dmaap_Status status, String dcaeLocationName, String fqtn, String clientRole, - String[] action, String mrClientId, String topicURL) { - super(lastMod, status); - this.dcaeLocationName = dcaeLocationName; - this.fqtn = fqtn; - this.clientRole = clientRole; - this.action = action; - this.mrClientId = mrClientId; - this.topicURL = topicURL; - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getFqtn() { - return fqtn; - } - - public void setFqtn(String fqtn) { - this.fqtn = fqtn; - } - - public String getClientRole() { - return clientRole; - } - - public void setClientRole(String clientRole) { - this.clientRole = clientRole; - } - - public String[] getAction() { - return action; - } - - public void setAction(String[] action) { - this.action = action; - } - - public String getMrClientId() { - return mrClientId; - } - - public void setMrClientId(String mrClientId) { - this.mrClientId = mrClientId; - } - - public String getTopicURL() { - return topicURL; - } - - public void setTopicURL(String topicURL) { - this.topicURL = topicURL; - } - - @Override - public String toString() { - return "MR_Client[dcaeLocationName=" + dcaeLocationName + ", fqtn=" + fqtn + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Cluster.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Cluster.java deleted file mode 100644 index 6b213b6..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/MR_Cluster.java +++ /dev/null @@ -1,108 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -import java.util.List; - -/** - * Bean that models a DMaaP Message Router cluster. - */ -public class MR_Cluster extends DmaapObject { - - /** dcaeLocation where cluster VMs are deployed */ - private String dcaeLocationName; - /** DNS name used by MR clients for this cluster */ - private String fqdn; - /** an array of hosts that are part of the MR Cluster. */ - private List hosts; - /** TODO */ - private String topicPort; - /** TODO */ - private String topicProtocol; - - public MR_Cluster() { - } - - /** - * @param status - * Status - * @param lastMod - * Last modification - * @param dcaeLocationName - * dcaeLocation where cluster VMs are deployed - * @param fqdn - * DNS name used by MR clients for this cluster - * @param hosts - * an array of hosts that are part of the MR Cluster - */ - public MR_Cluster(Dmaap_Status status, String lastMod, String dcaeLocationName, String fqdn, final String[] hosts) { - super(lastMod, status); - this.dcaeLocationName = dcaeLocationName; - this.fqdn = fqdn; - for (String h : hosts) - this.hosts.add(h); - } - - public String getDcaeLocationName() { - return dcaeLocationName; - } - - public void setDcaeLocationName(String dcaeLocationName) { - this.dcaeLocationName = dcaeLocationName; - } - - public String getFqdn() { - return fqdn; - } - - public void setFqdn(String fqdn) { - this.fqdn = fqdn; - } - - public List getHosts() { - return hosts; - } - - public void setHosts(List hosts) { - this.hosts = hosts; - } - - public String getTopicPort() { - return topicPort; - } - - public void setTopicPort(String topicPort) { - this.topicPort = topicPort; - } - - public String getTopicProtocol() { - return topicProtocol; - } - - public void setTopicProtocol(String topicProtocol) { - this.topicProtocol = topicProtocol; - } - - @Override - public String toString() { - return "MR_Cluster[dcaeLocationName=" + dcaeLocationName + ", fqdn=" + fqdn + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Topic.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Topic.java deleted file mode 100644 index 229ae3f..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/dcae/dmaapbc/model/Topic.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ================================================================================ - * DCAE DMaaP Bus Controller Models - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.dcae.dmaapbc.model; - -import java.util.ArrayList; -import java.util.List; - -/** - * Bean that models a DMaaP Message Router topic. - */ -public class Topic extends DmaapObject { - - /** fully qualified topic name (topic_ns_root.environment.topic_name) */ - private String fqtn; - /** application supplied value for topicName */ - private String topicName; - /** description of topic */ - private String topicDescription; - /** what identity owns this topic */ - private String owner; - /** flag to MR indicating whether transactions are enabled for this topic */ - private String tnxEnabled; - /** id of format description of feed content */ - private String formatUuid; - /** indicates what replication pattern, if any, is desired */ - private String replicationCase; - /** name of a specific Global MR host */ - private String globalMrURL; - /** a set of publishers and subscribers for this topic */ - private List clients; - - public Topic() { - this.clients = new ArrayList(); - } - - public Topic(String lastMod, Dmaap_Status status, String fqtn, String topicName, String topicDescription, - String owner, String tnxEnabled, String formatUuid, String replicationCase, String globalMrURL) { - super(lastMod, status); - this.fqtn = fqtn; - this.topicName = topicName; - this.topicDescription = topicDescription; - this.owner = owner; - this.tnxEnabled = tnxEnabled; - this.formatUuid = formatUuid; - this.replicationCase = replicationCase; - this.globalMrURL = globalMrURL; - this.clients = new ArrayList(); - } - - public String getFqtn() { - return fqtn; - } - - public void setFqtn(String fqtn) { - this.fqtn = fqtn; - } - - public String getTopicName() { - return topicName; - } - - public void setTopicName(String topicName) { - this.topicName = topicName; - } - - public String getTopicDescription() { - return topicDescription; - } - - public void setTopicDescription(String topicDescription) { - this.topicDescription = topicDescription; - } - - public String getTnxEnabled() { - return tnxEnabled; - } - - public void setTnxEnabled(String tnxEnabled) { - this.tnxEnabled = tnxEnabled; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getFormatUuid() { - return formatUuid; - } - - public void setFormatUuid(String formatUuid) { - this.formatUuid = formatUuid; - } - - public List getClients() { - return clients; - } - - public void setClients(List clients) { - this.clients = clients; - } - - public String getReplicationCase() { - return replicationCase; - } - - public void setReplicationCase(String replicationCase) { - this.replicationCase = replicationCase; - } - - public String getGlobalMrURL() { - return globalMrURL; - } - - public void setGlobalMrURL(String globalMrURL) { - this.globalMrURL = globalMrURL; - } - - @Override - public String toString() { - return "Topic[fqtn=" + fqtn + ", topicName=" + topicName + ", ...]"; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/model/Result.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/model/Result.java deleted file mode 100644 index d23ed72..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/model/Result.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.openecomp.fusionapp.model; - -public class Result { - private String result; - - public Result(String result) { - this.result = result; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/service/AdminAuthExtension.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/service/AdminAuthExtension.java deleted file mode 100644 index 5d71602..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/service/AdminAuthExtension.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openecomp.fusionapp.service; - -import org.openecomp.portalsdk.core.domain.User; - -//@Service("adminAuthExtension") -//@Transactional -public class AdminAuthExtension { - - public void saveUserExtension(User user){ - //app's developer implement their own logic here, like updating app's related tables - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/util/CustomLoggingFilter.java b/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/util/CustomLoggingFilter.java deleted file mode 100644 index 4562584..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/main/java/org/openecomp/fusionapp/util/CustomLoggingFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.fusionapp.util; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.filter.Filter; -import ch.qos.logback.core.spi.FilterReply; - -/** - * Custom Filter class bind with logback.xml configuration file to strip out - * certain log messages coming out of special packages or classes. - * - */ -public class CustomLoggingFilter extends Filter { - - /** - * Custom Filter is added to strip out the continuous U-EB logging messages - * But make sure we log the ERROR and WARNING Level messages. - * - * @param event - * Logging event - */ - @Override - public FilterReply decide(ILoggingEvent event) { - try { - if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) - && (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) - && (event.getLoggerName().contains("com.att.nsa") - || event.getLoggerName().contains("org.apache.http"))) { - return FilterReply.DENY; - } else { - return FilterReply.NEUTRAL; - } - } catch (Exception e) { - return FilterReply.NEUTRAL; - } - } -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/dcae/dmaapbc/model/DcaeLocationTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/dcae/dmaapbc/model/DcaeLocationTest.java new file mode 100644 index 0000000..ebd0244 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/dcae/dmaapbc/model/DcaeLocationTest.java @@ -0,0 +1,46 @@ +package org.onap.dcae.dmaapbc.model; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.dcae.dmaapbc.model.DmaapObject.Dmaap_Status; + +/** + * Trivial POJO test. + */ +public class DcaeLocationTest { + + // superclass + final String lastMod = "lastMod"; + final Dmaap_Status status = Dmaap_Status.NEW; + // class + final String clli = "clli"; + final String dcaeLayer = "dcaeLayer"; + final String dcaeLocationName = "dcaeLocationName"; + final String openStackAvailabilityZone = "openStackAvailabilityZone"; + + @Test + public void testModel() throws Exception { + DcaeLocation model = new DcaeLocation(); + model.setLastMod(lastMod); + model.setStatus(status); + model.setClli(clli); + model.setDcaeLayer(dcaeLayer); + model.setDcaeLocationName(dcaeLocationName); + model.setOpenStackAvailabilityZone(openStackAvailabilityZone); + checkValues(model); + + model = new DcaeLocation( lastMod, status, clli, dcaeLayer, dcaeLocationName, + openStackAvailabilityZone); + checkValues(model); + } + + private void checkValues(DcaeLocation model) { + Assert.assertEquals(lastMod, model.getLastMod()); + Assert.assertEquals(status, model.getStatus()); + Assert.assertEquals(clli, model.getClli()); + Assert.assertEquals(dcaeLayer, model.getDcaeLayer()); + Assert.assertEquals(dcaeLocationName, model.getDcaeLocationName()); + Assert.assertEquals(openStackAvailabilityZone, model.getOpenStackAvailabilityZone()); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java new file mode 100644 index 0000000..a7271f5 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusion/core/MockApplicationContextTestSuite.java @@ -0,0 +1,116 @@ +package org.onap.fusion.core; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Profile; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.AnnotationConfigWebContextLoader; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; + +/** + * In order to write a unit test, 1. inherit this class - See SanityTest.java 2. + * place the "war" folder on your test class's classpath 3. run the test with + * the following VM argument; This is important because when starting the + * application from Container, the System Properties file + * (SystemProperties.java) can have the direct path but, when running from the + * Mock Junit container, the path should be prefixed with "classpath" to enable + * the mock container to search for the file in the classpath + * -Dcontainer.classpath="classpath:" + * + */ + +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class }) +@ActiveProfiles(value = "test") +public class MockApplicationContextTestSuite { + + @Autowired + public WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + if (mockMvc == null) { + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + + } + } + + public Object getBean(String name) { + return this.wac.getBean(name); + } + + public MockMvc getMockMvc() { + return mockMvc; + } + + public void setMockMvc(MockMvc mockMvc) { + this.mockMvc = mockMvc; + } + + public WebApplicationContext getWebApplicationContext() { + return wac; + } + +} + +@Configuration +@ComponentScan(basePackages = "org.onap", excludeFilters = { + // see AppConfig class +}) +@Profile("test") +class MockAppConfig extends AppConfig { + + @Bean + public SystemProperties systemProperties() { + return new MockSystemProperties(); + } + + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager() { + + public void configure() throws IOException { + + } + }; + } + + protected String[] tileDefinitions() { + return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml", + "classpath:/WEB-INF/defs/definitions.xml" }; + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // registry.addInterceptor(new + // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); + // registry.addInterceptor(resourceInterceptor()); + } + + public static class MockSystemProperties extends SystemProperties { + + public MockSystemProperties() { + } + + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/SanityTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/SanityTest.java new file mode 100644 index 0000000..b5205a9 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/SanityTest.java @@ -0,0 +1,20 @@ +package org.onap.fusionapp; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.fusion.core.MockApplicationContextTestSuite; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +public class SanityTest extends MockApplicationContextTestSuite { + + @Test + public void testGetAvailableRoles() throws Exception { + + ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/api/roles")); + //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass()); + Assert.assertEquals("application/json",ra.andReturn().getResponse().getContentType()); + } + + +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java new file mode 100644 index 0000000..406a2e2 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/onap/fusionapp/service/ProfileServiceTest.java @@ -0,0 +1,37 @@ +package org.onap.fusionapp.service; + +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.fusion.core.MockApplicationContextTestSuite; +import org.openecomp.portalsdk.core.domain.Profile; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.service.ProfileService; +import org.openecomp.portalsdk.core.service.UserProfileService; +import org.springframework.beans.factory.annotation.Autowired; + + +public class ProfileServiceTest extends MockApplicationContextTestSuite { + + @Autowired + ProfileService service; + + @Autowired + UserProfileService userProfileService; + + @Test + public void testFindAll() { + + List profiles = service.findAll(); + Assert.assertTrue(profiles.size() > 0); + } + + @Test + public void testFindAllActive() { + + List users = userProfileService.findAllActive(); + List activeUsers = userProfileService.findAllActive(); + Assert.assertTrue(users.size() - activeUsers.size() >= 0); + } +} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/dcae/dmaapbc/model/DcaeLocationTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/dcae/dmaapbc/model/DcaeLocationTest.java deleted file mode 100644 index 9cc3350..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/dcae/dmaapbc/model/DcaeLocationTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.openecomp.dcae.dmaapbc.model; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.dcae.dmaapbc.model.DmaapObject.Dmaap_Status; - -/** - * Trivial POJO test. - */ -public class DcaeLocationTest { - - // superclass - final String lastMod = "lastMod"; - final Dmaap_Status status = Dmaap_Status.NEW; - // class - final String clli = "clli"; - final String dcaeLayer = "dcaeLayer"; - final String dcaeLocationName = "dcaeLocationName"; - final String openStackAvailabilityZone = "openStackAvailabilityZone"; - - @Test - public void testModel() throws Exception { - DcaeLocation model = new DcaeLocation(); - model.setLastMod(lastMod); - model.setStatus(status); - model.setClli(clli); - model.setDcaeLayer(dcaeLayer); - model.setDcaeLocationName(dcaeLocationName); - model.setOpenStackAvailabilityZone(openStackAvailabilityZone); - checkValues(model); - - model = new DcaeLocation( lastMod, status, clli, dcaeLayer, dcaeLocationName, - openStackAvailabilityZone); - checkValues(model); - } - - private void checkValues(DcaeLocation model) { - Assert.assertEquals(lastMod, model.getLastMod()); - Assert.assertEquals(status, model.getStatus()); - Assert.assertEquals(clli, model.getClli()); - Assert.assertEquals(dcaeLayer, model.getDcaeLayer()); - Assert.assertEquals(dcaeLocationName, model.getDcaeLocationName()); - Assert.assertEquals(openStackAvailabilityZone, model.getOpenStackAvailabilityZone()); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java deleted file mode 100644 index e828c88..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusion/core/MockApplicationContextTestSuite.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.openecomp.fusion.core; - -import java.io.IOException; - -import org.junit.Before; -import org.junit.runner.RunWith; -import org.openecomp.portalsdk.core.conf.AppConfig; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.util.CacheManager; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.AnnotationConfigWebContextLoader; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; - -/** - * In order to write a unit test, 1. inherit this class - See SanityTest.java 2. - * place the "war" folder on your test class's classpath 3. run the test with - * the following VM argument; This is important because when starting the - * application from Container, the System Properties file - * (SystemProperties.java) can have the direct path but, when running from the - * Mock Junit container, the path should be prefixed with "classpath" to enable - * the mock container to search for the file in the classpath - * -Dcontainer.classpath="classpath:" - * - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration -@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { MockAppConfig.class }) -@ActiveProfiles(value = "test") -public class MockApplicationContextTestSuite { - - @Autowired - public WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() { - if (mockMvc == null) { - this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); - - } - } - - public Object getBean(String name) { - return this.wac.getBean(name); - } - - public MockMvc getMockMvc() { - return mockMvc; - } - - public void setMockMvc(MockMvc mockMvc) { - this.mockMvc = mockMvc; - } - - public WebApplicationContext getWebApplicationContext() { - return wac; - } - -} - -@Configuration -@ComponentScan(basePackages = "org.openecomp", excludeFilters = { - // see AppConfig class -}) -@Profile("test") -class MockAppConfig extends AppConfig { - - @Bean - public SystemProperties systemProperties() { - return new MockSystemProperties(); - } - - @Bean - public AbstractCacheManager cacheManager() { - return new CacheManager() { - - public void configure() throws IOException { - - } - }; - } - - protected String[] tileDefinitions() { - return new String[] { "classpath:/WEB-INF/fusion/defs/definitions.xml", - "classpath:/WEB-INF/defs/definitions.xml" }; - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - // registry.addInterceptor(new - // SessionTimeoutInterceptor()).excludePathPatterns(getExcludeUrlPathsForSessionTimeout()); - // registry.addInterceptor(resourceInterceptor()); - } - - public static class MockSystemProperties extends SystemProperties { - - public MockSystemProperties() { - } - - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/SanityTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/SanityTest.java deleted file mode 100644 index a5022f9..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/SanityTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.openecomp.fusionapp; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.fusion.core.MockApplicationContextTestSuite; -import org.springframework.test.web.servlet.ResultActions; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; - -public class SanityTest extends MockApplicationContextTestSuite { - - @Test - public void testGetAvailableRoles() throws Exception { - - ResultActions ra =getMockMvc().perform(MockMvcRequestBuilders.get("/api/roles")); - //Assert.assertEquals(UrlAccessRestrictedException.class,ra.andReturn().getResolvedException().getClass()); - Assert.assertEquals("application/json",ra.andReturn().getResponse().getContentType()); - } - - -} diff --git a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/service/ProfileServiceTest.java b/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/service/ProfileServiceTest.java deleted file mode 100644 index 1e6d78c..0000000 --- a/dcae_dmaapbc_webapp/dbca-common/src/test/java/org/openecomp/fusionapp/service/ProfileServiceTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.openecomp.fusionapp.service; - -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.fusion.core.MockApplicationContextTestSuite; -import org.openecomp.portalsdk.core.domain.Profile; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.service.ProfileService; -import org.openecomp.portalsdk.core.service.UserProfileService; -import org.springframework.beans.factory.annotation.Autowired; - - -public class ProfileServiceTest extends MockApplicationContextTestSuite { - - @Autowired - ProfileService service; - - @Autowired - UserProfileService userProfileService; - - @Test - public void testFindAll() { - - List profiles = service.findAll(); - Assert.assertTrue(profiles.size() > 0); - } - - @Test - public void testFindAllActive() { - - List users = userProfileService.findAllActive(); - List activeUsers = userProfileService.findAllActive(); - Assert.assertTrue(users.size() - activeUsers.size() >= 0); - } -} diff --git a/dcae_dmaapbc_webapp/dbca-os/db-scripts/dbca-dml-mysql-1707-os.sql b/dcae_dmaapbc_webapp/dbca-os/db-scripts/dbca-dml-mysql-1707-os.sql index 5bd6014..0081c52 100644 --- a/dcae_dmaapbc_webapp/dbca-os/db-scripts/dbca-dml-mysql-1707-os.sql +++ b/dcae_dmaapbc_webapp/dbca-os/db-scripts/dbca-dml-mysql-1707-os.sql @@ -451,7 +451,7 @@ Insert into fn_user -- fn_app -- Use name "DMAAP-BC-APP" (originally "Default") -Insert into fn_app (APP_ID,APP_NAME,APP_IMAGE_URL,APP_DESCRIPTION,APP_NOTES,APP_URL,APP_ALTERNATE_URL,APP_REST_ENDPOINT,ML_APP_NAME,ML_APP_ADMIN_ID,MOTS_ID,APP_PASSWORD,OPEN,ENABLED,THUMBNAIL,APP_USERNAME,UEB_KEY,UEB_SECRET,UEB_TOPIC_NAME) VALUES (1,'DMAAP-BC-APP','assets/images/tmp/portal1.png','Some Default Description','Some Default Note','http://www.openecomp.org','http://www.openecomp.org',null,'ECPP','?','1','okYTaDrhzibcbGVq5mjkVQ==','N','N',null,'Default',null,null,'ECOMP-PORTAL-INBOX'); +Insert into fn_app (APP_ID,APP_NAME,APP_IMAGE_URL,APP_DESCRIPTION,APP_NOTES,APP_URL,APP_ALTERNATE_URL,APP_REST_ENDPOINT,ML_APP_NAME,ML_APP_ADMIN_ID,MOTS_ID,APP_PASSWORD,OPEN,ENABLED,THUMBNAIL,APP_USERNAME,UEB_KEY,UEB_SECRET,UEB_TOPIC_NAME) VALUES (1,'DMAAP-BC-APP','assets/images/tmp/portal1.png','Some Default Description','Some Default Note','http://www.onap.org','http://www.onap.org',null,'ECPP','?','1','okYTaDrhzibcbGVq5mjkVQ==','N','N',null,'Default',null,null,'ECOMP-PORTAL-INBOX'); -- fn_user_role Insert into fn_user_role (USER_ID,ROLE_ID,PRIORITY,APP_ID) values (1,1,null,1); diff --git a/dcae_dmaapbc_webapp/dbca-os/pom.xml b/dcae_dmaapbc_webapp/dbca-os/pom.xml index adeceac..472848b 100644 --- a/dcae_dmaapbc_webapp/dbca-os/pom.xml +++ b/dcae_dmaapbc_webapp/dbca-os/pom.xml @@ -3,9 +3,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.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-os - 1.1.0 + 1.2.0-SNAPSHOT war DCAE DMaaP Bus Controller Webapp for ONAP DMaaP Bus Controller Web Application for open-source release @@ -17,12 +17,12 @@ 4.2.0.RELEASE 4.3.11.Final 1.1.0 - 1.1.0-SNAPSHOT + 1.2.0-SNAPSHOT **.js https://nexus.onap.org /content/repositories/snapshots/ /content/repositories/releases/ - /content/sites/site/org/openecomp/ui/dmaapbc/${project.version} + /content/sites/site/org/onap/ui/dmaapbc/${project.version} @@ -71,7 +71,7 @@ - org.openecomp.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-overlay META-INF/MANIFEST.MF @@ -137,14 +137,14 @@ - org.openecomp.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-common ${dbca.version} jar - org.openecomp.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-overlay ${dbca.version} war diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java new file mode 100644 index 0000000..c827e84 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java @@ -0,0 +1,171 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.portalapp.lm.FusionLicenseManagerImpl; +import org.onap.portalapp.login.LoginStrategyImpl; +import org.openecomp.portalapp.scheduler.LogRegistry; +import org.openecomp.portalsdk.core.auth.LoginStrategy; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.conf.Configurable; +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.openecomp.portalsdk.core.lm.FusionLicenseManagerUtils; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.FilterType; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Profile; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +/** + * Configures Spring features in the DMaaP Bus Control web application. + * Subclasses the ECOMP Portal SDK core AppConfig class to reuse interceptors, + * view resolvers and other features defined there. + */ +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.openecomp, org.onap", + // Exclude unused annotated classes with heavy dependencies. + excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = { + // EPSDK-Analytics + org.openecomp.portalsdk.analytics.system.fusion.adapter.FusionAdapter.class, + org.openecomp.portalsdk.analytics.system.fusion.adapter.RaptorAdapter.class, + org.openecomp.portalsdk.analytics.system.fusion.web.RaptorController.class, + org.openecomp.portalsdk.analytics.system.fusion.web.RaptorControllerAsync.class, + org.openecomp.portalsdk.analytics.system.fusion.DbUtils.class, + // EPSDK-App-Common + org.openecomp.portalapp.controller.sample.ElasticSearchController.class, + LogRegistry.class, + org.openecomp.portalapp.controller.sample.PostDroolsController.class, + // EPSDK-Core + org.openecomp.portalsdk.core.scheduler.CoreRegister.class, + org.openecomp.portalsdk.core.scheduler.CronRegistry.class, + org.openecomp.portalsdk.core.service.PostDroolsService.class + })) +@Profile("src") +@EnableAsync +@EnableScheduling +public class ExternalAppConfig extends AppConfig implements Configurable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class); + + @Configuration + @Import(SystemProperties.class) + static class InnerConfiguration { + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver() + */ + public ViewResolver viewResolver() { + return super.viewResolver(); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry) + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + super.addResourceHandlers(registry); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService() + */ + @Override + public DataAccessService dataAccessService() { + // Echo the JDBC URL to assist developers when starting the app. + systemProperties(); + System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is " + + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); + return super.dataAccessService(); + } + + /** + * Creates a new list with a single entry that is the external app + * definitions.xml path. + * + * @return List of String, size 1 + */ + @Override + public List addTileDefinitions() { + List definitions = new ArrayList(); + // DBC does not need the sample page: + // definitions.add("/WEB-INF/defs/definitions.xml"); + definitions.add("/WEB-INF/dbcapp/dbcapp-definitions.xml"); + if (logger.isDebugEnabled()) + logger.debug(EELFLoggerDelegate.debugLogger, "addTileDefinitions: list is " + definitions); + return definitions; + } + + /** + * Adds request interceptors to the specified registry by calling + * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes + * certain paths from the session timeout interceptor. + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm", + "/api*", "/single_signon.htm", "/single_signon"); + super.addInterceptors(registry); + } + + /** + * Creates and returns a new instance of a {@link CacheManager} class. + * + * @return New instance of {@link CacheManager} + */ + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager(); + } + + @Bean + public FusionLicenseManager fusionLicenseManager() { + return new FusionLicenseManagerImpl(); + } + + @Bean + public FusionLicenseManagerUtils fusionLicenseManagerUtils() { + return new FusionLicenseManagerUtils(); + } + + @Bean + public LoginStrategy loginStrategy() { + return new LoginStrategyImpl(); + } +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java new file mode 100644 index 0000000..347bb51 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import org.openecomp.portalsdk.core.conf.AppInitializer; + +public class ExternalAppInitializer extends AppInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return super.getRootConfigClasses(); + } + + @Override + protected Class[] getServletConfigClasses() { + Class appConfigClass = ExternalAppConfig.class; + // Show something on stdout to indicate the app is starting. + System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName()); + return new Class[] { appConfigClass }; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return super.getServletMappings(); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java new file mode 100644 index 0000000..cbff8a9 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java @@ -0,0 +1,60 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; + +@Component +@Profile("src") +public class HibernateMappingLocations implements HibernateMappingLocatable { + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# + * getMappingLocations() + */ + @Override + public Resource[] getMappingLocations() { + return new Resource[] { + // Path is relative to WEB-INF/conf; + // a leading slash gets stripped so don't bother. + new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), + new ClassPathResource("../dbcapp/dbcapp.hbm.xml") + }; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# + * getPackagesToScan() + */ + @Override + public String[] getPackagesToScan() { + return new String[] { "org.onap", "org.openecomp" }; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java new file mode 100644 index 0000000..49a6070 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java @@ -0,0 +1,81 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ + +package org.onap.portalapp.lm; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; + +/** + * Empty implementation to satisfy an interface. + */ +public class FusionLicenseManagerImpl implements FusionLicenseManager { + + public FusionLicenseManagerImpl() { + } + + /** + * An implementation of the KeyStoreParam interface that returns the + * information required to work with the keystore containing the private key + */ + public void initKeyStoreParam() { + } + + public void initCipherParam() { + } + + public void initLicenseParam() { + } + + public void doInitWork() { + } + + public int installLicense() { + return OPENSOURCE_LICENSE; + } + + public synchronized int verifyLicense(ServletContext context) { + return OPENSOURCE_LICENSE; + } + + public void generateLicense(Map clientInfoMap, List ipAddressList) throws Exception { + } + + public static String nvls(String s) { + return null; + } + + public String nvl(String s) { + return null; + } + + public Date getExpiredDate() { + return null; + } + + public void setExpiredDate(Date expiredDate) { + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java new file mode 100644 index 0000000..1dd7abc --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java @@ -0,0 +1,111 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ + +package org.onap.portalapp.login; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.portalsdk.core.auth.LoginStrategy; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.web.servlet.ModelAndView; + +/** + * Implements basic single-signon login strategy for open-source applications + * when users start at Portal. Extracts an encrypted user ID sent by Portal. + */ +public class LoginStrategyImpl extends LoginStrategy { + + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginStrategyImpl.class); + + /** + * login for open source is same as external login in the non-open-source + * version. + */ + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + return doExternalLogin(request, response); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + // Check ECOMP Portal cookie + Cookie ep = getCookie(request, EP_SERVICE); + if (ep == null) { + logger.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null"); + return null; + } + + String userid = null; + try { + userid = getUserIdFromCookie(request); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e); + } + return userid; + } + + /** + * Searches the request for the user-ID cookie and decrypts the value using a + * key configured in properties + * + * @param request + * HttpServletRequest + * @return User ID + * @throws Exception + * On any failure + */ + private String getUserIdFromCookie(HttpServletRequest request) throws Exception { + String userId = ""; + Cookie userIdCookie = getCookie(request, USER_ID); + if (userIdCookie != null) { + final String cookieValue = userIdCookie.getValue(); + if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key)) + throw new Exception("Failed to find property " + SystemProperties.Decryption_Key); + final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key); + userId = CipherUtil.decrypt(cookieValue, decryptionKey); + logger.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId); + } + return userId; + } + + /** + * Searches the request for the named cookie. + * + * @param request + * HttpServletRequest + * @param cookieName + * Name of desired cookie + * @return Cookie if found; otherwise null. + */ + private Cookie getCookie(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(cookieName)) + return cookie; + return null; + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/service/AdminAuthExtension.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/service/AdminAuthExtension.java new file mode 100644 index 0000000..cbc6af2 --- /dev/null +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/onap/service/AdminAuthExtension.java @@ -0,0 +1,65 @@ +/*- + * ================================================================================ + * ECOMP Portal SDK + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.service; + +import java.util.Set; + +import org.openecomp.portalapp.service.IAdminAuthExtension; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + + +@Service("adminAuthExtension") +@Transactional +/** + * Provides empty implementations of the methods in IAdminAuthExtension. + */ +public class AdminAuthExtension implements IAdminAuthExtension { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class); + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserExtension(org.openecomp.portalsdk.core.domain.User) + */ + public void saveUserExtension(User user) { + logger.debug("saveUserExtension"); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.service.IAdminAuthExtension#editUserExtension(org.openecomp.portalsdk.core.domain.User) + */ + public void editUserExtension(User user) { + logger.debug("editUserExtension"); + } + + /* + * (non-Javadoc) + * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserRoleExtension(java.util.Set, org.openecomp.portalsdk.core.domain.User) + */ + public void saveUserRoleExtension(Set roles, User user) { + logger.debug("saveUserRoleExtension"); + } + +} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java deleted file mode 100644 index ddb4bc2..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.portalapp.lm.FusionLicenseManagerImpl; -import org.openecomp.portalapp.login.LoginStrategyImpl; -import org.openecomp.portalapp.scheduler.LogRegistry; -import org.openecomp.portalsdk.core.auth.LoginStrategy; -import org.openecomp.portalsdk.core.conf.AppConfig; -import org.openecomp.portalsdk.core.conf.Configurable; -import org.openecomp.portalsdk.core.lm.FusionLicenseManager; -import org.openecomp.portalsdk.core.lm.FusionLicenseManagerUtils; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.CacheManager; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; - -/** - * Configures Spring features in the DMaaP Bus Control web application. - * Subclasses the ECOMP Portal SDK core AppConfig class to reuse interceptors, - * view resolvers and other features defined there. - */ -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "org.openecomp", - // Exclude unused annotated classes with heavy dependencies. - excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = { - // EPSDK-Analytics - org.openecomp.portalsdk.analytics.system.fusion.adapter.FusionAdapter.class, - org.openecomp.portalsdk.analytics.system.fusion.adapter.RaptorAdapter.class, - org.openecomp.portalsdk.analytics.system.fusion.web.RaptorController.class, - org.openecomp.portalsdk.analytics.system.fusion.web.RaptorControllerAsync.class, - org.openecomp.portalsdk.analytics.system.fusion.DbUtils.class, - // EPSDK-App-Common - org.openecomp.portalapp.controller.sample.ElasticSearchController.class, - LogRegistry.class, - org.openecomp.portalapp.controller.sample.PostDroolsController.class, - // EPSDK-Core - org.openecomp.portalsdk.core.scheduler.CoreRegister.class, - org.openecomp.portalsdk.core.scheduler.CronRegistry.class, - org.openecomp.portalsdk.core.service.PostDroolsService.class - })) -@Profile("src") -@EnableAsync -@EnableScheduling -public class ExternalAppConfig extends AppConfig implements Configurable { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class); - - @Configuration - @Import(SystemProperties.class) - static class InnerConfiguration { - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver() - */ - public ViewResolver viewResolver() { - return super.viewResolver(); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry) - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - super.addResourceHandlers(registry); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService() - */ - @Override - public DataAccessService dataAccessService() { - // Echo the JDBC URL to assist developers when starting the app. - systemProperties(); - System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is " - + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); - return super.dataAccessService(); - } - - /** - * Creates a new list with a single entry that is the external app - * definitions.xml path. - * - * @return List of String, size 1 - */ - @Override - public List addTileDefinitions() { - List definitions = new ArrayList(); - // DBC does not need the sample page: - // definitions.add("/WEB-INF/defs/definitions.xml"); - definitions.add("/WEB-INF/dbcapp/dbcapp-definitions.xml"); - if (logger.isDebugEnabled()) - logger.debug(EELFLoggerDelegate.debugLogger, "addTileDefinitions: list is " + definitions); - return definitions; - } - - /** - * Adds request interceptors to the specified registry by calling - * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes - * certain paths from the session timeout interceptor. - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { - super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm", - "/api*", "/single_signon.htm", "/single_signon"); - super.addInterceptors(registry); - } - - /** - * Creates and returns a new instance of a {@link CacheManager} class. - * - * @return New instance of {@link CacheManager} - */ - @Bean - public AbstractCacheManager cacheManager() { - return new CacheManager(); - } - - @Bean - public FusionLicenseManager fusionLicenseManager() { - return new FusionLicenseManagerImpl(); - } - - @Bean - public FusionLicenseManagerUtils fusionLicenseManagerUtils() { - return new FusionLicenseManagerUtils(); - } - - @Bean - public LoginStrategy loginStrategy() { - return new LoginStrategyImpl(); - } -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java deleted file mode 100644 index 6d7c72d..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import org.openecomp.portalsdk.core.conf.AppInitializer; - -public class ExternalAppInitializer extends AppInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return super.getRootConfigClasses(); - } - - @Override - protected Class[] getServletConfigClasses() { - Class appConfigClass = ExternalAppConfig.class; - // Show something on stdout to indicate the app is starting. - System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName()); - return new Class[] { appConfigClass }; - } - - /* - * URL request will direct to the Spring dispatcher for processing - */ - @Override - protected String[] getServletMappings() { - return super.getServletMappings(); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java deleted file mode 100644 index ce77960..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import org.springframework.context.annotation.Profile; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.stereotype.Component; - -import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; - -@Component -@Profile("src") -public class HibernateMappingLocations implements HibernateMappingLocatable { - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# - * getMappingLocations() - */ - @Override - public Resource[] getMappingLocations() { - return new Resource[] { - // Path is relative to WEB-INF/conf; - // a leading slash gets stripped so don't bother. - new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), - new ClassPathResource("../dbcapp/dbcapp.hbm.xml") - }; - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# - * getPackagesToScan() - */ - @Override - public String[] getPackagesToScan() { - return new String[] { "org.openecomp" }; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java deleted file mode 100644 index abbf926..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ - -package org.openecomp.portalapp.lm; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.openecomp.portalsdk.core.lm.FusionLicenseManager; - -/** - * Empty implementation to satisfy an interface. - */ -public class FusionLicenseManagerImpl implements FusionLicenseManager { - - public FusionLicenseManagerImpl() { - } - - /** - * An implementation of the KeyStoreParam interface that returns the - * information required to work with the keystore containing the private key - */ - public void initKeyStoreParam() { - } - - public void initCipherParam() { - } - - public void initLicenseParam() { - } - - public void doInitWork() { - } - - public int installLicense() { - return OPENSOURCE_LICENSE; - } - - public synchronized int verifyLicense(ServletContext context) { - return OPENSOURCE_LICENSE; - } - - public void generateLicense(Map clientInfoMap, List ipAddressList) throws Exception { - } - - public static String nvls(String s) { - return null; - } - - public String nvl(String s) { - return null; - } - - public Date getExpiredDate() { - return null; - } - - public void setExpiredDate(Date expiredDate) { - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java deleted file mode 100644 index 270e69f..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ - -package org.openecomp.portalapp.login; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.portalsdk.core.auth.LoginStrategy; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; -import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.web.servlet.ModelAndView; - -/** - * Implements basic single-signon login strategy for open-source applications - * when users start at Portal. Extracts an encrypted user ID sent by Portal. - */ -public class LoginStrategyImpl extends LoginStrategy { - - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LoginStrategyImpl.class); - - /** - * login for open source is same as external login in the non-open-source - * version. - */ - @Override - public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { - return doExternalLogin(request, response); - } - - @Override - public String getUserId(HttpServletRequest request) throws PortalAPIException { - // Check ECOMP Portal cookie - Cookie ep = getCookie(request, EP_SERVICE); - if (ep == null) { - logger.debug(EELFLoggerDelegate.debugLogger, "getUserId: no EP_SERVICE cookie, returning null"); - return null; - } - - String userid = null; - try { - userid = getUserIdFromCookie(request); - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, "getUserId failed", e); - } - return userid; - } - - /** - * Searches the request for the user-ID cookie and decrypts the value using a - * key configured in properties - * - * @param request - * HttpServletRequest - * @return User ID - * @throws Exception - * On any failure - */ - private String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie userIdCookie = getCookie(request, USER_ID); - if (userIdCookie != null) { - final String cookieValue = userIdCookie.getValue(); - if (!SystemProperties.containsProperty(SystemProperties.Decryption_Key)) - throw new Exception("Failed to find property " + SystemProperties.Decryption_Key); - final String decryptionKey = SystemProperties.getProperty(SystemProperties.Decryption_Key); - userId = CipherUtil.decrypt(cookieValue, decryptionKey); - logger.debug(EELFLoggerDelegate.debugLogger, "getUserIdFromCookie: decrypted as {}", userId); - } - return userId; - } - - /** - * Searches the request for the named cookie. - * - * @param request - * HttpServletRequest - * @param cookieName - * Name of desired cookie - * @return Cookie if found; otherwise null. - */ - private Cookie getCookie(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(cookieName)) - return cookie; - return null; - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java b/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java deleted file mode 100644 index 2b9b60e..0000000 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.service; - -import java.util.Set; - -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - - -@Service("adminAuthExtension") -@Transactional -/** - * Provides empty implementations of the methods in IAdminAuthExtension. - */ -public class AdminAuthExtension implements IAdminAuthExtension { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class); - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserExtension(org.openecomp.portalsdk.core.domain.User) - */ - public void saveUserExtension(User user) { - logger.debug("saveUserExtension"); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#editUserExtension(org.openecomp.portalsdk.core.domain.User) - */ - public void editUserExtension(User user) { - logger.debug("editUserExtension"); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserRoleExtension(java.util.Set, org.openecomp.portalsdk.core.domain.User) - */ - public void saveUserRoleExtension(Set roles, User user) { - logger.debug("saveUserRoleExtension"); - } - -} diff --git a/dcae_dmaapbc_webapp/dbca-os/src/main/resources/logback.xml b/dcae_dmaapbc_webapp/dbca-os/src/main/resources/logback.xml index 869b349..4766277 100644 --- a/dcae_dmaapbc_webapp/dbca-os/src/main/resources/logback.xml +++ b/dcae_dmaapbc_webapp/dbca-os/src/main/resources/logback.xml @@ -80,7 +80,7 @@ ${applicationLoggerPattern} - + diff --git a/dcae_dmaapbc_webapp/dbca-overlay/pom.xml b/dcae_dmaapbc_webapp/dbca-overlay/pom.xml index 2675727..6e70f31 100644 --- a/dcae_dmaapbc_webapp/dbca-overlay/pom.xml +++ b/dcae_dmaapbc_webapp/dbca-overlay/pom.xml @@ -3,9 +3,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.ui.dmaapbc + org.onap.ui.dmaapbc dmaap-bc-app-overlay - 1.1.0-SNAPSHOT + 1.2.0-SNAPSHOT war DCAE DMaaP Bus Controller Webapp Common Web Files Web resource overlay for the DCAE DMaaP Bus Controller GUI diff --git a/dcae_dmaapbc_webapp/dbca-overlay/src/main/webapp/WEB-INF/dbcapp/dbcapp.hbm.xml b/dcae_dmaapbc_webapp/dbca-overlay/src/main/webapp/WEB-INF/dbcapp/dbcapp.hbm.xml index 87bf9c2..93d1dd4 100644 --- a/dcae_dmaapbc_webapp/dbca-overlay/src/main/webapp/WEB-INF/dbcapp/dbcapp.hbm.xml +++ b/dcae_dmaapbc_webapp/dbca-overlay/src/main/webapp/WEB-INF/dbcapp/dbcapp.hbm.xml @@ -3,7 +3,7 @@ "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> - + diff --git a/dcae_dmaapbc_webapp/pom.xml b/dcae_dmaapbc_webapp/pom.xml index bc50aa0..79ca5bb 100644 --- a/dcae_dmaapbc_webapp/pom.xml +++ b/dcae_dmaapbc_webapp/pom.xml @@ -3,9 +3,9 @@ 4.0.0 - org.openecomp.dcae.dmaapbc + org.onap.dcae.dmaapbc dmaap-bc-app-parent - 0 + 1 pom DCAE DMaaP Bus Controller Webapp projects (parent) diff --git a/pom.xml b/pom.xml index b4a04ec..086a6d5 100644 --- a/pom.xml +++ b/pom.xml @@ -2,9 +2,9 @@ 4.0.0 - org.openecomp.dcae.dmaapbc + org.onap.dcae.dmaapbc dcae_dmaapbc_webapp - 0 + 1 pom ui-dmaapbc -- cgit 1.2.3-korg