From 0bff051a842b164b680bc938f4a56db435dd5841 Mon Sep 17 00:00:00 2001 From: dglFromAtt Date: Tue, 10 Apr 2018 19:01:35 -0400 Subject: Refactor code to support no AAF requests Change-Id: Ib95ba2458eb9fab90013012718f708c15cbf9db3 Signed-off-by: dglFromAtt Issue-ID: DMAAP-320 --- .classpath | 31 + .../java/org/onap/dmaap/dbcapi/aaf/AafService.java | 42 +- .../aaf/authentication/ApiPermissionInterface.java | 28 - .../dmaap/dbcapi/aaf/authentication/ApiPerms.java | 167 ----- .../dmaap/dbcapi/aaf/authentication/ApiPolicy.java | 58 -- .../AuthenticationErrorException.java | 29 - .../dmaap/dbcapi/aaf/client/DrProvConnection.java | 813 --------------------- .../dmaap/dbcapi/aaf/client/MrProvConnection.java | 223 ------ .../dmaap/dbcapi/aaf/client/MrTopicConnection.java | 186 ----- .../dmaap/dbcapi/aaf/database/ConnWrapper.java | 63 -- .../dbcapi/aaf/database/ConnectionFactory.java | 89 --- .../dmaap/dbcapi/aaf/database/DBException.java | 34 - .../dmaap/dbcapi/aaf/database/DBFieldHandler.java | 202 ----- .../org/onap/dmaap/dbcapi/aaf/database/DBMap.java | 138 ---- .../dmaap/dbcapi/aaf/database/DBSingleton.java | 98 --- .../dmaap/dbcapi/aaf/database/DatabaseClass.java | 270 ------- .../onap/dmaap/dbcapi/aaf/database/LoadSchema.java | 117 --- .../dmaap/dbcapi/aaf/database/TableHandler.java | 115 --- .../authentication/ApiPermissionInterface.java | 28 + .../onap/dmaap/dbcapi/authentication/ApiPerms.java | 167 +++++ .../dmaap/dbcapi/authentication/ApiPolicy.java | 58 ++ .../AuthenticationErrorException.java | 29 + .../onap/dmaap/dbcapi/client/DrProvConnection.java | 813 +++++++++++++++++++++ .../onap/dmaap/dbcapi/client/MrProvConnection.java | 223 ++++++ .../dmaap/dbcapi/client/MrTopicConnection.java | 186 +++++ .../onap/dmaap/dbcapi/database/ConnWrapper.java | 63 ++ .../dmaap/dbcapi/database/ConnectionFactory.java | 89 +++ .../onap/dmaap/dbcapi/database/DBException.java | 34 + .../onap/dmaap/dbcapi/database/DBFieldHandler.java | 202 +++++ .../java/org/onap/dmaap/dbcapi/database/DBMap.java | 138 ++++ .../onap/dmaap/dbcapi/database/DBSingleton.java | 98 +++ .../onap/dmaap/dbcapi/database/DatabaseClass.java | 270 +++++++ .../org/onap/dmaap/dbcapi/database/LoadSchema.java | 117 +++ .../onap/dmaap/dbcapi/database/TableHandler.java | 115 +++ .../org/onap/dmaap/dbcapi/model/MR_Client.java | 5 +- .../dbcapi/resources/AuthorizationFilter.java | 2 +- .../dmaap/dbcapi/resources/BridgeResource.java | 2 +- .../onap/dmaap/dbcapi/resources/FeedResource.java | 21 +- .../org/onap/dmaap/dbcapi/server/JettyServer.java | 2 +- .../java/org/onap/dmaap/dbcapi/server/Main.java | 4 +- .../org/onap/dmaap/dbcapi/service/ApiService.java | 4 +- .../onap/dmaap/dbcapi/service/DR_NodeService.java | 4 +- .../onap/dmaap/dbcapi/service/DR_PubService.java | 4 +- .../onap/dmaap/dbcapi/service/DR_SubService.java | 4 +- .../dmaap/dbcapi/service/DcaeLocationService.java | 12 +- .../onap/dmaap/dbcapi/service/DmaapService.java | 4 +- .../org/onap/dmaap/dbcapi/service/FeedService.java | 4 +- .../dmaap/dbcapi/service/MR_ClientService.java | 4 +- .../dmaap/dbcapi/service/MR_ClusterService.java | 8 +- .../dmaap/dbcapi/service/MirrorMakerService.java | 4 +- .../onap/dmaap/dbcapi/service/TopicService.java | 2 +- .../java/org/onap/dmaap/dbcapi/util/Graph.java | 2 +- .../dbcapi/aaf/client/DrProvConnectionTest.java | 131 ---- .../dbcapi/aaf/client/MrProvConnectionTest.java | 102 --- .../dbcapi/aaf/client/MrTopicConnectionTest.java | 101 --- .../dbcapi/aaf/database/DBFieldHandlerTest.java | 106 --- .../onap/dmaap/dbcapi/aaf/database/DBMapTest.java | 87 --- .../dmaap/dbcapi/aaf/database/DBSingletonTest.java | 72 -- .../dmaap/dbcapi/aaf/database/LoadSchemaTest.java | 74 -- .../dbcapi/aaf/database/TableHandlerTest.java | 103 --- .../dmaap/dbcapi/client/DrProvConnectionTest.java | 132 ++++ .../dmaap/dbcapi/client/MrProvConnectionTest.java | 103 +++ .../dmaap/dbcapi/client/MrTopicConnectionTest.java | 102 +++ .../dmaap/dbcapi/database/DBFieldHandlerTest.java | 107 +++ .../org/onap/dmaap/dbcapi/database/DBMapTest.java | 89 +++ .../dmaap/dbcapi/database/DBSingletonTest.java | 72 ++ .../onap/dmaap/dbcapi/database/LoadSchemaTest.java | 75 ++ .../dmaap/dbcapi/database/TableHandlerTest.java | 106 +++ .../onap/dmaap/dbcapi/service/ApiServiceTest.java | 2 +- .../onap/dmaap/dbcapi/service/FeedServiceTest.java | 2 +- 70 files changed, 3502 insertions(+), 3489 deletions(-) create mode 100644 .classpath delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPermissionInterface.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPerms.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPolicy.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/AuthenticationErrorException.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnection.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnection.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnection.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnWrapper.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnectionFactory.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBException.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandler.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBMap.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBSingleton.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/DatabaseClass.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchema.java delete mode 100644 src/main/java/org/onap/dmaap/dbcapi/aaf/database/TableHandler.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPermissionInterface.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPerms.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPolicy.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/authentication/AuthenticationErrorException.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/client/DrProvConnection.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/client/MrProvConnection.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/client/MrTopicConnection.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/ConnWrapper.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/ConnectionFactory.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/DBException.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/DBFieldHandler.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/DBMap.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/DBSingleton.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/LoadSchema.java create mode 100644 src/main/java/org/onap/dmaap/dbcapi/database/TableHandler.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnectionTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnectionTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnectionTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandlerTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBMapTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBSingletonTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchemaTest.java delete mode 100644 src/test/java/org/onap/dmaap/dbcapi/aaf/database/TableHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java create mode 100644 src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..17efa84 --- /dev/null +++ b/.classpath @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/AafService.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/AafService.java index 727ec19..01506bf 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/AafService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/aaf/AafService.java @@ -36,6 +36,13 @@ public class AafService extends BaseLoggingClass { private AafConnection aaf; private ServiceType ctype; private String aafURL ; + private boolean useAAF = false; + + public AafService() { + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + useAAF= "true".equalsIgnoreCase(p.getProperty("UseAAF", "false")); + + } private String getCred( boolean wPwd ) { String mechIdProperty = null; @@ -54,21 +61,10 @@ public class AafService extends BaseLoggingClass { return null; } String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" ); - //String dClass = p.getProperty( "AafDecryption.Class", "org.openecomp.dmaapbc.aaf.ClearDecrypt"); + String pwd = ""; String encPwd = p.getProperty( pwdProperty, "notSet" ); - //DecryptionInterface dec = null; - //try { - // dec = (DecryptionInterface) (Class.forName(dClass).newInstance()); - // dec.init( p.getProperty("CredentialCodecKeyfile", "LocalKey")); - //} catch (Exception ee ) { - // errorLogger.error(DmaapbcLogMessageEnum.UNEXPECTED_CONDITION, "attempting to use " + dClass + " to decrypt " + encPwd ); - //} - //try { - // pwd = dec.decrypt( encPwd ); - //} catch( IOException io ) { - // errorLogger.error(DmaapbcLogMessageEnum.DECRYPT_IO_ERROR, dClass, encPwd ); - //} + pwd = decryptor.decrypt(encPwd); @@ -101,7 +97,11 @@ public class AafService extends BaseLoggingClass { int rc = -1; logger.info( "entry: addPerm() " ); String pURL = aafURL + "authz/perm"; - rc = aaf.postAaf( perm, pURL ); + if ( useAAF ) { + rc = aaf.postAaf( perm, pURL ); + } else { + rc = 201; + } switch( rc ) { case 401: case 403: @@ -127,7 +127,12 @@ public class AafService extends BaseLoggingClass { logger.info( "entry: addGrant() " ); String pURL = aafURL + "authz/role/perm"; - rc = aaf.postAaf( grant, pURL ); + if ( useAAF ) { + rc = aaf.postAaf( grant, pURL ); + } else { + rc = 201; + } + switch( rc ) { case 401: case 403: @@ -155,7 +160,12 @@ public class AafService extends BaseLoggingClass { logger.info( "entry: delGrant() " ); String pURL = aafURL + "authz/role/:" + grant.getRole() + "/perm"; - rc = aaf.delAaf( grant, pURL ); + + if ( useAAF ) { + rc = aaf.delAaf( grant, pURL ); + } else { + rc = 200; + } switch( rc ) { case 401: case 403: diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPermissionInterface.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPermissionInterface.java deleted file mode 100644 index acc5da9..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPermissionInterface.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.authentication; - -import org.onap.dmaap.dbcapi.aaf.DmaapPerm; - -public interface ApiPermissionInterface { - public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException; - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPerms.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPerms.java deleted file mode 100644 index 478b772..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPerms.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.authentication; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.dmaap.dbcapi.aaf.AafService; -import org.onap.dmaap.dbcapi.aaf.DmaapGrant; -import org.onap.dmaap.dbcapi.aaf.DmaapPerm; -import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.model.Dmaap; -import org.onap.dmaap.dbcapi.service.DmaapService; -import org.onap.dmaap.dbcapi.util.DmaapConfig; - -public class ApiPerms extends BaseLoggingClass { - - private static class PermissionMap { - static final EELFLogger logger = EELFManager.getInstance().getLogger( PermissionMap.class ); - static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - String uri; - String action; - String[] roles; - - public String getUri() { - return uri; - } - public void setUri(String uri) { - this.uri = uri; - } - public String getAction() { - return action; - } - public void setAction(String action) { - this.action = action; - } - - public String[] getRoles() { - return roles; - } - public void setRoles(String[] roles) { - this.roles = roles; - } - - private PermissionMap( String u, String a, String[] r ) { - this.setUri(u); - this.setAction(a); - this.setRoles(r); - } - - static public void initMap( PermissionMap[] pmap, String instance ) { - - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - String api = p.getProperty("ApiNamespace", "apiNamespace.not.set"); - - // this is needed because PE AAF may be a different instance than AAF used by MR - String peEnv = p.getProperty("PeAafEnvironment", "notSet"); - String url = p.getProperty( new String( "PeAafUrl." + peEnv ), "URL.not.set" ); - logger.info( "PeAafEnvironment=" + peEnv + " using URL " + url); - AafService aaf = new AafService(ServiceType.AAF_Admin, url ); - - for ( int i = 0; i < pmap.length ; i++ ) { - String uri = new String( api + "." + pmap[i].getUri()); - DmaapPerm perm = new DmaapPerm( uri, instance, pmap[i].getAction() ); - int rc = aaf.addPerm( perm ); - if ( rc != 201 && rc != 409 ) { - errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "add perm", perm.toString() ); - - } - for( String r: pmap[i].getRoles()) { - String fr = new String( api + "." + r ); - logger.debug( "i:" + i + " granting perm " + perm.toString()+ " to role=" + fr ); - DmaapGrant grant = new DmaapGrant( perm, fr ); - rc = aaf.addGrant( grant ); - if ( rc != 201 && rc != 409 ) { - errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "grant perm", perm.toString() ); - } - } - - } - } - } - - static PermissionMap[] bootMap = { - new PermissionMap( "dmaap", "GET", new String[] { "Controller" }), - new PermissionMap( "dmaap", "POST", new String[] { "Controller" }), - new PermissionMap( "dmaap", "PUT", new String[] { "Controller" }), - new PermissionMap( "dmaap", "DELETE", new String[] { "Controller" }) - - }; - - static PermissionMap[] envMap = { - new PermissionMap( "dmaap", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "dmaap", "POST", new String[] { "Controller" } ), - new PermissionMap( "dmaap", "PUT", new String[] { "Controller" }), - new PermissionMap( "dmaap", "DELETE", new String[] { "Controller" }), - new PermissionMap( "bridge", "GET", new String[] { "Metrics" }), - //new PermissionMap( "bridge", "POST", new String[] { "Metrics" } ), - //new PermissionMap( "bridge", "PUT", new String[] { "Metrics" }), - //new PermissionMap( "bridge", "DELETE", new String[] { "Metrics" }), - new PermissionMap( "dcaeLocations", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "dcaeLocations", "POST", new String[] { "Controller" } ), - new PermissionMap( "dcaeLocations", "PUT", new String[] { "Controller" }), - new PermissionMap( "dcaeLocations", "DELETE", new String[] { "Controller" }), - new PermissionMap( "dr_nodes", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "PortalUser" }), - new PermissionMap( "dr_nodes", "POST", new String[] { "Controller" } ), - new PermissionMap( "dr_nodes", "PUT", new String[] { "Controller" }), - new PermissionMap( "dr_nodes", "DELETE", new String[] { "Controller" }), - new PermissionMap( "dr_pubs", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "dr_pubs", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), - new PermissionMap( "dr_pubs", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), - new PermissionMap( "dr_pubs", "DELETE", new String[] { "Controller", "Orchestrator","PortalUser" }), - new PermissionMap( "dr_subs", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "dr_subs", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), - new PermissionMap( "dr_subs", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), - new PermissionMap( "dr_subs", "DELETE", new String[] { "Controller", "Orchestrator","PortalUser" }), - new PermissionMap( "feeds", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "feeds", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), - new PermissionMap( "feeds", "PUT", new String[] { "Controller", "Orchestrator", "PortalUser" }), - new PermissionMap( "feeds", "DELETE", new String[] { "Controller", "PortalUser" }), - new PermissionMap( "mr_clients", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "mr_clients", "POST", new String[] { "Controller","Orchestrator", "PortalUser" } ), - new PermissionMap( "mr_clients", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), - new PermissionMap( "mr_clients", "DELETE", new String[] { "Controller","Orchestrator", "PortalUser" }), - new PermissionMap( "mr_clusters", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "mr_clusters", "POST", new String[] { "Controller" } ), - new PermissionMap( "mr_clusters", "PUT", new String[] { "Controller" }), - new PermissionMap( "mr_clusters", "DELETE", new String[] { "Controller" }), - new PermissionMap( "topics", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), - new PermissionMap( "topics", "POST", new String[] { "Controller", "Orchestrator" } ), - new PermissionMap( "topics", "PUT", new String[] { "Controller", "Orchestrator" }), - new PermissionMap( "topics", "DELETE", new String[] { "Controller", "Orchestrator" }) - }; - - public void setBootMap() { - String instance = "boot"; - PermissionMap.initMap( bootMap, instance ); - } - - public void setEnvMap() { - Dmaap dmaap = new DmaapService().getDmaap(); - String dmaap_name = dmaap.getDmaapName(); - PermissionMap.initMap( envMap, dmaap_name ); - } - - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPolicy.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPolicy.java deleted file mode 100644 index a86f83f..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/ApiPolicy.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.authentication; - -import org.onap.dmaap.dbcapi.aaf.DmaapPerm; -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.util.DmaapConfig; - -public class ApiPolicy extends BaseLoggingClass { - static String allow = "allow"; - String dClass = null; - ApiPermissionInterface perm = null; - - public ApiPolicy() { - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - dClass = p.getProperty( "ApiPermission.Class", allow ); - logger.info( "ApiPolicy implements " + dClass); - if ( dClass.equalsIgnoreCase( allow )) { - return; - } - - try { - perm = (ApiPermissionInterface) (Class.forName(dClass).newInstance()); - } catch (Exception ee ) { - errorLogger.error(DmaapbcLogMessageEnum.UNEXPECTED_CONDITION, "attempting to instantiate " + dClass ); - errorLogger.error( "trace is: " + ee ); - } - } - - public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException { - if ( dClass.equalsIgnoreCase( allow )) { - return; - } - - // execute check of loaded class - perm.check( mechid, pwd, p ); - - } - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/AuthenticationErrorException.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/AuthenticationErrorException.java deleted file mode 100644 index c740eac..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/authentication/AuthenticationErrorException.java +++ /dev/null @@ -1,29 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.authentication; - -public class AuthenticationErrorException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnection.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnection.java deleted file mode 100644 index c744021..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnection.java +++ /dev/null @@ -1,813 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.client; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.ConnectException; -import java.net.ProtocolException; -import java.net.SocketException; -import java.net.URL; -import java.util.ArrayList; - -import javax.net.ssl.HttpsURLConnection; - -import org.apache.log4j.Logger; -import org.apache.log4j.PropertyConfigurator; -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.model.ApiError; -import org.onap.dmaap.dbcapi.model.DR_Pub; -import org.onap.dmaap.dbcapi.model.DR_Sub; -import org.onap.dmaap.dbcapi.model.Feed; -import org.onap.dmaap.dbcapi.service.DmaapService; -import org.onap.dmaap.dbcapi.util.RandomInteger; - - - -public class DrProvConnection extends BaseLoggingClass { - - - private String provURL; - - private HttpsURLConnection uc; - - - public DrProvConnection() { - provURL = new DmaapService().getDmaap().getDrProvUrl(); - if ( provURL.length() < 1 ) { - errorLogger.error( DmaapbcLogMessageEnum.PREREQ_DMAAP_OBJECT, "getDrProvUrl"); - } - - } - - public boolean makeFeedConnection() { - return makeConnection( provURL ); - } - public boolean makeFeedConnection(String feedId) { - return makeConnection( provURL + "/feed/" + feedId ); - } - public boolean makeSubPostConnection( String subURL ) { - String[] parts = subURL.split("/"); - String revisedURL = provURL + "/" + parts[3] + "/" + parts[4]; - logger.info( "mapping " + subURL + " to " + revisedURL ); - return makeConnection( revisedURL ); - } - public boolean makeSubPutConnection( String subId ) { - String revisedURL = provURL + "/subs/" + subId; - logger.info( "mapping " + subId + " to " + revisedURL ); - return makeConnection( revisedURL ); - } - - public boolean makeIngressConnection( String feed, String user, String subnet, String nodep ) { - String uri = String.format("/internal/route/ingress/?feed=%s&user=%s&subnet=%s&nodepatt=%s", - feed, user, subnet, nodep ); - return makeConnection( provURL + uri ); - } - public boolean makeEgressConnection( String sub, String nodep ) { - String uri = String.format("/internal/route/egress/?sub=%s&node=%s", - sub, nodep ); - return makeConnection( provURL + uri ); - } - public boolean makeNodesConnection( String varName ) { - - String uri = String.format("/internal/api/%s", varName); - return makeConnection( provURL + uri ); - } - - public boolean makeNodesConnection( String varName, String val ) { - - if ( val == null ) { - return false; - } - String cv = val.replaceAll("\\|", "%7C"); - String uri = String.format( "/internal/api/%s?val=%s", varName, cv ); - - return makeConnection( provURL + uri ); - } - - private boolean makeConnection( String pURL ) { - - try { - URL u = new URL( pURL ); - uc = (HttpsURLConnection) u.openConnection(); - uc.setInstanceFollowRedirects(false); - logger.info( "successful connect to " + pURL ); - return(true); - } catch (Exception e) { - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR, pURL, e.getMessage() ); - e.printStackTrace(); - return(false); - } - - } - - public String bodyToString( InputStream is ) { - logger.info( "is=" + is ); - StringBuilder sb = new StringBuilder(); - BufferedReader br = new BufferedReader( new InputStreamReader(is)); - String line; - try { - while ((line = br.readLine()) != null ) { - sb.append( line ); - } - } catch (IOException ex ) { - errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION, ex.getMessage()); - } - - return sb.toString(); - } - - - public String doPostFeed( Feed postFeed, ApiError err ) { - - byte[] postData = postFeed.getBytes(); - logger.info( "post fields=" + postData.toString() ); - String responsemessage = null; - String responseBody = null; - - try { - logger.info( "uc=" + uc ); - uc.setRequestMethod("POST"); - uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() ); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc == 201 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else { - err.setCode( rc ); - err.setMessage(responsemessage); - } - - } catch (ConnectException ce) { - errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); - err.setCode( 500 ); - err.setMessage("Backend connection refused"); - } catch (SocketException se) { - errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from prov server" ); - err.setCode( 500 ); - err.setMessage( "Unable to read response from DR"); - } catch (Exception e) { - logger.warn("Unable to read response " ); - e.printStackTrace(); - try { - err.setCode( uc.getResponseCode()); - err.setMessage(uc.getResponseMessage()); - } catch (Exception e2) { - err.setCode( 500 ); - err.setMessage("Unable to determine response message"); - } - } - finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return responseBody; - - } - - - // the POST for /internal/route/ingress doesn't return any data, so needs a different function - // the POST for /internal/route/egress doesn't return any data, so needs a different function - public int doXgressPost( ApiError err ) { - - String responsemessage = null; - int rc = -1; - - try { - uc.setRequestMethod("POST"); -// uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); -// uc.setRequestProperty( "charset", "utf-8"); -// uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() ); -// uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); -// uc.setUseCaches(false); -// uc.setDoOutput(true); - OutputStream os = null; - - - try { - uc.connect(); - os = uc.getOutputStream(); - - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - - if (rc < 200 || rc >= 300 ) { - err.setCode( rc ); - err.setMessage(responsemessage); - } - } catch (Exception e) { - System.err.println("Unable to read response " ); - e.printStackTrace(); - } finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - - return rc; - - } - - public String doPostDr_Sub( DR_Sub postSub, ApiError err ) { - logger.info( "entry: doPostDr_Sub() " ); - byte[] postData = postSub.getBytes(); - logger.info( "post fields=" + postData ); - String responsemessage = null; - String responseBody = null; - - try { - - uc.setRequestMethod("POST"); - - uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc == 201 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else { - err.setCode(rc); - err.setMessage(responsemessage); - } - - } catch (Exception e) { - System.err.println("Unable to read response " ); - e.printStackTrace(); - } finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return responseBody; - - } - - - public String doPutFeed(Feed putFeed, ApiError err) { - byte[] postData = putFeed.getBytes(); - logger.info( "post fields=" + postData.toString() ); - String responsemessage = null; - String responseBody = null; - - try { - logger.info( "uc=" + uc ); - uc.setRequestMethod("PUT"); - uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", putFeed.getOwner() ); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc >= 200 && rc < 300 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else if ( rc == 404 ) { - err.setCode( rc ); - err.setFields( "feedid"); - String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?"; - err.setMessage( message ); - errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() ); - - } else { - err.setCode( rc ); - err.setMessage(responsemessage); - } - - } catch (ConnectException ce) { - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); - err.setCode( 500 ); - err.setMessage("Backend connection refused"); - } catch (SocketException se) { - errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" ); - err.setCode( 500 ); - err.setMessage( "Unable to read response from DR"); - } catch (Exception e) { - logger.warn("Unable to read response " ); - e.printStackTrace(); - try { - err.setCode( uc.getResponseCode()); - err.setMessage(uc.getResponseMessage()); - } catch (Exception e2) { - err.setCode( 500 ); - err.setMessage("Unable to determine response message"); - } - } finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return responseBody; - } - public String doPutDr_Sub(DR_Sub postSub, ApiError err) { - logger.info( "entry: doPutDr_Sub() " ); - byte[] postData = postSub.getBytes(); - logger.info( "post fields=" + postData ); - String responsemessage = null; - String responseBody = null; - - try { - - uc.setRequestMethod("PUT"); - - uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc == 200 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else { - err.setCode(rc); - err.setMessage(responsemessage); - } - - } catch (ConnectException ce) { - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); - err.setCode( 500 ); - err.setMessage("Backend connection refused"); - } catch (Exception e) { - System.err.println("Unable to read response " ); - e.printStackTrace(); - } finally { - uc.disconnect(); - } - return responseBody; - - } - - public String doGetNodes( ApiError err ) { - logger.info( "entry: doGetNodes() " ); - //byte[] postData = postSub.getBytes(); - //logger.info( "get fields=" + postData ); - String responsemessage = null; - String responseBody = null; - logger.info( "templog:doGetNodes at 12.10.14.10" ); - - try { - logger.info( "templog:doGetNodes at 12.10.14.11" ); - - uc.setRequestMethod("GET"); - - //uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); - //uc.setRequestProperty( "charset", "utf-8"); - //uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); - //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - //uc.setUseCaches(false); - //uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - logger.info( "templog:doGetNodes at 12.10.14.12" ); - try { - uc.connect(); - logger.info( "templog:doGetNodes at 12.10.14.13" ); - //os = uc.getOutputStream(); - //os.write( postData ); - - } catch (ProtocolException pe) { - logger.info( "templog:doGetNodes at 12.10.14.14" ); - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - logger.info( "templog:doGetNodes at 12.10.14.15" ); - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - logger.info( "templog:doGetNodes at 12.10.14.16" ); - - - if (responsemessage == null) { - logger.info( "templog:doGetNodes at 12.10.14.17" ); - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - logger.info( "templog:doGetNodes at 12.10.14.18" ); - err.setCode(rc); // may not really be an error, but we save rc - if (rc == 200 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - } else { - err.setMessage(responsemessage); - } - - logger.info( "templog:doGetNodes at 12.10.14.19" ); - } catch (ConnectException ce) { - logger.info( "templog:doGetNodes at 12.10.14.20" ); - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); - err.setCode( 500 ); - err.setMessage("Backend connection refused"); - } catch (Exception e) { - logger.info( "templog:doGetNodes at 12.10.14.21" ); - System.err.println("Unable to read response " ); - e.printStackTrace(); - } finally { - logger.info( "templog:doGetNodes at 12.10.14.22" ); - if ( uc != null ) uc.disconnect(); - } - logger.info( "templog:doGetNodes at 12.10.14.23" ); - return responseBody; - - } - public String doPutNodes( ApiError err ) { - logger.info( "entry: doPutNodes() " ); - //byte[] postData = nodeList.getBytes(); - //logger.info( "get fields=" + postData ); - String responsemessage = null; - String responseBody = null; - - try { - - uc.setRequestMethod("PUT"); - - //uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); - //uc.setRequestProperty( "charset", "utf-8"); - //uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); - //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - //uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - //os = uc.getOutputStream(); - //os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - err.setCode(rc); - if (rc == 200 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else { - - err.setMessage(responsemessage); - } - - } catch (Exception e) { - System.err.println("Unable to read response " + e.getMessage() ); - e.printStackTrace(); - } finally { - if ( uc != null ) { - uc.disconnect(); - } - } - return responseBody; - - } - - public String doDeleteFeed(Feed putFeed, ApiError err) { - //byte[] postData = putFeed.getBytes(); - //logger.info( "post fields=" + postData.toString() ); - String responsemessage = null; - String responseBody = null; - - try { - logger.info( "uc=" + uc ); - uc.setRequestMethod("DELETE"); - uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", putFeed.getOwner() ); - //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - int rc = -1; - - try { - uc.connect(); - os = uc.getOutputStream(); - //os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc >= 200 && rc < 300 ) { - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - - } else if ( rc == 404 ) { - err.setCode( rc ); - err.setFields( "feedid"); - String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?"; - err.setMessage( message ); - errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() ); - - } else { - err.setCode( rc ); - err.setMessage(responsemessage); - } - - } catch (ConnectException ce) { - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); - err.setCode( 500 ); - err.setMessage("Backend connection refused"); - } catch (SocketException se) { - errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" ); - err.setCode( 500 ); - err.setMessage( "Unable to read response from DR"); - } catch (Exception e) { - logger.warn("Unable to read response " ); - e.printStackTrace(); - try { - err.setCode( uc.getResponseCode()); - err.setMessage(uc.getResponseMessage()); - } catch (Exception e2) { - err.setCode( 500 ); - err.setMessage("Unable to determine response message"); - } - } finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return responseBody; - } - - /* - public static void main( String[] args ) throws Exception { - PropertyConfigurator.configure("log4j.properties"); - logger.info("Started."); - - RandomInteger ri = new RandomInteger(10000); - //String postJSON = String.format("{\"name\": \"dgl feed %d\", \"version\": \"v1.0\", \"description\": \"dgl feed N for testing\", \"authorization\": { \"classification\": \"unclassified\", \"endpoint_addrs\": [],\"endpoint_ids\": [{\"password\": \"test\",\"id\": \"test\"}]}}", ri.next()) ; - int i = ri.next(); - Feed tst = new Feed( "dgl feed " + i, - "v1.0", - "dgl feed " + i + "for testing", - "TEST", - "unclassified" - ); - ArrayList pubs = new ArrayList(); - pubs.add( new DR_Pub( "centralLocation" ) ); - tst.setPubs(pubs); - - boolean rc; - DrProvConnection context = new DrProvConnection(); - rc = context.makeFeedConnection(); - logger.info( "makeFeedConnection returns " + rc); - ApiError err = new ApiError(); - if ( rc ) { - String tmp = context.doPostFeed( tst, err ); - logger.info( "doPostFeed returns " + tmp); - } - - } - */ - - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnection.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnection.java deleted file mode 100644 index 529cbf0..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnection.java +++ /dev/null @@ -1,223 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.client; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.ConnectException; -import java.net.ProtocolException; -import java.net.URL; -import java.net.UnknownHostException; - -import javax.net.ssl.HttpsURLConnection; - -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; -import org.onap.dmaap.dbcapi.aaf.AafDecrypt; -import org.onap.dmaap.dbcapi.aaf.AafService; -import org.onap.dmaap.dbcapi.aaf.DecryptionInterface; -import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.model.ApiError; -import org.onap.dmaap.dbcapi.model.MR_Cluster; -import org.onap.dmaap.dbcapi.model.Topic; -import org.onap.dmaap.dbcapi.util.DmaapConfig; - -public class MrProvConnection extends BaseLoggingClass{ - - private String provURL; - - private HttpsURLConnection uc; - - - private String topicMgrCred; - - private String getCred( ) { - String mechIdProperty = "aaf.TopicMgrUser"; - String pwdProperty = "aaf.TopicMgrPassword"; - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - logger.info( "templog:getCred: 10"); - - String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" ); - logger.info( "templog:getCred: 20"); - - String pwd = ""; - String encPwd = p.getProperty( pwdProperty, "notSet" ); - logger.info( "templog:getCred: 30"); - - AafDecrypt decryptor = new AafDecrypt(); - logger.info( "templog:getCred: 40"); - pwd = decryptor.decrypt(encPwd); - logger.info( "templog:getCred: 50"); - - return user + ":" + pwd; - - - - } - - - public MrProvConnection( ) { - topicMgrCred = getCred(); - - } - - public boolean makeTopicConnection( MR_Cluster cluster ) { - logger.info( "connect to cluster: " + cluster.getDcaeLocationName()); - - - provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create"; - - return makeConnection( provURL ); - } - - private boolean makeConnection( String pURL ) { - logger.info( "makeConnection to " + pURL ); - - try { - URL u = new URL( pURL ); - uc = (HttpsURLConnection) u.openConnection(); - uc.setInstanceFollowRedirects(false); - logger.info( "open connect to " + pURL ); - return(true); - } catch( UnknownHostException uhe ){ - logger.error( "Caught UnknownHostException for " + pURL); - return(false); - } catch (Exception e) { - logger.error("Unexpected error during openConnection of " + pURL ); - e.printStackTrace(); - return(false); - } - - } - - static String bodyToString( InputStream is ) { - StringBuilder sb = new StringBuilder(); - BufferedReader br = new BufferedReader( new InputStreamReader(is)); - String line; - try { - while ((line = br.readLine()) != null ) { - sb.append( line ); - } - } catch (IOException ex ) { - errorLogger.error( "IOexception:" + ex); - } - - return sb.toString(); - } - - public String doPostTopic( Topic postTopic, ApiError err ) { - String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes()); - - - String responsemessage = null; - int rc = -1; - - - try { - byte[] postData = postTopic.getBytes(); - logger.info( "post fields=" + postData.toString() ); - uc.setRequestProperty("Authorization", auth); - logger.info( "Authenticating with " + auth ); - uc.setRequestMethod("POST"); - uc.setRequestProperty("Content-Type", "application/json"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } catch ( UnknownHostException uhe ) { - errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL ); - err.setCode(500); - err.setMessage("Unknown Host Exception"); - err.setFields( uc.getURL().getHost()); - return new String( "500: " + uhe.getMessage()); - }catch ( ConnectException ce ) { - errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" ); - err.setCode(500); - err.setMessage("HTTP Connection Exception"); - err.setFields( uc.getURL().getHost()); - return new String( "500: " + ce.getMessage()); - } - rc = uc.getResponseCode(); - logger.info( "http response code:" + rc ); - err.setCode(rc); - responsemessage = uc.getResponseMessage(); - logger.info( "responsemessage=" + responsemessage ); - err.setMessage(responsemessage); - - - if (responsemessage == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - responsemessage = h0.substring(j + 1); - } - } - } - if (rc >= 200 && rc < 300 ) { - String responseBody = null; - responseBody = bodyToString( uc.getInputStream() ); - logger.info( "responseBody=" + responseBody ); - return responseBody; - - } - - } catch (Exception e) { - System.err.println("Unable to read response " ); - e.printStackTrace(); - } - finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return new String( rc +": " + responsemessage ); - - } - - - - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnection.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnection.java deleted file mode 100644 index bfbe826..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnection.java +++ /dev/null @@ -1,186 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.client; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.ProtocolException; -import java.net.URL; - -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLException; - -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.model.ApiError; -import org.onap.dmaap.dbcapi.model.MR_Cluster; -import org.onap.dmaap.dbcapi.util.DmaapConfig; - -public class MrTopicConnection extends BaseLoggingClass { - private String topicURL; - - private HttpsURLConnection uc; - - - private String mmProvCred; - private String unit_test; - - - - public MrTopicConnection(String user, String pwd ) { - mmProvCred = new String( user + ":" + pwd ); - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - unit_test = p.getProperty( "UnitTest", "No" ); - } - - public boolean makeTopicConnection( MR_Cluster cluster, String topic, String overrideFqdn ) { - String fqdn = overrideFqdn != null ? overrideFqdn : cluster.getFqdn(); - logger.info( "connect to cluster: " + fqdn + " for topic: " + topic ); - - - topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ; - - return makeConnection( topicURL ); - } - - private boolean makeConnection( String pURL ) { - logger.info( "makeConnection to " + pURL ); - - try { - URL u = new URL( pURL ); - uc = (HttpsURLConnection) u.openConnection(); - uc.setInstanceFollowRedirects(false); - logger.info( "open connection to " + pURL ); - return(true); - } catch (Exception e) { - logger.error("Unexpected error during openConnection of " + pURL ); - e.printStackTrace(); - return(false); - } - - } - - static String bodyToString( InputStream is ) { - StringBuilder sb = new StringBuilder(); - BufferedReader br = new BufferedReader( new InputStreamReader(is)); - String line; - try { - while ((line = br.readLine()) != null ) { - sb.append( line ); - } - } catch (IOException ex ) { - errorLogger.error( "IOexception:" + ex); - } - - return sb.toString(); - } - - public ApiError doPostMessage( String postMessage ) { - ApiError response = new ApiError(); - String auth = "Basic " + Base64.encodeBase64String(mmProvCred.getBytes()); - - - - try { - byte[] postData = postMessage.getBytes(); - logger.info( "post fields=" + postMessage ); - uc.setRequestProperty("Authorization", auth); - logger.info( "Authenticating with " + auth ); - uc.setRequestMethod("POST"); - uc.setRequestProperty("Content-Type", "application/json"); - uc.setRequestProperty( "charset", "utf-8"); - uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); - uc.setUseCaches(false); - uc.setDoOutput(true); - OutputStream os = null; - - - try { - uc.connect(); - os = uc.getOutputStream(); - os.write( postData ); - - } catch (ProtocolException pe) { - // Rcvd error instead of 100-Continue - try { - // work around glitch in Java 1.7.0.21 and likely others - // without this, Java will connect multiple times to the server to run the same request - uc.setDoOutput(false); - } catch (Exception e) { - } - } catch ( SSLException se ) { - response.setCode(500); - response.setMessage( se.getMessage()); - return response; - - } - response.setCode( uc.getResponseCode()); - logger.info( "http response code:" + response.getCode()); - response.setMessage( uc.getResponseMessage() ); - logger.info( "response message=" + response.getMessage() ); - - - if ( response.getMessage() == null) { - // work around for glitch in Java 1.7.0.21 and likely others - // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is - String h0 = uc.getHeaderField(0); - if (h0 != null) { - int i = h0.indexOf(' '); - int j = h0.indexOf(' ', i + 1); - if (i != -1 && j != -1) { - response.setMessage( h0.substring(j + 1) ); - } - } - } - if ( response.is2xx() ) { - response.setFields( bodyToString( uc.getInputStream() ) ); - logger.info( "responseBody=" + response.getFields() ); - return response; - - } - - } catch (Exception e) { - if ( unit_test.equals( "Yes" ) ) { - response.setCode(200); - response.setMessage( "simulated response"); - logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test ); - } else { - - response.setCode(500); - response.setMessage( "Unable to read response"); - logger.warn( response.getMessage() ); - e.printStackTrace(); - } - } - finally { - try { - uc.disconnect(); - } catch ( Exception e ) {} - } - return response; - - } - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnWrapper.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnWrapper.java deleted file mode 100644 index 019caef..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnWrapper.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.sql.*; - - -public abstract class ConnWrapper { - protected Connection c; - protected PreparedStatement ps; - protected ResultSet rs; - protected abstract T run(U u) throws Exception; - public T protect(ConnectionFactory cf, U u) throws DBException { - try { - try { - return(attempt(cf, u, false)); - } catch (SQLException sqle) { - return(attempt(cf, u, true)); - } - } catch (RuntimeException rte) { - throw rte; - } catch (Exception e) { - throw new DBException(e); - } - } - private T attempt(ConnectionFactory cf, U u, boolean fresh) throws Exception { - c = null; - ps = null; - rs = null; - try { - c = cf.get(fresh); - T ret = run(u); - cf.release(c); - c = null; - return(ret); - } finally { - if (rs != null) { try { rs.close(); } catch (Exception e) {}} - rs = null; - if (ps != null) { try { ps.close(); } catch (Exception e) {}} - ps = null; - if (c != null) { try { c.close(); } catch (Exception e) {}} - c = null; - } - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnectionFactory.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnectionFactory.java deleted file mode 100644 index 64a2959..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/ConnectionFactory.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.sql.*; -import java.util.*; - -import org.apache.log4j.Logger; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.util.DmaapConfig; - -public class ConnectionFactory { - static final EELFLogger logger = EELFManager.getInstance().getLogger( ConnectionFactory.class ); - static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger(); - static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); - static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - static final EELFLogger serverLogger = EELFManager.getInstance().getServerLogger(); - - static { - try { - Class.forName("org.postgresql.Driver"); - } catch (Exception e) { - logger.error("Unable to load postgres driver " + e, e); - } - } - private static ConnectionFactory instance = new ConnectionFactory(); - private String host; - private String dbname; - private String dbuser; - private String dbcr; - public ConnectionFactory() { - Properties p = DmaapConfig.getConfig(); - host = p.getProperty("DB.host", "dcae-pstg-write-ftl.domain.notset.com"); - dbname = p.getProperty("DB.name", "dmaap"); - dbuser = p.getProperty("DB.user", "dmaap_admin"); - dbcr = p.getProperty("DB.cred", "test234-ftl"); - } - public static ConnectionFactory getDefaultInstance() { - return(instance); - } - private Connection[] pool = new Connection[5]; - private int cur; - public Connection get(boolean fresh) throws SQLException { - if (!fresh) { - synchronized(this) { - if (cur > 0) { - return(pool[--cur]); - } - } - } - Properties p = new Properties(); - p.put("user", dbuser); - p.put("password", dbcr); - return(DriverManager.getConnection("jdbc:postgresql://" + host + "/" + dbname, p)); - } - public void release(Connection c) { - synchronized(this) { - if (cur < pool.length) { - pool[cur++] = c; - return; - } - } - try { c.close(); } catch (Exception e) {} - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBException.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBException.java deleted file mode 100644 index f73e510..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBException.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; - -public class DBException extends RuntimeException { - static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - public DBException(Exception e) { - super(e); - errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_ERROR, e.getMessage()); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandler.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandler.java deleted file mode 100644 index 52af453..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandler.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.lang.reflect.*; -import java.sql.*; -import java.util.*; - -import org.apache.log4j.Logger; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; - - -public class DBFieldHandler { - static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - - public static interface SqlOp { - public Object get(ResultSet rs, int index) throws Exception; - public void set(PreparedStatement ps, int index, Object value) throws Exception; - } - private static class AofString implements SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - String val = rs.getString(index); - if (val == null) { - return(null); - } - String[] ret = val.split(","); - for (int i = 0; i < ret.length; i++) { - ret[i] = funesc(ret[i]); - } - return(ret); - } - public void set(PreparedStatement ps, int index, Object x) throws Exception { - String[] val = (String[])x; - if (val == null) { - ps.setString(index, null); - return; - } - StringBuffer sb = new StringBuffer(); - String sep = ""; - for (String s: val) { - sb.append(sep).append(fesc(s)); - sep = ","; - } - ps.setString(index, sb.toString()); - } - } - private static class EnumSql implements SqlOp { - private Class enclass; - public EnumSql(Class enclass) { - this.enclass = enclass; - } - @SuppressWarnings("unchecked") - public Object get(ResultSet rs, int index) throws Exception { - String val = rs.getString(index); - if (val == null) { - return(null); - } else { - return(Enum.valueOf(enclass, val)); - } - } - public void set(PreparedStatement ps, int index, Object value) throws Exception { - if (value == null) { - ps.setString(index, null); - } else { - ps.setString(index, value.toString()); - } - } - } - private static class SqlDate implements SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - return(rs.getTimestamp(index)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val instanceof java.util.Date && !(val instanceof java.sql.Timestamp)) { - val = new java.sql.Timestamp(((java.util.Date)val).getTime()); - } - ps.setTimestamp(index, (java.sql.Timestamp)val); - } - } - private static class SqlType implements SqlOp { - private Method sqlget; - private Method sqlset; - private SqlType(String tag) throws Exception { - sqlget = ResultSet.class.getMethod("get" + tag, Integer.TYPE); - sqlset = PreparedStatement.class.getMethod("set" + tag, Integer.TYPE, sqlget.getReturnType()); - sqltypes.put(sqlget.getReturnType().getName(), this); - } - public Object get(ResultSet rs, int index) throws Exception { - return(sqlget.invoke(rs, index)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - try { - sqlset.invoke(ps, index, val); - } catch (Exception e) { - errorLogger.error(DmaapbcLogMessageEnum.DB_FIELD_INIT_ERROR, Integer.toString(index), val.toString(), ps.toString()); - throw e; - } - } - } - private static Map sqltypes; - static { - sqltypes = new HashMap(); - sqltypes.put("[Ljava.lang.String;", new AofString()); - sqltypes.put("java.util.Date", new SqlDate()); - try { - new SqlType("Boolean"); - new SqlType("Timestamp"); - new SqlType("Double"); - new SqlType("Float"); - new SqlType("Int"); - new SqlType("Long"); - new SqlType("Short"); - new SqlType("String"); - } catch (Exception e) { - errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_INIT_ERROR, e.getMessage() ); - } - } - private Method objget; - private Method objset; - private SqlOp sqlop; - private int fieldnum; - public void copy(Object from, Object to) throws Exception { - objset.invoke(to, objget.invoke(from)); - } - public void setKey(Object o, String key) throws Exception { - objset.invoke(o, key); - } - public String getKey(Object o) throws Exception { - return((String)objget.invoke(o)); - } - public void toSQL(Object o, PreparedStatement ps) throws Exception { - sqlop.set(ps, fieldnum, objget.invoke(o)); - } - public void fromSQL(ResultSet r, Object o) throws Exception { - objset.invoke(o, sqlop.get(r, fieldnum)); - } - public DBFieldHandler(Class c, String fieldname, int fieldnum) throws Exception { - this(c, fieldname, fieldnum, null); - } - public DBFieldHandler(Class c, String fieldname, int fieldnum, SqlOp op) throws Exception { - this.fieldnum = fieldnum; - StringBuffer sb = new StringBuffer(); - for (String s: fieldname.split("_")) { - sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); - } - String camelcase = sb.toString(); - try { - objget = c.getMethod("is" + camelcase); - } catch (Exception e) { - objget = c.getMethod("get" + camelcase); - } - objset = c.getMethod("set" + camelcase, objget.getReturnType()); - sqlop = op; - if (sqlop != null) { - return; - } - Class x = objget.getReturnType(); - if (x.isEnum()) { - sqlop = new EnumSql(x); - return; - } - sqlop = sqltypes.get(x.getName()); - if (sqlop != null) { - return; - } - errorLogger.error(DmaapbcLogMessageEnum.DB_NO_FIELD_HANDLER, c.getName(), fieldname, Integer.toString(fieldnum), x.getName()); - } - public static String fesc(String s) { - if (s == null) { - return(s); - } - return(s.replaceAll("@", "@a").replaceAll(";", "@s").replaceAll(",", "@c")); - } - public static String funesc(String s) { - if (s == null) { - return(s); - } - return(s.replaceAll("@c", ",").replaceAll("@s", ";").replaceAll("@a", "@")); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBMap.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBMap.java deleted file mode 100644 index 8b8e3ad..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBMap.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.sql.*; -import java.util.*; - -public class DBMap extends TableHandler implements Map { - public DBMap(Class cls, String tabname, String keyfield) throws Exception { - this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyfield); - } - public DBMap(ConnectionFactory cf, Class cls, String tabname, String keyfield) throws Exception { - super(cf, cls, tabname, keyfield); - } - public void clear() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - public boolean containsKey(Object key) throws DBException { - return(get(key) != null); - } - public boolean containsValue(Object value) throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - public boolean isEmpty() { - return(false); - } - public Set> entrySet() throws DBException { - return(list()); - } - public Set keySet() throws DBException { - Set ret = new HashSet(); - for (Map.Entry x: list()) { - ret.add(x.getKey()); - } - return(ret); - } - public void putAll(Map m) throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - public int size() { - return(2); - } - public Collection values() throws DBException { - Collection ret = new Vector(); - for (Map.Entry x: list()) { - ret.add(x.getValue()); - } - return(ret); - } - public C get(Object key) throws DBException { - if (!(key instanceof String)) { - return(null); - } - return((new ConnWrapper() { - protected C run(String key) throws Exception { - ps = c.prepareStatement(getstmt); - ps.setString(1, (String)key); - rs = ps.executeQuery(); - if (!rs.next()) { - return(null); - } - C ret = cls.newInstance(); - for (DBFieldHandler f: fields) { - f.fromSQL(rs, ret); - } - return(ret); - } - }).protect(cf, (String)key)); - } - public Set> list() throws DBException { - return((new ConnWrapper>, Object>() { - protected Set> run(Object junk) throws Exception { - DBFieldHandler keyfield = fields[fields.length - 1]; - ps = c.prepareStatement(liststmt); - rs = ps.executeQuery(); - Set> ret = new HashSet>(); - while (rs.next()) { - C val = cls.newInstance(); - for (DBFieldHandler f: fields) { - f.fromSQL(rs, val); - } - String key = keyfield.getKey(val); - ret.add(new AbstractMap.SimpleEntry(key, val)); - } - return(ret); - } - }).protect(cf, null)); - } - public C put(String key, C val) throws DBException { - try { - fields[fields.length - 1].setKey(val, key); - } catch (Exception e) { - throw new DBException(e); - } - PreparedStatement ps = null; - return((new ConnWrapper() { - protected C run(C val) throws Exception { - ps = c.prepareStatement(insorreplstmt); - for (DBFieldHandler f: fields) { - f.toSQL(val, ps); - } - ps.executeUpdate(); - return(null); - } - }).protect(cf, val)); - } - public C remove(Object key) throws DBException { - if (!(key instanceof String)) { - return(null); - } - return((new ConnWrapper() { - protected C run(String key) throws Exception { - ps = c.prepareStatement(delstmt); - ps.setString(1, key); - ps.executeUpdate(); - return(null); - } - }).protect(cf, (String)key)); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBSingleton.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBSingleton.java deleted file mode 100644 index 8c158ca..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DBSingleton.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.sql.*; -import java.util.*; - -import org.onap.dmaap.dbcapi.util.Singleton; - -public class DBSingleton extends TableHandler implements Singleton { - private C singleton; - public DBSingleton(Class cls, String tabname) throws Exception { - this(ConnectionFactory.getDefaultInstance(), cls, tabname); - } - public DBSingleton(ConnectionFactory cf, Class cls, String tabname) throws Exception { - super(cf, cls, tabname, null); - singleton = cls.newInstance(); - } - public C get() throws DBException { - return((new ConnWrapper() { - protected C run(Object junk) throws Exception { - ps = c.prepareStatement(getstmt); - rs = ps.executeQuery(); - if (!rs.next()) { - return(null); - } - for (DBFieldHandler f: fields) { - f.fromSQL(rs, singleton); - } - return(singleton); - } - }).protect(cf, null)); - } - public void init(C val) throws DBException { - if (get() != null) { - return; - } - (new ConnWrapper() { - protected Void run(C val) throws Exception { - ps = c.prepareStatement(initstmt); - for (DBFieldHandler f: fields) { - f.toSQL(val, ps); - } - ps.executeUpdate(); - if (val != singleton) { - for (DBFieldHandler f: fields) { - f.copy(val, singleton); - } - } - return(null); - } - }).protect(cf, val); - } - public void update(C val) throws DBException { - (new ConnWrapper() { - protected Void run(C val) throws Exception { - ps = c.prepareStatement(insorreplstmt); - for (DBFieldHandler f: fields) { - f.toSQL(val, ps); - } - ps.executeUpdate(); - if (val != singleton) { - for (DBFieldHandler f: fields) { - f.copy(val, singleton); - } - } - return(null); - } - }).protect(cf, val); - } - public void remove() throws DBException { - (new ConnWrapper() { - protected Void run(Object junk) throws Exception { - ps = c.prepareStatement(delstmt); - ps.executeUpdate(); - return(null); - } - }).protect(cf, null); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DatabaseClass.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DatabaseClass.java deleted file mode 100644 index baa86a6..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/DatabaseClass.java +++ /dev/null @@ -1,270 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.util.*; -import java.sql.*; - -import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.util.DmaapConfig; -import org.onap.dmaap.dbcapi.util.Singleton; - - - - -public class DatabaseClass extends BaseLoggingClass { - - private static Singleton dmaap; - private static Map dcaeLocations; - private static Map dr_nodes; - private static Map dr_pubs; - private static Map dr_subs; - private static Map mr_clients; - private static Map mr_clusters; - private static Map feeds; - private static Map topics; - private static Map mirrors; - - private static long lastTime = 0L; - - private static class MirrorVectorHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - String val = rs.getString(index); - if (val == null) { - return(null); - } - Set rv = new HashSet(); - for (String s: val.split(",")) { - String[] f = s.split(";"); - if (f.length < 3) { - continue; - } - rv.add(new ReplicationVector(DBFieldHandler.funesc(f[0]), DBFieldHandler.funesc(f[1]), DBFieldHandler.funesc(f[2]))); - } - return(rv); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setString(index, null); - return; - } - Set xv = (Set)val; - StringBuffer sb = new StringBuffer(); - String sep = ""; - for (Object o: xv) { - ReplicationVector rv = (ReplicationVector)o; - sb.append(sep).append(DBFieldHandler.fesc(rv.getFqtn())).append(';').append(DBFieldHandler.fesc(rv.getSourceCluster())).append(';').append(DBFieldHandler.fesc(rv.getTargetCluster())); - sep = ","; - } - ps.setString(index, sb.toString()); - } - } - - // modified version of MirrorVectorHandler for Topics - private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - String val = rs.getString(index); - if (val == null) { - return(null); - } - List rv = new ArrayList(); - for (String s: val.split(",")) { - //String[] f = s.split(";"); - //if (f.length < 3) { - // continue; - //} - rv.add(new String(s)); - } - return(rv); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setString(index, null); - return; - } - @SuppressWarnings("unchecked") - List xv = (List)val; - StringBuffer sb = new StringBuffer(); - String sep = ""; - for (Object o: xv) { - String rv = (String)o; - sb.append(sep).append(DBFieldHandler.fesc(rv)); - sep = ","; - } - ps.setString(index, sb.toString()); - } - } - private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - int val = rs.getInt(index); - - return (ReplicationType.valueOf(val)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setInt(index, 0); - return; - } - @SuppressWarnings("unchecked") - ReplicationType rep = (ReplicationType) val; - ps.setInt(index, rep.getValue()); - } - } - public static Singleton getDmaap() { - return dmaap; - } - - - - public static Map getDcaeLocations() { - return dcaeLocations; - } - - public static Map getDr_nodes() { - return dr_nodes; - } - - public static Map getDr_subs() { - return dr_subs; - } - public static Map getDr_pubs() { - return dr_pubs; - } - - public static Map getMr_clients() { - return mr_clients; - } - - - public static Map getMr_clusters() { - return mr_clusters; - } - - public static Map getFeeds() { - return feeds; - } - public static Map getTopics() { - return topics; - } - public static Map getMirrorMakers() { - return mirrors; - } - - static { - try { - appLogger.info( "begin static initialization"); - appLogger.info( "initializing dmaap" ); - DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); - if ("true".equalsIgnoreCase(p.getProperty("UsePGSQL", "false"))) { - appLogger.info("Data from database"); - try { - LoadSchema.upgrade(); - } catch (Exception e) { - appLogger.warn("Problem updating DB schema", e); - } - try { - dmaap = new DBSingleton(Dmaap.class, "dmaap"); - dcaeLocations = new DBMap(DcaeLocation.class, "dcae_location", "dcae_location_name"); - dr_nodes = new DBMap(DR_Node.class, "dr_node", "fqdn"); - dr_pubs = new DBMap(DR_Pub.class, "dr_pub", "pub_id"); - dr_subs = new DBMap(DR_Sub.class, "dr_sub", "sub_id"); - mr_clients = new DBMap(MR_Client.class, "mr_client", "mr_client_id"); - mr_clusters = new DBMap(MR_Cluster.class, "mr_cluster", "dcae_location_name"); - feeds = new DBMap(Feed.class, "feed", "feed_id"); - TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); - topics = new DBMap(Topic.class, "topic", "fqtn"); - //TableHandler.setSpecialCase("mirror_maker", "vectors", new MirrorVectorHandler()); - TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler()); - mirrors = new DBMap(MirrorMaker.class, "mirror_maker", "mm_name"); - } catch (Exception e) { - errorLogger.error("Error initializing database access " + e, e); - System.exit(1); - } - } else { - appLogger.info("Data from memory"); - dmaap = new Singleton() { - private Dmaap dmaap; - public void remove() { - dmaap = null; - } - public void init(Dmaap val) { - if (dmaap == null) { - dmaap = val; - } - } - public Dmaap get() { - return(dmaap); - } - public void update(Dmaap nd) { - dmaap.setVersion(nd.getVersion()); - dmaap.setTopicNsRoot(nd.getTopicNsRoot()); - dmaap.setDmaapName(nd.getDmaapName()); - dmaap.setDrProvUrl(nd.getDrProvUrl()); - dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic()); - dmaap.setLoggingUrl(nd.getLoggingUrl()); - dmaap.setNodeKey(nd.getNodeKey()); - dmaap.setAccessKeyOwner(nd.getAccessKeyOwner()); - } - }; - dcaeLocations = new HashMap(); - dr_nodes = new HashMap(); - dr_pubs = new HashMap(); - dr_subs = new HashMap(); - mr_clients = new HashMap(); - mr_clusters = new HashMap(); - feeds = new HashMap(); - topics = new HashMap(); - mirrors = new HashMap(); - } - dmaap.init(new Dmaap("0", "", "", "", "", "", "", "")); - // check for, and set up initial data, if it isn't already there - Dmaap dmx = dmaap.get(); - if ("0".equals(dmx.getVersion())) { - - dmx = new Dmaap("0", "", "", "", "", "", "", ""); - dmx.setDmaapName(p.getProperty("DmaapName")); - dmx.setDrProvUrl("https://" + p.getProperty("DR.provhost", "notSet")); - dmx.setTopicNsRoot(p.getProperty("topicNsRoot")); - dmx.setBridgeAdminTopic("DCAE_MM_AGENT"); - - dmaap.update(dmx); - } - } catch (Exception e) { - errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage()); - } - } - - public synchronized static String getNextClientId() { - - long id = System.currentTimeMillis(); - if ( id <= lastTime ) { - id = lastTime + 1; - } - lastTime = id; - return Long.toString(id); - } - - - - -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchema.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchema.java deleted file mode 100644 index bbd6f18..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchema.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.io.*; -import java.sql.*; - -import org.apache.log4j.Logger; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; - -public class LoadSchema { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoadSchema.class); - private static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger(); - private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - private static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); - private static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); - private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - - static int getVer(Statement s) throws SQLException { - ResultSet rs = null; - try { - rs = s.executeQuery("SELECT version FROM dmaapbc_sch_ver"); - rs.next(); - return(rs.getInt(1)); - } finally { - if (rs != null) { - rs.close(); - } - } - } - static void upgrade() throws SQLException { - ConnectionFactory cf = ConnectionFactory.getDefaultInstance(); - Connection c = null; - Statement stmt = null; - InputStream is = null; - try { - c = cf.get(true); - stmt = c.createStatement(); - int newver = -1; - try { - newver = getVer(stmt); - } catch (Exception e) {} - logger.info("Database schema currently at version " + newver++); - while ((is = LoadSchema.class.getClassLoader().getResourceAsStream("schema_" + newver + ".sql")) != null) { - logger.info("Upgrading database schema to version " + newver); - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - String s; - String sofar = null; - while ((s = br.readLine()) != null) { - logger.info("SCHEMA: " + s); - s = s.trim(); - if (s.length() == 0 || s.startsWith("--")) { - continue; - } - if (sofar == null) { - sofar = s; - } else { - sofar = sofar + " " + s; - } - if (s.endsWith(";")) { - sofar = sofar.substring(0, sofar.length() - 1); - boolean ignore = false; - if (sofar.startsWith("@")) { - ignore = true; - sofar = sofar.substring(1).trim(); - } - try { - stmt.execute(sofar); - } catch (SQLException sqle) { - if (!ignore) { - throw sqle; - } - } - sofar = null; - } - } - is.close(); - is = null; - if (getVer(stmt) != newver) { - throw new SQLException("Schema version not properly updated to " + newver + " by upgrade script"); - } - logger.info("Upgrade to database schema version " + newver + " successful"); - newver++; - } - } catch (IOException ioe) { - throw new SQLException(ioe); - } finally { - if (stmt != null) { try { stmt.close(); } catch (Exception e) {}} - if (c != null) { try { c.close(); } catch (Exception e) {}} - } - } - public static void main(String[] args) throws Exception { - upgrade(); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/TableHandler.java b/src/main/java/org/onap/dmaap/dbcapi/aaf/database/TableHandler.java deleted file mode 100644 index fe610ab..0000000 --- a/src/main/java/org/onap/dmaap/dbcapi/aaf/database/TableHandler.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dmaap.dbcapi.aaf.database; - -import java.util.*; -import java.lang.reflect.*; -import java.sql.*; - -class TableHandler { - protected ConnectionFactory cf; - protected boolean haskey; - protected String delstmt; - protected String insorreplstmt; - protected String getstmt; - protected String liststmt; - protected String initstmt; - protected Class cls; - protected DBFieldHandler[] fields; - private static Map> exceptions = new HashMap>(); - public static void setSpecialCase(String dbtabname, String dbfldname, DBFieldHandler.SqlOp handler) { - Map m = exceptions.get(dbtabname); - if (m == null) { - m = new HashMap(); - exceptions.put(dbtabname, m); - } - m.put(dbfldname, handler); - } - public static DBFieldHandler.SqlOp getSpecialCase(String dbtabname, String dbfldname) { - Map m = exceptions.get(dbtabname); - if (m != null) { - return(m.get(dbfldname)); - } - return(null); - } - protected TableHandler(Class cls, String tabname, String keyname) throws Exception { - this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyname); - } - protected TableHandler(ConnectionFactory cf, Class cls, String tabname, String keyname) throws Exception { - this.cf = cf; - Connection c = null; - try { - c = cf.get(false); - setup(c.getMetaData(), cls, tabname, keyname); - } finally { - if (c != null) { - cf.release(c); - } - } - } - private void setup(DatabaseMetaData dmd, Class cls, String tabname, String keyname) throws Exception { - this.cls = cls; - Vector h = new Vector(); - ResultSet rs = dmd.getColumns("", "public", tabname, null); - StringBuffer sb1 = new StringBuffer(); - StringBuffer sb2 = new StringBuffer(); - StringBuffer sb3 = new StringBuffer(); - int count = 0; - while (rs.next()) { - if (!rs.getString(3).equals(tabname)) { - continue; - } - String cname = rs.getString(4); - if (cname.equals(keyname)) { - haskey = true; - continue; - } - sb1.append(", ").append(cname); - sb2.append(", ?"); - sb3.append(", EXCLUDED.").append(cname); - count++; - h.add(new DBFieldHandler(cls, cname, count, getSpecialCase(tabname, cname))); - } - if (count == 0) { - throw new SQLException("Table " + tabname + " not found"); - } - String clist = sb1.substring(2); - String qlist = sb2.substring(2); - String elist = sb3.substring(2); - if (keyname != null && !haskey) { - throw new SQLException("Table " + tabname + " does not have key column " + keyname + " not found"); - } - if (haskey) { - count++; - h.add(new DBFieldHandler(cls, keyname, count, getSpecialCase(tabname, keyname))); - delstmt = "DELETE FROM " + tabname + " WHERE " + keyname + " = ?"; - insorreplstmt = "INSERT INTO " + tabname + " (" + clist + ", " + keyname + ") VALUES (" + qlist + ", ?) ON CONFLICT(" + keyname + ") DO UPDATE SET (" + clist + ") = (" + elist + ")"; - getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname + " WHERE " + keyname + " = ?"; - liststmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname; - } else { - delstmt = "DELETE FROM " + tabname; - initstmt = "INSERT INTO " + tabname + " (" + clist + ") VALUES (" + qlist + ")"; - insorreplstmt = "UPDATE " + tabname + " SET (" + clist + ") = (" + qlist + ")"; - getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname; - } - fields = h.toArray(new DBFieldHandler[h.size()]); - } -} diff --git a/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPermissionInterface.java b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPermissionInterface.java new file mode 100644 index 0000000..fa695f9 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPermissionInterface.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.authentication; + +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; + +public interface ApiPermissionInterface { + public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException; + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPerms.java b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPerms.java new file mode 100644 index 0000000..6749932 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPerms.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.authentication; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.dmaap.dbcapi.aaf.AafService; +import org.onap.dmaap.dbcapi.aaf.DmaapGrant; +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; +import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.model.Dmaap; +import org.onap.dmaap.dbcapi.service.DmaapService; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +public class ApiPerms extends BaseLoggingClass { + + private static class PermissionMap { + static final EELFLogger logger = EELFManager.getInstance().getLogger( PermissionMap.class ); + static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + String uri; + String action; + String[] roles; + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + + public String[] getRoles() { + return roles; + } + public void setRoles(String[] roles) { + this.roles = roles; + } + + private PermissionMap( String u, String a, String[] r ) { + this.setUri(u); + this.setAction(a); + this.setRoles(r); + } + + static public void initMap( PermissionMap[] pmap, String instance ) { + + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + String api = p.getProperty("ApiNamespace", "apiNamespace.not.set"); + + // this is needed because PE AAF may be a different instance than AAF used by MR + String peEnv = p.getProperty("PeAafEnvironment", "notSet"); + String url = p.getProperty( new String( "PeAafUrl." + peEnv ), "URL.not.set" ); + logger.info( "PeAafEnvironment=" + peEnv + " using URL " + url); + AafService aaf = new AafService(ServiceType.AAF_Admin, url ); + + for ( int i = 0; i < pmap.length ; i++ ) { + String uri = new String( api + "." + pmap[i].getUri()); + DmaapPerm perm = new DmaapPerm( uri, instance, pmap[i].getAction() ); + int rc = aaf.addPerm( perm ); + if ( rc != 201 && rc != 409 ) { + errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "add perm", perm.toString() ); + + } + for( String r: pmap[i].getRoles()) { + String fr = new String( api + "." + r ); + logger.debug( "i:" + i + " granting perm " + perm.toString()+ " to role=" + fr ); + DmaapGrant grant = new DmaapGrant( perm, fr ); + rc = aaf.addGrant( grant ); + if ( rc != 201 && rc != 409 ) { + errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "grant perm", perm.toString() ); + } + } + + } + } + } + + static PermissionMap[] bootMap = { + new PermissionMap( "dmaap", "GET", new String[] { "Controller" }), + new PermissionMap( "dmaap", "POST", new String[] { "Controller" }), + new PermissionMap( "dmaap", "PUT", new String[] { "Controller" }), + new PermissionMap( "dmaap", "DELETE", new String[] { "Controller" }) + + }; + + static PermissionMap[] envMap = { + new PermissionMap( "dmaap", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "dmaap", "POST", new String[] { "Controller" } ), + new PermissionMap( "dmaap", "PUT", new String[] { "Controller" }), + new PermissionMap( "dmaap", "DELETE", new String[] { "Controller" }), + new PermissionMap( "bridge", "GET", new String[] { "Metrics" }), + //new PermissionMap( "bridge", "POST", new String[] { "Metrics" } ), + //new PermissionMap( "bridge", "PUT", new String[] { "Metrics" }), + //new PermissionMap( "bridge", "DELETE", new String[] { "Metrics" }), + new PermissionMap( "dcaeLocations", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "dcaeLocations", "POST", new String[] { "Controller" } ), + new PermissionMap( "dcaeLocations", "PUT", new String[] { "Controller" }), + new PermissionMap( "dcaeLocations", "DELETE", new String[] { "Controller" }), + new PermissionMap( "dr_nodes", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "PortalUser" }), + new PermissionMap( "dr_nodes", "POST", new String[] { "Controller" } ), + new PermissionMap( "dr_nodes", "PUT", new String[] { "Controller" }), + new PermissionMap( "dr_nodes", "DELETE", new String[] { "Controller" }), + new PermissionMap( "dr_pubs", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "dr_pubs", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), + new PermissionMap( "dr_pubs", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), + new PermissionMap( "dr_pubs", "DELETE", new String[] { "Controller", "Orchestrator","PortalUser" }), + new PermissionMap( "dr_subs", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "dr_subs", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), + new PermissionMap( "dr_subs", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), + new PermissionMap( "dr_subs", "DELETE", new String[] { "Controller", "Orchestrator","PortalUser" }), + new PermissionMap( "feeds", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "feeds", "POST", new String[] { "Controller", "Orchestrator","PortalUser" } ), + new PermissionMap( "feeds", "PUT", new String[] { "Controller", "Orchestrator", "PortalUser" }), + new PermissionMap( "feeds", "DELETE", new String[] { "Controller", "PortalUser" }), + new PermissionMap( "mr_clients", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "mr_clients", "POST", new String[] { "Controller","Orchestrator", "PortalUser" } ), + new PermissionMap( "mr_clients", "PUT", new String[] { "Controller", "Orchestrator","PortalUser" }), + new PermissionMap( "mr_clients", "DELETE", new String[] { "Controller","Orchestrator", "PortalUser" }), + new PermissionMap( "mr_clusters", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "mr_clusters", "POST", new String[] { "Controller" } ), + new PermissionMap( "mr_clusters", "PUT", new String[] { "Controller" }), + new PermissionMap( "mr_clusters", "DELETE", new String[] { "Controller" }), + new PermissionMap( "topics", "GET", new String[] { "Controller", "Orchestrator", "Inventory", "Metrics", "PortalUser" }), + new PermissionMap( "topics", "POST", new String[] { "Controller", "Orchestrator" } ), + new PermissionMap( "topics", "PUT", new String[] { "Controller", "Orchestrator" }), + new PermissionMap( "topics", "DELETE", new String[] { "Controller", "Orchestrator" }) + }; + + public void setBootMap() { + String instance = "boot"; + PermissionMap.initMap( bootMap, instance ); + } + + public void setEnvMap() { + Dmaap dmaap = new DmaapService().getDmaap(); + String dmaap_name = dmaap.getDmaapName(); + PermissionMap.initMap( envMap, dmaap_name ); + } + + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPolicy.java b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPolicy.java new file mode 100644 index 0000000..33d0786 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/authentication/ApiPolicy.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.authentication; + +import org.onap.dmaap.dbcapi.aaf.DmaapPerm; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +public class ApiPolicy extends BaseLoggingClass { + static String allow = "allow"; + String dClass = null; + ApiPermissionInterface perm = null; + + public ApiPolicy() { + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + dClass = p.getProperty( "ApiPermission.Class", allow ); + logger.info( "ApiPolicy implements " + dClass); + if ( dClass.equalsIgnoreCase( allow )) { + return; + } + + try { + perm = (ApiPermissionInterface) (Class.forName(dClass).newInstance()); + } catch (Exception ee ) { + errorLogger.error(DmaapbcLogMessageEnum.UNEXPECTED_CONDITION, "attempting to instantiate " + dClass ); + errorLogger.error( "trace is: " + ee ); + } + } + + public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException { + if ( dClass.equalsIgnoreCase( allow )) { + return; + } + + // execute check of loaded class + perm.check( mechid, pwd, p ); + + } + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/authentication/AuthenticationErrorException.java b/src/main/java/org/onap/dmaap/dbcapi/authentication/AuthenticationErrorException.java new file mode 100644 index 0000000..5119c76 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/authentication/AuthenticationErrorException.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.authentication; + +public class AuthenticationErrorException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/client/DrProvConnection.java b/src/main/java/org/onap/dmaap/dbcapi/client/DrProvConnection.java new file mode 100644 index 0000000..9807fba --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/client/DrProvConnection.java @@ -0,0 +1,813 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.client; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.ProtocolException; +import java.net.SocketException; +import java.net.URL; +import java.util.ArrayList; + +import javax.net.ssl.HttpsURLConnection; + +import org.apache.log4j.Logger; +import org.apache.log4j.PropertyConfigurator; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.DR_Pub; +import org.onap.dmaap.dbcapi.model.DR_Sub; +import org.onap.dmaap.dbcapi.model.Feed; +import org.onap.dmaap.dbcapi.service.DmaapService; +import org.onap.dmaap.dbcapi.util.RandomInteger; + + + +public class DrProvConnection extends BaseLoggingClass { + + + private String provURL; + + private HttpsURLConnection uc; + + + public DrProvConnection() { + provURL = new DmaapService().getDmaap().getDrProvUrl(); + if ( provURL.length() < 1 ) { + errorLogger.error( DmaapbcLogMessageEnum.PREREQ_DMAAP_OBJECT, "getDrProvUrl"); + } + + } + + public boolean makeFeedConnection() { + return makeConnection( provURL ); + } + public boolean makeFeedConnection(String feedId) { + return makeConnection( provURL + "/feed/" + feedId ); + } + public boolean makeSubPostConnection( String subURL ) { + String[] parts = subURL.split("/"); + String revisedURL = provURL + "/" + parts[3] + "/" + parts[4]; + logger.info( "mapping " + subURL + " to " + revisedURL ); + return makeConnection( revisedURL ); + } + public boolean makeSubPutConnection( String subId ) { + String revisedURL = provURL + "/subs/" + subId; + logger.info( "mapping " + subId + " to " + revisedURL ); + return makeConnection( revisedURL ); + } + + public boolean makeIngressConnection( String feed, String user, String subnet, String nodep ) { + String uri = String.format("/internal/route/ingress/?feed=%s&user=%s&subnet=%s&nodepatt=%s", + feed, user, subnet, nodep ); + return makeConnection( provURL + uri ); + } + public boolean makeEgressConnection( String sub, String nodep ) { + String uri = String.format("/internal/route/egress/?sub=%s&node=%s", + sub, nodep ); + return makeConnection( provURL + uri ); + } + public boolean makeNodesConnection( String varName ) { + + String uri = String.format("/internal/api/%s", varName); + return makeConnection( provURL + uri ); + } + + public boolean makeNodesConnection( String varName, String val ) { + + if ( val == null ) { + return false; + } + String cv = val.replaceAll("\\|", "%7C"); + String uri = String.format( "/internal/api/%s?val=%s", varName, cv ); + + return makeConnection( provURL + uri ); + } + + private boolean makeConnection( String pURL ) { + + try { + URL u = new URL( pURL ); + uc = (HttpsURLConnection) u.openConnection(); + uc.setInstanceFollowRedirects(false); + logger.info( "successful connect to " + pURL ); + return(true); + } catch (Exception e) { + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR, pURL, e.getMessage() ); + e.printStackTrace(); + return(false); + } + + } + + public String bodyToString( InputStream is ) { + logger.info( "is=" + is ); + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader( new InputStreamReader(is)); + String line; + try { + while ((line = br.readLine()) != null ) { + sb.append( line ); + } + } catch (IOException ex ) { + errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION, ex.getMessage()); + } + + return sb.toString(); + } + + + public String doPostFeed( Feed postFeed, ApiError err ) { + + byte[] postData = postFeed.getBytes(); + logger.info( "post fields=" + postData.toString() ); + String responsemessage = null; + String responseBody = null; + + try { + logger.info( "uc=" + uc ); + uc.setRequestMethod("POST"); + uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() ); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc == 201 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else { + err.setCode( rc ); + err.setMessage(responsemessage); + } + + } catch (ConnectException ce) { + errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); + err.setCode( 500 ); + err.setMessage("Backend connection refused"); + } catch (SocketException se) { + errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from prov server" ); + err.setCode( 500 ); + err.setMessage( "Unable to read response from DR"); + } catch (Exception e) { + logger.warn("Unable to read response " ); + e.printStackTrace(); + try { + err.setCode( uc.getResponseCode()); + err.setMessage(uc.getResponseMessage()); + } catch (Exception e2) { + err.setCode( 500 ); + err.setMessage("Unable to determine response message"); + } + } + finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return responseBody; + + } + + + // the POST for /internal/route/ingress doesn't return any data, so needs a different function + // the POST for /internal/route/egress doesn't return any data, so needs a different function + public int doXgressPost( ApiError err ) { + + String responsemessage = null; + int rc = -1; + + try { + uc.setRequestMethod("POST"); +// uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); +// uc.setRequestProperty( "charset", "utf-8"); +// uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() ); +// uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); +// uc.setUseCaches(false); +// uc.setDoOutput(true); + OutputStream os = null; + + + try { + uc.connect(); + os = uc.getOutputStream(); + + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + + if (rc < 200 || rc >= 300 ) { + err.setCode( rc ); + err.setMessage(responsemessage); + } + } catch (Exception e) { + System.err.println("Unable to read response " ); + e.printStackTrace(); + } finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + + return rc; + + } + + public String doPostDr_Sub( DR_Sub postSub, ApiError err ) { + logger.info( "entry: doPostDr_Sub() " ); + byte[] postData = postSub.getBytes(); + logger.info( "post fields=" + postData ); + String responsemessage = null; + String responseBody = null; + + try { + + uc.setRequestMethod("POST"); + + uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc == 201 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else { + err.setCode(rc); + err.setMessage(responsemessage); + } + + } catch (Exception e) { + System.err.println("Unable to read response " ); + e.printStackTrace(); + } finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return responseBody; + + } + + + public String doPutFeed(Feed putFeed, ApiError err) { + byte[] postData = putFeed.getBytes(); + logger.info( "post fields=" + postData.toString() ); + String responsemessage = null; + String responseBody = null; + + try { + logger.info( "uc=" + uc ); + uc.setRequestMethod("PUT"); + uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", putFeed.getOwner() ); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc >= 200 && rc < 300 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else if ( rc == 404 ) { + err.setCode( rc ); + err.setFields( "feedid"); + String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?"; + err.setMessage( message ); + errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() ); + + } else { + err.setCode( rc ); + err.setMessage(responsemessage); + } + + } catch (ConnectException ce) { + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); + err.setCode( 500 ); + err.setMessage("Backend connection refused"); + } catch (SocketException se) { + errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" ); + err.setCode( 500 ); + err.setMessage( "Unable to read response from DR"); + } catch (Exception e) { + logger.warn("Unable to read response " ); + e.printStackTrace(); + try { + err.setCode( uc.getResponseCode()); + err.setMessage(uc.getResponseMessage()); + } catch (Exception e2) { + err.setCode( 500 ); + err.setMessage("Unable to determine response message"); + } + } finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return responseBody; + } + public String doPutDr_Sub(DR_Sub postSub, ApiError err) { + logger.info( "entry: doPutDr_Sub() " ); + byte[] postData = postSub.getBytes(); + logger.info( "post fields=" + postData ); + String responsemessage = null; + String responseBody = null; + + try { + + uc.setRequestMethod("PUT"); + + uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc == 200 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else { + err.setCode(rc); + err.setMessage(responsemessage); + } + + } catch (ConnectException ce) { + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); + err.setCode( 500 ); + err.setMessage("Backend connection refused"); + } catch (Exception e) { + System.err.println("Unable to read response " ); + e.printStackTrace(); + } finally { + uc.disconnect(); + } + return responseBody; + + } + + public String doGetNodes( ApiError err ) { + logger.info( "entry: doGetNodes() " ); + //byte[] postData = postSub.getBytes(); + //logger.info( "get fields=" + postData ); + String responsemessage = null; + String responseBody = null; + logger.info( "templog:doGetNodes at 12.10.14.10" ); + + try { + logger.info( "templog:doGetNodes at 12.10.14.11" ); + + uc.setRequestMethod("GET"); + + //uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); + //uc.setRequestProperty( "charset", "utf-8"); + //uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); + //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + //uc.setUseCaches(false); + //uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + logger.info( "templog:doGetNodes at 12.10.14.12" ); + try { + uc.connect(); + logger.info( "templog:doGetNodes at 12.10.14.13" ); + //os = uc.getOutputStream(); + //os.write( postData ); + + } catch (ProtocolException pe) { + logger.info( "templog:doGetNodes at 12.10.14.14" ); + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + logger.info( "templog:doGetNodes at 12.10.14.15" ); + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + logger.info( "templog:doGetNodes at 12.10.14.16" ); + + + if (responsemessage == null) { + logger.info( "templog:doGetNodes at 12.10.14.17" ); + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + logger.info( "templog:doGetNodes at 12.10.14.18" ); + err.setCode(rc); // may not really be an error, but we save rc + if (rc == 200 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + } else { + err.setMessage(responsemessage); + } + + logger.info( "templog:doGetNodes at 12.10.14.19" ); + } catch (ConnectException ce) { + logger.info( "templog:doGetNodes at 12.10.14.20" ); + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); + err.setCode( 500 ); + err.setMessage("Backend connection refused"); + } catch (Exception e) { + logger.info( "templog:doGetNodes at 12.10.14.21" ); + System.err.println("Unable to read response " ); + e.printStackTrace(); + } finally { + logger.info( "templog:doGetNodes at 12.10.14.22" ); + if ( uc != null ) uc.disconnect(); + } + logger.info( "templog:doGetNodes at 12.10.14.23" ); + return responseBody; + + } + public String doPutNodes( ApiError err ) { + logger.info( "entry: doPutNodes() " ); + //byte[] postData = nodeList.getBytes(); + //logger.info( "get fields=" + postData ); + String responsemessage = null; + String responseBody = null; + + try { + + uc.setRequestMethod("PUT"); + + //uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription"); + //uc.setRequestProperty( "charset", "utf-8"); + //uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" ); + //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + //uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + //os = uc.getOutputStream(); + //os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + err.setCode(rc); + if (rc == 200 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else { + + err.setMessage(responsemessage); + } + + } catch (Exception e) { + System.err.println("Unable to read response " + e.getMessage() ); + e.printStackTrace(); + } finally { + if ( uc != null ) { + uc.disconnect(); + } + } + return responseBody; + + } + + public String doDeleteFeed(Feed putFeed, ApiError err) { + //byte[] postData = putFeed.getBytes(); + //logger.info( "post fields=" + postData.toString() ); + String responsemessage = null; + String responseBody = null; + + try { + logger.info( "uc=" + uc ); + uc.setRequestMethod("DELETE"); + uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", putFeed.getOwner() ); + //uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + int rc = -1; + + try { + uc.connect(); + os = uc.getOutputStream(); + //os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc >= 200 && rc < 300 ) { + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + + } else if ( rc == 404 ) { + err.setCode( rc ); + err.setFields( "feedid"); + String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?"; + err.setMessage( message ); + errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() ); + + } else { + err.setCode( rc ); + err.setMessage(responsemessage); + } + + } catch (ConnectException ce) { + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() ); + err.setCode( 500 ); + err.setMessage("Backend connection refused"); + } catch (SocketException se) { + errorLogger.error( DmaapbcLogMessageEnum.SOCKET_EXCEPTION, se.getMessage(), "response from Prov server" ); + err.setCode( 500 ); + err.setMessage( "Unable to read response from DR"); + } catch (Exception e) { + logger.warn("Unable to read response " ); + e.printStackTrace(); + try { + err.setCode( uc.getResponseCode()); + err.setMessage(uc.getResponseMessage()); + } catch (Exception e2) { + err.setCode( 500 ); + err.setMessage("Unable to determine response message"); + } + } finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return responseBody; + } + + /* + public static void main( String[] args ) throws Exception { + PropertyConfigurator.configure("log4j.properties"); + logger.info("Started."); + + RandomInteger ri = new RandomInteger(10000); + //String postJSON = String.format("{\"name\": \"dgl feed %d\", \"version\": \"v1.0\", \"description\": \"dgl feed N for testing\", \"authorization\": { \"classification\": \"unclassified\", \"endpoint_addrs\": [],\"endpoint_ids\": [{\"password\": \"test\",\"id\": \"test\"}]}}", ri.next()) ; + int i = ri.next(); + Feed tst = new Feed( "dgl feed " + i, + "v1.0", + "dgl feed " + i + "for testing", + "TEST", + "unclassified" + ); + ArrayList pubs = new ArrayList(); + pubs.add( new DR_Pub( "centralLocation" ) ); + tst.setPubs(pubs); + + boolean rc; + DrProvConnection context = new DrProvConnection(); + rc = context.makeFeedConnection(); + logger.info( "makeFeedConnection returns " + rc); + ApiError err = new ApiError(); + if ( rc ) { + String tmp = context.doPostFeed( tst, err ); + logger.info( "doPostFeed returns " + tmp); + } + + } + */ + + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/client/MrProvConnection.java b/src/main/java/org/onap/dmaap/dbcapi/client/MrProvConnection.java new file mode 100644 index 0000000..91ed1bb --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/client/MrProvConnection.java @@ -0,0 +1,223 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.client; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.ProtocolException; +import java.net.URL; +import java.net.UnknownHostException; + +import javax.net.ssl.HttpsURLConnection; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; +import org.onap.dmaap.dbcapi.aaf.AafDecrypt; +import org.onap.dmaap.dbcapi.aaf.AafService; +import org.onap.dmaap.dbcapi.aaf.DecryptionInterface; +import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.model.Topic; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +public class MrProvConnection extends BaseLoggingClass{ + + private String provURL; + + private HttpsURLConnection uc; + + + private String topicMgrCred; + + private String getCred( ) { + String mechIdProperty = "aaf.TopicMgrUser"; + String pwdProperty = "aaf.TopicMgrPassword"; + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + logger.info( "templog:getCred: 10"); + + String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" ); + logger.info( "templog:getCred: 20"); + + String pwd = ""; + String encPwd = p.getProperty( pwdProperty, "notSet" ); + logger.info( "templog:getCred: 30"); + + AafDecrypt decryptor = new AafDecrypt(); + logger.info( "templog:getCred: 40"); + pwd = decryptor.decrypt(encPwd); + logger.info( "templog:getCred: 50"); + + return user + ":" + pwd; + + + + } + + + public MrProvConnection( ) { + topicMgrCred = getCred(); + + } + + public boolean makeTopicConnection( MR_Cluster cluster ) { + logger.info( "connect to cluster: " + cluster.getDcaeLocationName()); + + + provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create"; + + return makeConnection( provURL ); + } + + private boolean makeConnection( String pURL ) { + logger.info( "makeConnection to " + pURL ); + + try { + URL u = new URL( pURL ); + uc = (HttpsURLConnection) u.openConnection(); + uc.setInstanceFollowRedirects(false); + logger.info( "open connect to " + pURL ); + return(true); + } catch( UnknownHostException uhe ){ + logger.error( "Caught UnknownHostException for " + pURL); + return(false); + } catch (Exception e) { + logger.error("Unexpected error during openConnection of " + pURL ); + e.printStackTrace(); + return(false); + } + + } + + static String bodyToString( InputStream is ) { + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader( new InputStreamReader(is)); + String line; + try { + while ((line = br.readLine()) != null ) { + sb.append( line ); + } + } catch (IOException ex ) { + errorLogger.error( "IOexception:" + ex); + } + + return sb.toString(); + } + + public String doPostTopic( Topic postTopic, ApiError err ) { + String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes()); + + + String responsemessage = null; + int rc = -1; + + + try { + byte[] postData = postTopic.getBytes(); + logger.info( "post fields=" + postData.toString() ); + uc.setRequestProperty("Authorization", auth); + logger.info( "Authenticating with " + auth ); + uc.setRequestMethod("POST"); + uc.setRequestProperty("Content-Type", "application/json"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } catch ( UnknownHostException uhe ) { + errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , "Unknown Host Exception" , provURL ); + err.setCode(500); + err.setMessage("Unknown Host Exception"); + err.setFields( uc.getURL().getHost()); + return new String( "500: " + uhe.getMessage()); + }catch ( ConnectException ce ) { + errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, "HTTP Connection Exception" ); + err.setCode(500); + err.setMessage("HTTP Connection Exception"); + err.setFields( uc.getURL().getHost()); + return new String( "500: " + ce.getMessage()); + } + rc = uc.getResponseCode(); + logger.info( "http response code:" + rc ); + err.setCode(rc); + responsemessage = uc.getResponseMessage(); + logger.info( "responsemessage=" + responsemessage ); + err.setMessage(responsemessage); + + + if (responsemessage == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + responsemessage = h0.substring(j + 1); + } + } + } + if (rc >= 200 && rc < 300 ) { + String responseBody = null; + responseBody = bodyToString( uc.getInputStream() ); + logger.info( "responseBody=" + responseBody ); + return responseBody; + + } + + } catch (Exception e) { + System.err.println("Unable to read response " ); + e.printStackTrace(); + } + finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return new String( rc +": " + responsemessage ); + + } + + + + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/client/MrTopicConnection.java b/src/main/java/org/onap/dmaap/dbcapi/client/MrTopicConnection.java new file mode 100644 index 0000000..b79b33a --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/client/MrTopicConnection.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.client; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.ProtocolException; +import java.net.URL; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLException; + +import org.apache.commons.codec.binary.Base64; +import org.apache.log4j.Logger; +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.model.ApiError; +import org.onap.dmaap.dbcapi.model.MR_Cluster; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +public class MrTopicConnection extends BaseLoggingClass { + private String topicURL; + + private HttpsURLConnection uc; + + + private String mmProvCred; + private String unit_test; + + + + public MrTopicConnection(String user, String pwd ) { + mmProvCred = new String( user + ":" + pwd ); + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + unit_test = p.getProperty( "UnitTest", "No" ); + } + + public boolean makeTopicConnection( MR_Cluster cluster, String topic, String overrideFqdn ) { + String fqdn = overrideFqdn != null ? overrideFqdn : cluster.getFqdn(); + logger.info( "connect to cluster: " + fqdn + " for topic: " + topic ); + + + topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ; + + return makeConnection( topicURL ); + } + + private boolean makeConnection( String pURL ) { + logger.info( "makeConnection to " + pURL ); + + try { + URL u = new URL( pURL ); + uc = (HttpsURLConnection) u.openConnection(); + uc.setInstanceFollowRedirects(false); + logger.info( "open connection to " + pURL ); + return(true); + } catch (Exception e) { + logger.error("Unexpected error during openConnection of " + pURL ); + e.printStackTrace(); + return(false); + } + + } + + static String bodyToString( InputStream is ) { + StringBuilder sb = new StringBuilder(); + BufferedReader br = new BufferedReader( new InputStreamReader(is)); + String line; + try { + while ((line = br.readLine()) != null ) { + sb.append( line ); + } + } catch (IOException ex ) { + errorLogger.error( "IOexception:" + ex); + } + + return sb.toString(); + } + + public ApiError doPostMessage( String postMessage ) { + ApiError response = new ApiError(); + String auth = "Basic " + Base64.encodeBase64String(mmProvCred.getBytes()); + + + + try { + byte[] postData = postMessage.getBytes(); + logger.info( "post fields=" + postMessage ); + uc.setRequestProperty("Authorization", auth); + logger.info( "Authenticating with " + auth ); + uc.setRequestMethod("POST"); + uc.setRequestProperty("Content-Type", "application/json"); + uc.setRequestProperty( "charset", "utf-8"); + uc.setRequestProperty( "Content-Length", Integer.toString( postData.length )); + uc.setUseCaches(false); + uc.setDoOutput(true); + OutputStream os = null; + + + try { + uc.connect(); + os = uc.getOutputStream(); + os.write( postData ); + + } catch (ProtocolException pe) { + // Rcvd error instead of 100-Continue + try { + // work around glitch in Java 1.7.0.21 and likely others + // without this, Java will connect multiple times to the server to run the same request + uc.setDoOutput(false); + } catch (Exception e) { + } + } catch ( SSLException se ) { + response.setCode(500); + response.setMessage( se.getMessage()); + return response; + + } + response.setCode( uc.getResponseCode()); + logger.info( "http response code:" + response.getCode()); + response.setMessage( uc.getResponseMessage() ); + logger.info( "response message=" + response.getMessage() ); + + + if ( response.getMessage() == null) { + // work around for glitch in Java 1.7.0.21 and likely others + // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is + String h0 = uc.getHeaderField(0); + if (h0 != null) { + int i = h0.indexOf(' '); + int j = h0.indexOf(' ', i + 1); + if (i != -1 && j != -1) { + response.setMessage( h0.substring(j + 1) ); + } + } + } + if ( response.is2xx() ) { + response.setFields( bodyToString( uc.getInputStream() ) ); + logger.info( "responseBody=" + response.getFields() ); + return response; + + } + + } catch (Exception e) { + if ( unit_test.equals( "Yes" ) ) { + response.setCode(200); + response.setMessage( "simulated response"); + logger.info( "artificial 200 response from doPostMessage because unit_test =" + unit_test ); + } else { + + response.setCode(500); + response.setMessage( "Unable to read response"); + logger.warn( response.getMessage() ); + e.printStackTrace(); + } + } + finally { + try { + uc.disconnect(); + } catch ( Exception e ) {} + } + return response; + + } + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/ConnWrapper.java b/src/main/java/org/onap/dmaap/dbcapi/database/ConnWrapper.java new file mode 100644 index 0000000..e0c7819 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/ConnWrapper.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.sql.*; + + +public abstract class ConnWrapper { + protected Connection c; + protected PreparedStatement ps; + protected ResultSet rs; + protected abstract T run(U u) throws Exception; + public T protect(ConnectionFactory cf, U u) throws DBException { + try { + try { + return(attempt(cf, u, false)); + } catch (SQLException sqle) { + return(attempt(cf, u, true)); + } + } catch (RuntimeException rte) { + throw rte; + } catch (Exception e) { + throw new DBException(e); + } + } + private T attempt(ConnectionFactory cf, U u, boolean fresh) throws Exception { + c = null; + ps = null; + rs = null; + try { + c = cf.get(fresh); + T ret = run(u); + cf.release(c); + c = null; + return(ret); + } finally { + if (rs != null) { try { rs.close(); } catch (Exception e) {}} + rs = null; + if (ps != null) { try { ps.close(); } catch (Exception e) {}} + ps = null; + if (c != null) { try { c.close(); } catch (Exception e) {}} + c = null; + } + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/ConnectionFactory.java b/src/main/java/org/onap/dmaap/dbcapi/database/ConnectionFactory.java new file mode 100644 index 0000000..1d93d68 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/ConnectionFactory.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.sql.*; +import java.util.*; + +import org.apache.log4j.Logger; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.util.DmaapConfig; + +public class ConnectionFactory { + static final EELFLogger logger = EELFManager.getInstance().getLogger( ConnectionFactory.class ); + static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger(); + static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + static final EELFLogger serverLogger = EELFManager.getInstance().getServerLogger(); + + static { + try { + Class.forName("org.postgresql.Driver"); + } catch (Exception e) { + logger.error("Unable to load postgres driver " + e, e); + } + } + private static ConnectionFactory instance = new ConnectionFactory(); + private String host; + private String dbname; + private String dbuser; + private String dbcr; + public ConnectionFactory() { + Properties p = DmaapConfig.getConfig(); + host = p.getProperty("DB.host", "dcae-pstg-write-ftl.domain.notset.com"); + dbname = p.getProperty("DB.name", "dmaap"); + dbuser = p.getProperty("DB.user", "dmaap_admin"); + dbcr = p.getProperty("DB.cred", "test234-ftl"); + } + public static ConnectionFactory getDefaultInstance() { + return(instance); + } + private Connection[] pool = new Connection[5]; + private int cur; + public Connection get(boolean fresh) throws SQLException { + if (!fresh) { + synchronized(this) { + if (cur > 0) { + return(pool[--cur]); + } + } + } + Properties p = new Properties(); + p.put("user", dbuser); + p.put("password", dbcr); + return(DriverManager.getConnection("jdbc:postgresql://" + host + "/" + dbname, p)); + } + public void release(Connection c) { + synchronized(this) { + if (cur < pool.length) { + pool[cur++] = c; + return; + } + } + try { c.close(); } catch (Exception e) {} + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DBException.java b/src/main/java/org/onap/dmaap/dbcapi/database/DBException.java new file mode 100644 index 0000000..6538167 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DBException.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; + +public class DBException extends RuntimeException { + static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + public DBException(Exception e) { + super(e); + errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_ERROR, e.getMessage()); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DBFieldHandler.java b/src/main/java/org/onap/dmaap/dbcapi/database/DBFieldHandler.java new file mode 100644 index 0000000..072c548 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DBFieldHandler.java @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.lang.reflect.*; +import java.sql.*; +import java.util.*; + +import org.apache.log4j.Logger; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; + + +public class DBFieldHandler { + static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + + public static interface SqlOp { + public Object get(ResultSet rs, int index) throws Exception; + public void set(PreparedStatement ps, int index, Object value) throws Exception; + } + private static class AofString implements SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + String val = rs.getString(index); + if (val == null) { + return(null); + } + String[] ret = val.split(","); + for (int i = 0; i < ret.length; i++) { + ret[i] = funesc(ret[i]); + } + return(ret); + } + public void set(PreparedStatement ps, int index, Object x) throws Exception { + String[] val = (String[])x; + if (val == null) { + ps.setString(index, null); + return; + } + StringBuffer sb = new StringBuffer(); + String sep = ""; + for (String s: val) { + sb.append(sep).append(fesc(s)); + sep = ","; + } + ps.setString(index, sb.toString()); + } + } + private static class EnumSql implements SqlOp { + private Class enclass; + public EnumSql(Class enclass) { + this.enclass = enclass; + } + @SuppressWarnings("unchecked") + public Object get(ResultSet rs, int index) throws Exception { + String val = rs.getString(index); + if (val == null) { + return(null); + } else { + return(Enum.valueOf(enclass, val)); + } + } + public void set(PreparedStatement ps, int index, Object value) throws Exception { + if (value == null) { + ps.setString(index, null); + } else { + ps.setString(index, value.toString()); + } + } + } + private static class SqlDate implements SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + return(rs.getTimestamp(index)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val instanceof java.util.Date && !(val instanceof java.sql.Timestamp)) { + val = new java.sql.Timestamp(((java.util.Date)val).getTime()); + } + ps.setTimestamp(index, (java.sql.Timestamp)val); + } + } + private static class SqlType implements SqlOp { + private Method sqlget; + private Method sqlset; + private SqlType(String tag) throws Exception { + sqlget = ResultSet.class.getMethod("get" + tag, Integer.TYPE); + sqlset = PreparedStatement.class.getMethod("set" + tag, Integer.TYPE, sqlget.getReturnType()); + sqltypes.put(sqlget.getReturnType().getName(), this); + } + public Object get(ResultSet rs, int index) throws Exception { + return(sqlget.invoke(rs, index)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + try { + sqlset.invoke(ps, index, val); + } catch (Exception e) { + errorLogger.error(DmaapbcLogMessageEnum.DB_FIELD_INIT_ERROR, Integer.toString(index), val.toString(), ps.toString()); + throw e; + } + } + } + private static Map sqltypes; + static { + sqltypes = new HashMap(); + sqltypes.put("[Ljava.lang.String;", new AofString()); + sqltypes.put("java.util.Date", new SqlDate()); + try { + new SqlType("Boolean"); + new SqlType("Timestamp"); + new SqlType("Double"); + new SqlType("Float"); + new SqlType("Int"); + new SqlType("Long"); + new SqlType("Short"); + new SqlType("String"); + } catch (Exception e) { + errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_INIT_ERROR, e.getMessage() ); + } + } + private Method objget; + private Method objset; + private SqlOp sqlop; + private int fieldnum; + public void copy(Object from, Object to) throws Exception { + objset.invoke(to, objget.invoke(from)); + } + public void setKey(Object o, String key) throws Exception { + objset.invoke(o, key); + } + public String getKey(Object o) throws Exception { + return((String)objget.invoke(o)); + } + public void toSQL(Object o, PreparedStatement ps) throws Exception { + sqlop.set(ps, fieldnum, objget.invoke(o)); + } + public void fromSQL(ResultSet r, Object o) throws Exception { + objset.invoke(o, sqlop.get(r, fieldnum)); + } + public DBFieldHandler(Class c, String fieldname, int fieldnum) throws Exception { + this(c, fieldname, fieldnum, null); + } + public DBFieldHandler(Class c, String fieldname, int fieldnum, SqlOp op) throws Exception { + this.fieldnum = fieldnum; + StringBuffer sb = new StringBuffer(); + for (String s: fieldname.split("_")) { + sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1)); + } + String camelcase = sb.toString(); + try { + objget = c.getMethod("is" + camelcase); + } catch (Exception e) { + objget = c.getMethod("get" + camelcase); + } + objset = c.getMethod("set" + camelcase, objget.getReturnType()); + sqlop = op; + if (sqlop != null) { + return; + } + Class x = objget.getReturnType(); + if (x.isEnum()) { + sqlop = new EnumSql(x); + return; + } + sqlop = sqltypes.get(x.getName()); + if (sqlop != null) { + return; + } + errorLogger.error(DmaapbcLogMessageEnum.DB_NO_FIELD_HANDLER, c.getName(), fieldname, Integer.toString(fieldnum), x.getName()); + } + public static String fesc(String s) { + if (s == null) { + return(s); + } + return(s.replaceAll("@", "@a").replaceAll(";", "@s").replaceAll(",", "@c")); + } + public static String funesc(String s) { + if (s == null) { + return(s); + } + return(s.replaceAll("@c", ",").replaceAll("@s", ";").replaceAll("@a", "@")); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DBMap.java b/src/main/java/org/onap/dmaap/dbcapi/database/DBMap.java new file mode 100644 index 0000000..a9bf56e --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DBMap.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.sql.*; +import java.util.*; + +public class DBMap extends TableHandler implements Map { + public DBMap(Class cls, String tabname, String keyfield) throws Exception { + this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyfield); + } + public DBMap(ConnectionFactory cf, Class cls, String tabname, String keyfield) throws Exception { + super(cf, cls, tabname, keyfield); + } + public void clear() throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + public boolean containsKey(Object key) throws DBException { + return(get(key) != null); + } + public boolean containsValue(Object value) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + public boolean isEmpty() { + return(false); + } + public Set> entrySet() throws DBException { + return(list()); + } + public Set keySet() throws DBException { + Set ret = new HashSet(); + for (Map.Entry x: list()) { + ret.add(x.getKey()); + } + return(ret); + } + public void putAll(Map m) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + public int size() { + return(2); + } + public Collection values() throws DBException { + Collection ret = new Vector(); + for (Map.Entry x: list()) { + ret.add(x.getValue()); + } + return(ret); + } + public C get(Object key) throws DBException { + if (!(key instanceof String)) { + return(null); + } + return((new ConnWrapper() { + protected C run(String key) throws Exception { + ps = c.prepareStatement(getstmt); + ps.setString(1, (String)key); + rs = ps.executeQuery(); + if (!rs.next()) { + return(null); + } + C ret = cls.newInstance(); + for (DBFieldHandler f: fields) { + f.fromSQL(rs, ret); + } + return(ret); + } + }).protect(cf, (String)key)); + } + public Set> list() throws DBException { + return((new ConnWrapper>, Object>() { + protected Set> run(Object junk) throws Exception { + DBFieldHandler keyfield = fields[fields.length - 1]; + ps = c.prepareStatement(liststmt); + rs = ps.executeQuery(); + Set> ret = new HashSet>(); + while (rs.next()) { + C val = cls.newInstance(); + for (DBFieldHandler f: fields) { + f.fromSQL(rs, val); + } + String key = keyfield.getKey(val); + ret.add(new AbstractMap.SimpleEntry(key, val)); + } + return(ret); + } + }).protect(cf, null)); + } + public C put(String key, C val) throws DBException { + try { + fields[fields.length - 1].setKey(val, key); + } catch (Exception e) { + throw new DBException(e); + } + PreparedStatement ps = null; + return((new ConnWrapper() { + protected C run(C val) throws Exception { + ps = c.prepareStatement(insorreplstmt); + for (DBFieldHandler f: fields) { + f.toSQL(val, ps); + } + ps.executeUpdate(); + return(null); + } + }).protect(cf, val)); + } + public C remove(Object key) throws DBException { + if (!(key instanceof String)) { + return(null); + } + return((new ConnWrapper() { + protected C run(String key) throws Exception { + ps = c.prepareStatement(delstmt); + ps.setString(1, key); + ps.executeUpdate(); + return(null); + } + }).protect(cf, (String)key)); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DBSingleton.java b/src/main/java/org/onap/dmaap/dbcapi/database/DBSingleton.java new file mode 100644 index 0000000..9a34f58 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DBSingleton.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.sql.*; +import java.util.*; + +import org.onap.dmaap.dbcapi.util.Singleton; + +public class DBSingleton extends TableHandler implements Singleton { + private C singleton; + public DBSingleton(Class cls, String tabname) throws Exception { + this(ConnectionFactory.getDefaultInstance(), cls, tabname); + } + public DBSingleton(ConnectionFactory cf, Class cls, String tabname) throws Exception { + super(cf, cls, tabname, null); + singleton = cls.newInstance(); + } + public C get() throws DBException { + return((new ConnWrapper() { + protected C run(Object junk) throws Exception { + ps = c.prepareStatement(getstmt); + rs = ps.executeQuery(); + if (!rs.next()) { + return(null); + } + for (DBFieldHandler f: fields) { + f.fromSQL(rs, singleton); + } + return(singleton); + } + }).protect(cf, null)); + } + public void init(C val) throws DBException { + if (get() != null) { + return; + } + (new ConnWrapper() { + protected Void run(C val) throws Exception { + ps = c.prepareStatement(initstmt); + for (DBFieldHandler f: fields) { + f.toSQL(val, ps); + } + ps.executeUpdate(); + if (val != singleton) { + for (DBFieldHandler f: fields) { + f.copy(val, singleton); + } + } + return(null); + } + }).protect(cf, val); + } + public void update(C val) throws DBException { + (new ConnWrapper() { + protected Void run(C val) throws Exception { + ps = c.prepareStatement(insorreplstmt); + for (DBFieldHandler f: fields) { + f.toSQL(val, ps); + } + ps.executeUpdate(); + if (val != singleton) { + for (DBFieldHandler f: fields) { + f.copy(val, singleton); + } + } + return(null); + } + }).protect(cf, val); + } + public void remove() throws DBException { + (new ConnWrapper() { + protected Void run(Object junk) throws Exception { + ps = c.prepareStatement(delstmt); + ps.executeUpdate(); + return(null); + } + }).protect(cf, null); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java b/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java new file mode 100644 index 0000000..9b7c8ff --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/DatabaseClass.java @@ -0,0 +1,270 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.util.*; +import java.sql.*; + +import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.util.DmaapConfig; +import org.onap.dmaap.dbcapi.util.Singleton; + + + + +public class DatabaseClass extends BaseLoggingClass { + + private static Singleton dmaap; + private static Map dcaeLocations; + private static Map dr_nodes; + private static Map dr_pubs; + private static Map dr_subs; + private static Map mr_clients; + private static Map mr_clusters; + private static Map feeds; + private static Map topics; + private static Map mirrors; + + private static long lastTime = 0L; + + private static class MirrorVectorHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + String val = rs.getString(index); + if (val == null) { + return(null); + } + Set rv = new HashSet(); + for (String s: val.split(",")) { + String[] f = s.split(";"); + if (f.length < 3) { + continue; + } + rv.add(new ReplicationVector(DBFieldHandler.funesc(f[0]), DBFieldHandler.funesc(f[1]), DBFieldHandler.funesc(f[2]))); + } + return(rv); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setString(index, null); + return; + } + Set xv = (Set)val; + StringBuffer sb = new StringBuffer(); + String sep = ""; + for (Object o: xv) { + ReplicationVector rv = (ReplicationVector)o; + sb.append(sep).append(DBFieldHandler.fesc(rv.getFqtn())).append(';').append(DBFieldHandler.fesc(rv.getSourceCluster())).append(';').append(DBFieldHandler.fesc(rv.getTargetCluster())); + sep = ","; + } + ps.setString(index, sb.toString()); + } + } + + // modified version of MirrorVectorHandler for Topics + private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + String val = rs.getString(index); + if (val == null) { + return(null); + } + List rv = new ArrayList(); + for (String s: val.split(",")) { + //String[] f = s.split(";"); + //if (f.length < 3) { + // continue; + //} + rv.add(new String(s)); + } + return(rv); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setString(index, null); + return; + } + @SuppressWarnings("unchecked") + List xv = (List)val; + StringBuffer sb = new StringBuffer(); + String sep = ""; + for (Object o: xv) { + String rv = (String)o; + sb.append(sep).append(DBFieldHandler.fesc(rv)); + sep = ","; + } + ps.setString(index, sb.toString()); + } + } + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + public static Singleton getDmaap() { + return dmaap; + } + + + + public static Map getDcaeLocations() { + return dcaeLocations; + } + + public static Map getDr_nodes() { + return dr_nodes; + } + + public static Map getDr_subs() { + return dr_subs; + } + public static Map getDr_pubs() { + return dr_pubs; + } + + public static Map getMr_clients() { + return mr_clients; + } + + + public static Map getMr_clusters() { + return mr_clusters; + } + + public static Map getFeeds() { + return feeds; + } + public static Map getTopics() { + return topics; + } + public static Map getMirrorMakers() { + return mirrors; + } + + static { + try { + appLogger.info( "begin static initialization"); + appLogger.info( "initializing dmaap" ); + DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig(); + if ("true".equalsIgnoreCase(p.getProperty("UsePGSQL", "false"))) { + appLogger.info("Data from database"); + try { + LoadSchema.upgrade(); + } catch (Exception e) { + appLogger.warn("Problem updating DB schema", e); + } + try { + dmaap = new DBSingleton(Dmaap.class, "dmaap"); + dcaeLocations = new DBMap(DcaeLocation.class, "dcae_location", "dcae_location_name"); + dr_nodes = new DBMap(DR_Node.class, "dr_node", "fqdn"); + dr_pubs = new DBMap(DR_Pub.class, "dr_pub", "pub_id"); + dr_subs = new DBMap(DR_Sub.class, "dr_sub", "sub_id"); + mr_clients = new DBMap(MR_Client.class, "mr_client", "mr_client_id"); + mr_clusters = new DBMap(MR_Cluster.class, "mr_cluster", "dcae_location_name"); + feeds = new DBMap(Feed.class, "feed", "feed_id"); + TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); + topics = new DBMap(Topic.class, "topic", "fqtn"); + //TableHandler.setSpecialCase("mirror_maker", "vectors", new MirrorVectorHandler()); + TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler()); + mirrors = new DBMap(MirrorMaker.class, "mirror_maker", "mm_name"); + } catch (Exception e) { + errorLogger.error("Error initializing database access " + e, e); + System.exit(1); + } + } else { + appLogger.info("Data from memory"); + dmaap = new Singleton() { + private Dmaap dmaap; + public void remove() { + dmaap = null; + } + public void init(Dmaap val) { + if (dmaap == null) { + dmaap = val; + } + } + public Dmaap get() { + return(dmaap); + } + public void update(Dmaap nd) { + dmaap.setVersion(nd.getVersion()); + dmaap.setTopicNsRoot(nd.getTopicNsRoot()); + dmaap.setDmaapName(nd.getDmaapName()); + dmaap.setDrProvUrl(nd.getDrProvUrl()); + dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic()); + dmaap.setLoggingUrl(nd.getLoggingUrl()); + dmaap.setNodeKey(nd.getNodeKey()); + dmaap.setAccessKeyOwner(nd.getAccessKeyOwner()); + } + }; + dcaeLocations = new HashMap(); + dr_nodes = new HashMap(); + dr_pubs = new HashMap(); + dr_subs = new HashMap(); + mr_clients = new HashMap(); + mr_clusters = new HashMap(); + feeds = new HashMap(); + topics = new HashMap(); + mirrors = new HashMap(); + } + dmaap.init(new Dmaap("0", "", "", "", "", "", "", "")); + // check for, and set up initial data, if it isn't already there + Dmaap dmx = dmaap.get(); + if ("0".equals(dmx.getVersion())) { + + dmx = new Dmaap("0", "", "", "", "", "", "", ""); + dmx.setDmaapName(p.getProperty("DmaapName")); + dmx.setDrProvUrl("https://" + p.getProperty("DR.provhost", "notSet")); + dmx.setTopicNsRoot(p.getProperty("topicNsRoot")); + dmx.setBridgeAdminTopic("DCAE_MM_AGENT"); + + dmaap.update(dmx); + } + } catch (Exception e) { + errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage()); + } + } + + public synchronized static String getNextClientId() { + + long id = System.currentTimeMillis(); + if ( id <= lastTime ) { + id = lastTime + 1; + } + lastTime = id; + return Long.toString(id); + } + + + + +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/LoadSchema.java b/src/main/java/org/onap/dmaap/dbcapi/database/LoadSchema.java new file mode 100644 index 0000000..6e64c4a --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/LoadSchema.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.io.*; +import java.sql.*; + +import org.apache.log4j.Logger; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; + +public class LoadSchema { + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoadSchema.class); + private static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger(); + private static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger(); + private static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger(); + private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + + static int getVer(Statement s) throws SQLException { + ResultSet rs = null; + try { + rs = s.executeQuery("SELECT version FROM dmaapbc_sch_ver"); + rs.next(); + return(rs.getInt(1)); + } finally { + if (rs != null) { + rs.close(); + } + } + } + static void upgrade() throws SQLException { + ConnectionFactory cf = ConnectionFactory.getDefaultInstance(); + Connection c = null; + Statement stmt = null; + InputStream is = null; + try { + c = cf.get(true); + stmt = c.createStatement(); + int newver = -1; + try { + newver = getVer(stmt); + } catch (Exception e) {} + logger.info("Database schema currently at version " + newver++); + while ((is = LoadSchema.class.getClassLoader().getResourceAsStream("schema_" + newver + ".sql")) != null) { + logger.info("Upgrading database schema to version " + newver); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + String s; + String sofar = null; + while ((s = br.readLine()) != null) { + logger.info("SCHEMA: " + s); + s = s.trim(); + if (s.length() == 0 || s.startsWith("--")) { + continue; + } + if (sofar == null) { + sofar = s; + } else { + sofar = sofar + " " + s; + } + if (s.endsWith(";")) { + sofar = sofar.substring(0, sofar.length() - 1); + boolean ignore = false; + if (sofar.startsWith("@")) { + ignore = true; + sofar = sofar.substring(1).trim(); + } + try { + stmt.execute(sofar); + } catch (SQLException sqle) { + if (!ignore) { + throw sqle; + } + } + sofar = null; + } + } + is.close(); + is = null; + if (getVer(stmt) != newver) { + throw new SQLException("Schema version not properly updated to " + newver + " by upgrade script"); + } + logger.info("Upgrade to database schema version " + newver + " successful"); + newver++; + } + } catch (IOException ioe) { + throw new SQLException(ioe); + } finally { + if (stmt != null) { try { stmt.close(); } catch (Exception e) {}} + if (c != null) { try { c.close(); } catch (Exception e) {}} + } + } + public static void main(String[] args) throws Exception { + upgrade(); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/database/TableHandler.java b/src/main/java/org/onap/dmaap/dbcapi/database/TableHandler.java new file mode 100644 index 0000000..b43edc5 --- /dev/null +++ b/src/main/java/org/onap/dmaap/dbcapi/database/TableHandler.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dmaap.dbcapi.database; + +import java.util.*; +import java.lang.reflect.*; +import java.sql.*; + +class TableHandler { + protected ConnectionFactory cf; + protected boolean haskey; + protected String delstmt; + protected String insorreplstmt; + protected String getstmt; + protected String liststmt; + protected String initstmt; + protected Class cls; + protected DBFieldHandler[] fields; + private static Map> exceptions = new HashMap>(); + public static void setSpecialCase(String dbtabname, String dbfldname, DBFieldHandler.SqlOp handler) { + Map m = exceptions.get(dbtabname); + if (m == null) { + m = new HashMap(); + exceptions.put(dbtabname, m); + } + m.put(dbfldname, handler); + } + public static DBFieldHandler.SqlOp getSpecialCase(String dbtabname, String dbfldname) { + Map m = exceptions.get(dbtabname); + if (m != null) { + return(m.get(dbfldname)); + } + return(null); + } + protected TableHandler(Class cls, String tabname, String keyname) throws Exception { + this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyname); + } + protected TableHandler(ConnectionFactory cf, Class cls, String tabname, String keyname) throws Exception { + this.cf = cf; + Connection c = null; + try { + c = cf.get(false); + setup(c.getMetaData(), cls, tabname, keyname); + } finally { + if (c != null) { + cf.release(c); + } + } + } + private void setup(DatabaseMetaData dmd, Class cls, String tabname, String keyname) throws Exception { + this.cls = cls; + Vector h = new Vector(); + ResultSet rs = dmd.getColumns("", "public", tabname, null); + StringBuffer sb1 = new StringBuffer(); + StringBuffer sb2 = new StringBuffer(); + StringBuffer sb3 = new StringBuffer(); + int count = 0; + while (rs.next()) { + if (!rs.getString(3).equals(tabname)) { + continue; + } + String cname = rs.getString(4); + if (cname.equals(keyname)) { + haskey = true; + continue; + } + sb1.append(", ").append(cname); + sb2.append(", ?"); + sb3.append(", EXCLUDED.").append(cname); + count++; + h.add(new DBFieldHandler(cls, cname, count, getSpecialCase(tabname, cname))); + } + if (count == 0) { + throw new SQLException("Table " + tabname + " not found"); + } + String clist = sb1.substring(2); + String qlist = sb2.substring(2); + String elist = sb3.substring(2); + if (keyname != null && !haskey) { + throw new SQLException("Table " + tabname + " does not have key column " + keyname + " not found"); + } + if (haskey) { + count++; + h.add(new DBFieldHandler(cls, keyname, count, getSpecialCase(tabname, keyname))); + delstmt = "DELETE FROM " + tabname + " WHERE " + keyname + " = ?"; + insorreplstmt = "INSERT INTO " + tabname + " (" + clist + ", " + keyname + ") VALUES (" + qlist + ", ?) ON CONFLICT(" + keyname + ") DO UPDATE SET (" + clist + ") = (" + elist + ")"; + getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname + " WHERE " + keyname + " = ?"; + liststmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname; + } else { + delstmt = "DELETE FROM " + tabname; + initstmt = "INSERT INTO " + tabname + " (" + clist + ") VALUES (" + qlist + ")"; + insorreplstmt = "UPDATE " + tabname + " SET (" + clist + ") = (" + qlist + ")"; + getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname; + } + fields = h.toArray(new DBFieldHandler[h.size()]); + } +} diff --git a/src/main/java/org/onap/dmaap/dbcapi/model/MR_Client.java b/src/main/java/org/onap/dmaap/dbcapi/model/MR_Client.java index dc43cc0..580800c 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/model/MR_Client.java +++ b/src/main/java/org/onap/dmaap/dbcapi/model/MR_Client.java @@ -24,10 +24,7 @@ import java.util.Date; import javax.xml.bind.annotation.XmlRootElement; - - - -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.database.DatabaseClass; @XmlRootElement public class MR_Client extends DmaapObject { diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/AuthorizationFilter.java b/src/main/java/org/onap/dmaap/dbcapi/resources/AuthorizationFilter.java index d990b09..ab0e262 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/resources/AuthorizationFilter.java +++ b/src/main/java/org/onap/dmaap/dbcapi/resources/AuthorizationFilter.java @@ -25,7 +25,7 @@ import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.service.ApiService; import org.onap.dmaap.dbcapi.util.DmaapConfig; diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/BridgeResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/BridgeResource.java index 4796217..1a6310c 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/resources/BridgeResource.java +++ b/src/main/java/org/onap/dmaap/dbcapi/resources/BridgeResource.java @@ -40,7 +40,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Response.Status; -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java b/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java index 417b18a..eead1de 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java +++ b/src/main/java/org/onap/dmaap/dbcapi/resources/FeedResource.java @@ -46,26 +46,7 @@ import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import org.apache.log4j.Logger; - - - - - - - - - - - - - - - - - - - -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/server/JettyServer.java b/src/main/java/org/onap/dmaap/dbcapi/server/JettyServer.java index c0699d5..519fa4a 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/server/JettyServer.java +++ b/src/main/java/org/onap/dmaap/dbcapi/server/JettyServer.java @@ -45,7 +45,7 @@ import org.eclipse.jetty.util.ssl.SslContextFactory; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import org.onap.dmaap.dbcapi.aaf.database.LoadSchema; +import org.onap.dmaap.dbcapi.database.LoadSchema; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; /** * A Jetty server which supports: diff --git a/src/main/java/org/onap/dmaap/dbcapi/server/Main.java b/src/main/java/org/onap/dmaap/dbcapi/server/Main.java index 1ada428..c3340e6 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/server/Main.java +++ b/src/main/java/org/onap/dmaap/dbcapi/server/Main.java @@ -23,8 +23,8 @@ import java.net.InetAddress; import java.util.Properties; import java.util.UUID; -import org.onap.dmaap.dbcapi.aaf.authentication.ApiPerms; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.authentication.ApiPerms; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.*; import org.onap.dmaap.dbcapi.model.Dmaap; import org.onap.dmaap.dbcapi.util.DmaapConfig; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java b/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java index aab989d..e708043 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/ApiService.java @@ -41,8 +41,8 @@ import javax.ws.rs.core.Response.Status; import javax.xml.bind.DatatypeConverter; import org.onap.dmaap.dbcapi.aaf.DmaapPerm; -import org.onap.dmaap.dbcapi.aaf.authentication.ApiPolicy; -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; +import org.onap.dmaap.dbcapi.authentication.ApiPolicy; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.model.ApiError; import org.onap.dmaap.dbcapi.model.Dmaap; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DR_NodeService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DR_NodeService.java index b6d62a2..cf8c7c1 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DR_NodeService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DR_NodeService.java @@ -27,8 +27,8 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; -import org.onap.dmaap.dbcapi.aaf.client.DrProvConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.DrProvConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.model.ApiError; import org.onap.dmaap.dbcapi.model.DR_Node; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DR_PubService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DR_PubService.java index ca60b8a..13717da 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DR_PubService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DR_PubService.java @@ -27,8 +27,8 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; -import org.onap.dmaap.dbcapi.aaf.client.DrProvConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.DrProvConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java index c3f8c9c..0fe1d9e 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DR_SubService.java @@ -26,8 +26,8 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; -import org.onap.dmaap.dbcapi.aaf.client.DrProvConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.DrProvConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DcaeLocationService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DcaeLocationService.java index 23d44d1..de72ade 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DcaeLocationService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DcaeLocationService.java @@ -24,17 +24,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; - - - - - - - - - - -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.model.DcaeLocation; import org.onap.dmaap.dbcapi.model.DmaapObject.DmaapObject_Status; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/DmaapService.java b/src/main/java/org/onap/dmaap/dbcapi/service/DmaapService.java index 6f1294a..03410f3 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/DmaapService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/DmaapService.java @@ -35,8 +35,8 @@ import org.onap.dmaap.dbcapi.aaf.AafService; import org.onap.dmaap.dbcapi.aaf.DmaapGrant; import org.onap.dmaap.dbcapi.aaf.DmaapPerm; import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; -import org.onap.dmaap.dbcapi.aaf.authentication.ApiPerms; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.authentication.ApiPerms; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/FeedService.java b/src/main/java/org/onap/dmaap/dbcapi/service/FeedService.java index 5f1cfb8..8332a35 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/FeedService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/FeedService.java @@ -29,8 +29,8 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; import org.apache.log4j.Logger; -import org.onap.dmaap.dbcapi.aaf.client.DrProvConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.DrProvConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.model.ApiError; import org.onap.dmaap.dbcapi.model.DR_Pub; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClientService.java b/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClientService.java index 68b340f..40f86b6 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClientService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClientService.java @@ -38,8 +38,8 @@ import org.onap.dmaap.dbcapi.aaf.AafService; import org.onap.dmaap.dbcapi.aaf.DmaapGrant; import org.onap.dmaap.dbcapi.aaf.DmaapPerm; import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; -import org.onap.dmaap.dbcapi.aaf.client.MrProvConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.MrProvConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.model.ApiError; import org.onap.dmaap.dbcapi.model.DcaeLocation; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClusterService.java b/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClusterService.java index d8eb91d..529723e 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClusterService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/MR_ClusterService.java @@ -26,13 +26,7 @@ import java.util.Map; import javax.ws.rs.core.Response.Status; - - - - - - -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.model.ApiError; import org.onap.dmaap.dbcapi.model.DcaeLocation; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/MirrorMakerService.java b/src/main/java/org/onap/dmaap/dbcapi/service/MirrorMakerService.java index 6701328..29010b6 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/MirrorMakerService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/MirrorMakerService.java @@ -34,8 +34,8 @@ import java.util.Map; //import org.openecomp.dmaapbc.aaf.AndrewDecryptor; import org.onap.dmaap.dbcapi.aaf.AafDecrypt; -import org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.client.MrTopicConnection; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/service/TopicService.java b/src/main/java/org/onap/dmaap/dbcapi/service/TopicService.java index 7082b9b..d3c849c 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/service/TopicService.java +++ b/src/main/java/org/onap/dmaap/dbcapi/service/TopicService.java @@ -31,7 +31,7 @@ import javax.ws.rs.core.Response.Status; import org.onap.dmaap.dbcapi.aaf.AafService; import org.onap.dmaap.dbcapi.aaf.DmaapPerm; import org.onap.dmaap.dbcapi.aaf.AafService.ServiceType; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.logging.BaseLoggingClass; import org.onap.dmaap.dbcapi.logging.DmaapbcLogMessageEnum; import org.onap.dmaap.dbcapi.model.ApiError; diff --git a/src/main/java/org/onap/dmaap/dbcapi/util/Graph.java b/src/main/java/org/onap/dmaap/dbcapi/util/Graph.java index 5c57ebc..f86569d 100644 --- a/src/main/java/org/onap/dmaap/dbcapi/util/Graph.java +++ b/src/main/java/org/onap/dmaap/dbcapi/util/Graph.java @@ -26,7 +26,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.onap.dmaap.dbcapi.aaf.database.DatabaseClass; +import org.onap.dmaap.dbcapi.database.DatabaseClass; import org.onap.dmaap.dbcapi.model.DcaeLocation; import org.onap.dmaap.dbcapi.model.MR_Client; diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnectionTest.java deleted file mode 100644 index 7dec442..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/DrProvConnectionTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.client; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.service.*; -import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.List; -import java.util.ArrayList; -import java.io.InputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -public class DrProvConnectionTest { - - private static final String fmt = "%24s: %s%n"; - private static DmaapObjectFactory factory = new DmaapObjectFactory(); - - ReflectionHarness rh = new ReflectionHarness(); - - DrProvConnection ns; - MR_ClusterService mcs; - TopicService ts; - - @Before - public void setUp() throws Exception { - ns = new DrProvConnection(); - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "set", v ); - - } - - @Test - public void test3() { - String locname = "central-demo"; - - DcaeLocationService dls = new DcaeLocationService(); - DcaeLocation loc = factory.genDcaeLocation( "central" ); - dls.addDcaeLocation( loc ); - - ApiError err = new ApiError(); - String[] hl = { "host1", "host2", "host3" }; - ns.makeFeedConnection( ); - ns.makeFeedConnection( "01" ); - ns.makeSubPostConnection( "part0/part1/part2/part3/part4" ); - ns.makeSubPutConnection( "44" ); - ns.makeIngressConnection( "01", "aUser", "10.10.10.10", "aNode" ); - ns.makeEgressConnection( "01", "aNode" ); - ns.makeNodesConnection( "someVar" ); - Feed feed = new Feed( "dgl feed 1" , - "v1.0", - "dgl feed 1 for testing", - "TEST", - "unclassified" - ); - ArrayList pubs = new ArrayList(); - pubs.add( new DR_Pub( "central-demo" ) ); - feed.setPubs(pubs); - - String resp = ns.doPostFeed( feed, err ); - resp = ns.doPutFeed( feed, err ); - resp = ns.doDeleteFeed( feed, err ); - - int i = ns.doXgressPost( err ); - - DR_Sub sub = factory.genDrSub( "central", feed.getFeedId() ); - assertTrue( sub != null ); - String sr = ns.doPostDr_Sub( sub, err ); - /* - * TODO: - - create a new DR_Sub based on a simulated response - - update using ns.doPutDr_Sub( sub, err ); - */ - } - - @Test - public void test4() { - ApiError err = new ApiError(); - String resp = ns.doGetNodes( err ); - ns.makeNodesConnection( "someVar", "host1|host2" ); - resp = ns.doPutNodes( err ); - try { - InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); - String body = ns.bodyToString( is ); - } catch ( FileNotFoundException fnfe ) { - } - } - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnectionTest.java deleted file mode 100644 index b96e173..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrProvConnectionTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.client; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.service.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.List; -import java.util.ArrayList; -import java.io.InputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -public class MrProvConnectionTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - MrProvConnection ns; - MR_ClusterService mcs; - TopicService ts; - - @Before - public void setUp() throws Exception { - ns = new MrProvConnection(); - ts = new TopicService(); - mcs = new MR_ClusterService(); - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "set", v ); - - } - - @Test - public void test3() { - String locname = "central-demo"; - - DcaeLocationService dls = new DcaeLocationService(); - DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); - dls.addDcaeLocation( loc ); - - ApiError err = new ApiError(); - String[] hl = { "host1", "host2", "host3" }; - MR_Cluster cluster = new MR_Cluster( locname, "localhost", "", hl ); - mcs.addMr_Cluster( cluster, err ); - ns.makeTopicConnection( cluster ); - Topic topic = new Topic(); - topic.setTopicName( "test5" ); - String resp = ns.doPostTopic( topic, err ); - - try { - InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); - String body = ns.bodyToString( is ); - } catch ( FileNotFoundException fnfe ) { - } - - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnectionTest.java deleted file mode 100644 index 548c24a..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/client/MrTopicConnectionTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.client; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.service.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.List; -import java.util.ArrayList; -import java.io.InputStream; -import java.io.FileInputStream; -import java.io.FileNotFoundException; - -public class MrTopicConnectionTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - MrTopicConnection ns; - MR_ClusterService mcs; - TopicService ts; - - @Before - public void setUp() throws Exception { - ns = new MrTopicConnection( "aUser", "aPwd" ); - ts = new TopicService(); - mcs = new MR_ClusterService(); - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); - - } - - @Test - public void test3() { - String locname = "central-demo"; - - DcaeLocationService dls = new DcaeLocationService(); - DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); - dls.addDcaeLocation( loc ); - - ApiError err = new ApiError(); - String[] hl = { "host1", "host2", "host3" }; - MR_Cluster cluster = new MR_Cluster( locname, "localhost", "", hl ); - mcs.addMr_Cluster( cluster, err ); - ns.makeTopicConnection( cluster, "org.onap.dmaap.anInterestingTopic", "" ); - String msg = "{ 'key': '1234', 'val': 'hello world' }"; - ApiError e2 = ns.doPostMessage( msg ); - - try { - InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); - String body = ns.bodyToString( is ); - } catch ( FileNotFoundException fnfe ) { - } - - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandlerTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandlerTest.java deleted file mode 100644 index 99022b4..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBFieldHandlerTest.java +++ /dev/null @@ -1,106 +0,0 @@ - -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.database; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; - -public class DBFieldHandlerTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - int val = rs.getInt(index); - - return (ReplicationType.valueOf(val)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setInt(index, 0); - return; - } - @SuppressWarnings("unchecked") - ReplicationType rep = (ReplicationType) val; - ps.setInt(index, rep.getValue()); - } - } - - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); - - } - - @Test - public void test3() { - - try { - DBFieldHandler fh = new DBFieldHandler( String.class, "aString", 1 ); - } catch (Exception e ) { - } - - } - - @Test - public void test4() { - - try { - DBFieldHandler fh = new DBFieldHandler( String.class, "aString", 1, null ); - } catch (Exception e ) { - } - - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBMapTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBMapTest.java deleted file mode 100644 index 46138ab..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBMapTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.database; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; -import org.onap.dmaap.dbcapi.util.Singleton; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; - -public class DBMapTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - - private static Singleton dmaap; - private static Map dcaeLocations; - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); - - } - - @Test - public void test3() { - try { - dmaap = new DBSingleton(Dmaap.class, "dmaap"); - Dmaap nd = new Dmaap(); - dmaap.update(nd); - } catch (Exception e ) { - } - try { - dcaeLocations = new DBMap(DcaeLocation.class, "dcae_location", "dcae_location_name"); - } catch (Exception e ) { - } - - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBSingletonTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBSingletonTest.java deleted file mode 100644 index e2b3653..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/DBSingletonTest.java +++ /dev/null @@ -1,72 +0,0 @@ - -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.database; - -import org.onap.dmaap.dbcapi.aaf.database.DBSingleton; -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; - -public class DBSingletonTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - - @Test - public void test3() { - - try { - DBSingleton dmaap = new DBSingleton(Dmaap.class, "dmaap"); - Dmaap d = new Dmaap(); - dmaap.init( d ); - d = dmaap.get(); - d.setDmaapName( "foo" ); - dmaap.update( d ); - dmaap.remove(); - } catch (Exception e ) { - } - - } - - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchemaTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchemaTest.java deleted file mode 100644 index 3650a6e..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/LoadSchemaTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.database; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; - -public class LoadSchemaTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - LoadSchema ls; - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - rh.reflect( "org.onap.dmaap.dbcapi.aaf.database.LoadSchema", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - rh.reflect( "org.onap.dmaap.dbcapi.aaf.database.LoadSchema", "set", v ); - - } - - @Test - public void test3() { - ls = new LoadSchema(); - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/TableHandlerTest.java b/src/test/java/org/onap/dmaap/dbcapi/aaf/database/TableHandlerTest.java deleted file mode 100644 index ac6b336..0000000 --- a/src/test/java/org/onap/dmaap/dbcapi/aaf/database/TableHandlerTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dmaap - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ -package org.onap.dmaap.dbcapi.aaf.database; - -import org.onap.dmaap.dbcapi.model.*; -import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; - -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import java.util.*; -import java.sql.*; - -public class TableHandlerTest { - - private static final String fmt = "%24s: %s%n"; - - ReflectionHarness rh = new ReflectionHarness(); - - private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { - public Object get(ResultSet rs, int index) throws Exception { - int val = rs.getInt(index); - - return (ReplicationType.valueOf(val)); - } - public void set(PreparedStatement ps, int index, Object val) throws Exception { - if (val == null) { - ps.setInt(index, 0); - return; - } - @SuppressWarnings("unchecked") - ReplicationType rep = (ReplicationType) val; - ps.setInt(index, rep.getValue()); - } - } - - - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void test1() { - - - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); - - } - - @Test - public void test2() { - String v = "Validate"; - //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); - - } - - @Test - public void test3() { - TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); - - try { - ConnectionFactory cf = new ConnectionFactory(); - TableHandler th = new TableHandler( cf, TopicReplicationTypeHandler.class, "foo", "bar" ); - } catch (Exception e ) { - } - try { - ConnectionFactory cf = new ConnectionFactory(); - TableHandler th = new TableHandler( TopicReplicationTypeHandler.class, "foo", "bar" ); - th.getSpecialCase( "foo", "bar" ); - } catch (Exception e ) { - } - - } - - - -} - diff --git a/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java new file mode 100644 index 0000000..420b991 --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/client/DrProvConnectionTest.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.client; + +import org.onap.dmaap.dbcapi.client.DrProvConnection; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import org.onap.dmaap.dbcapi.testframework.DmaapObjectFactory; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; +import java.util.ArrayList; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class DrProvConnectionTest { + + private static final String fmt = "%24s: %s%n"; + private static DmaapObjectFactory factory = new DmaapObjectFactory(); + + ReflectionHarness rh = new ReflectionHarness(); + + DrProvConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new DrProvConnection(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.DrProvConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = factory.genDcaeLocation( "central" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] hl = { "host1", "host2", "host3" }; + ns.makeFeedConnection( ); + ns.makeFeedConnection( "01" ); + ns.makeSubPostConnection( "part0/part1/part2/part3/part4" ); + ns.makeSubPutConnection( "44" ); + ns.makeIngressConnection( "01", "aUser", "10.10.10.10", "aNode" ); + ns.makeEgressConnection( "01", "aNode" ); + ns.makeNodesConnection( "someVar" ); + Feed feed = new Feed( "dgl feed 1" , + "v1.0", + "dgl feed 1 for testing", + "TEST", + "unclassified" + ); + ArrayList pubs = new ArrayList(); + pubs.add( new DR_Pub( "central-demo" ) ); + feed.setPubs(pubs); + + String resp = ns.doPostFeed( feed, err ); + resp = ns.doPutFeed( feed, err ); + resp = ns.doDeleteFeed( feed, err ); + + int i = ns.doXgressPost( err ); + + DR_Sub sub = factory.genDrSub( "central", feed.getFeedId() ); + assertTrue( sub != null ); + String sr = ns.doPostDr_Sub( sub, err ); + /* + * TODO: + - create a new DR_Sub based on a simulated response + - update using ns.doPutDr_Sub( sub, err ); + */ + } + + @Test + public void test4() { + ApiError err = new ApiError(); + String resp = ns.doGetNodes( err ); + ns.makeNodesConnection( "someVar", "host1|host2" ); + resp = ns.doPutNodes( err ); + try { + InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + } + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java new file mode 100644 index 0000000..45b2f2e --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/client/MrProvConnectionTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.client; + +import org.onap.dmaap.dbcapi.client.MrProvConnection; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; +import java.util.ArrayList; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class MrProvConnectionTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + MrProvConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new MrProvConnection(); + ts = new TopicService(); + mcs = new MR_ClusterService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrProvConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] hl = { "host1", "host2", "host3" }; + MR_Cluster cluster = new MR_Cluster( locname, "localhost", "", hl ); + mcs.addMr_Cluster( cluster, err ); + ns.makeTopicConnection( cluster ); + Topic topic = new Topic(); + topic.setTopicName( "test5" ); + String resp = ns.doPostTopic( topic, err ); + + try { + InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java b/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java new file mode 100644 index 0000000..2163925 --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/client/MrTopicConnectionTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.client; + +import org.onap.dmaap.dbcapi.client.MrTopicConnection; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.service.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.List; +import java.util.ArrayList; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +public class MrTopicConnectionTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + MrTopicConnection ns; + MR_ClusterService mcs; + TopicService ts; + + @Before + public void setUp() throws Exception { + ns = new MrTopicConnection( "aUser", "aPwd" ); + ts = new TopicService(); + mcs = new MR_ClusterService(); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + String locname = "central-demo"; + + DcaeLocationService dls = new DcaeLocationService(); + DcaeLocation loc = new DcaeLocation( "CLLI1234", "central-onap", locname, "aZone", "10.10.10.0/24" ); + dls.addDcaeLocation( loc ); + + ApiError err = new ApiError(); + String[] hl = { "host1", "host2", "host3" }; + MR_Cluster cluster = new MR_Cluster( locname, "localhost", "", hl ); + mcs.addMr_Cluster( cluster, err ); + ns.makeTopicConnection( cluster, "org.onap.dmaap.anInterestingTopic", "" ); + String msg = "{ 'key': '1234', 'val': 'hello world' }"; + ApiError e2 = ns.doPostMessage( msg ); + + try { + InputStream is = new FileInputStream( "./etc/dmaapbc.properties" ); + String body = ns.bodyToString( is ); + } catch ( FileNotFoundException fnfe ) { + } + + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java b/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java new file mode 100644 index 0000000..c1e9c35 --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/database/DBFieldHandlerTest.java @@ -0,0 +1,107 @@ + +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.database; + +import org.onap.dmaap.dbcapi.database.DBFieldHandler; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +public class DBFieldHandlerTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + + try { + DBFieldHandler fh = new DBFieldHandler( String.class, "aString", 1 ); + } catch (Exception e ) { + } + + } + + @Test + public void test4() { + + try { + DBFieldHandler fh = new DBFieldHandler( String.class, "aString", 1, null ); + } catch (Exception e ) { + } + + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java b/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java new file mode 100644 index 0000000..338479d --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/database/DBMapTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.database; + +import org.onap.dmaap.dbcapi.database.DBMap; +import org.onap.dmaap.dbcapi.database.DBSingleton; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; +import org.onap.dmaap.dbcapi.util.Singleton; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +public class DBMapTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + private static Singleton dmaap; + private static Map dcaeLocations; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + try { + dmaap = new DBSingleton(Dmaap.class, "dmaap"); + Dmaap nd = new Dmaap(); + dmaap.update(nd); + } catch (Exception e ) { + } + try { + dcaeLocations = new DBMap(DcaeLocation.class, "dcae_location", "dcae_location_name"); + } catch (Exception e ) { + } + + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java b/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java new file mode 100644 index 0000000..18eff64 --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/database/DBSingletonTest.java @@ -0,0 +1,72 @@ + +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.database; + +import org.onap.dmaap.dbcapi.database.DBSingleton; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +public class DBSingletonTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + + @Test + public void test3() { + + try { + DBSingleton dmaap = new DBSingleton(Dmaap.class, "dmaap"); + Dmaap d = new Dmaap(); + dmaap.init( d ); + d = dmaap.get(); + d.setDmaapName( "foo" ); + dmaap.update( d ); + dmaap.remove(); + } catch (Exception e ) { + } + + } + + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java b/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java new file mode 100644 index 0000000..48a3cf6 --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/database/LoadSchemaTest.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.database; + +import org.onap.dmaap.dbcapi.database.LoadSchema; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +public class LoadSchemaTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + LoadSchema ls; + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + rh.reflect( "org.onap.dmaap.dbcapi.aaf.database.LoadSchema", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + rh.reflect( "org.onap.dmaap.dbcapi.aaf.database.LoadSchema", "set", v ); + + } + + @Test + public void test3() { + ls = new LoadSchema(); + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java b/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java new file mode 100644 index 0000000..dc2bb2f --- /dev/null +++ b/src/test/java/org/onap/dmaap/dbcapi/database/TableHandlerTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dmaap + * ================================================================================ + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ +package org.onap.dmaap.dbcapi.database; + +import org.onap.dmaap.dbcapi.database.ConnectionFactory; +import org.onap.dmaap.dbcapi.database.DBFieldHandler; +import org.onap.dmaap.dbcapi.database.TableHandler; +import org.onap.dmaap.dbcapi.model.*; +import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; + +import static org.junit.Assert.*; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import java.util.*; +import java.sql.*; + +public class TableHandlerTest { + + private static final String fmt = "%24s: %s%n"; + + ReflectionHarness rh = new ReflectionHarness(); + + private static class TopicReplicationTypeHandler implements DBFieldHandler.SqlOp { + public Object get(ResultSet rs, int index) throws Exception { + int val = rs.getInt(index); + + return (ReplicationType.valueOf(val)); + } + public void set(PreparedStatement ps, int index, Object val) throws Exception { + if (val == null) { + ps.setInt(index, 0); + return; + } + @SuppressWarnings("unchecked") + ReplicationType rep = (ReplicationType) val; + ps.setInt(index, rep.getValue()); + } + } + + + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void test1() { + + + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "get", "idNotSet@namespaceNotSet:pwdNotSet" ); + + } + + @Test + public void test2() { + String v = "Validate"; + //rh.reflect( "org.onap.dmaap.dbcapi.aaf.client.MrTopicConnection", "set", v ); + + } + + @Test + public void test3() { + TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler()); + + try { + ConnectionFactory cf = new ConnectionFactory(); + TableHandler th = new TableHandler( cf, TopicReplicationTypeHandler.class, "foo", "bar" ); + } catch (Exception e ) { + } + try { + ConnectionFactory cf = new ConnectionFactory(); + TableHandler th = new TableHandler( TopicReplicationTypeHandler.class, "foo", "bar" ); + th.getSpecialCase( "foo", "bar" ); + } catch (Exception e ) { + } + + } + + + +} + diff --git a/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java b/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java index f29d985..67489e1 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/service/ApiServiceTest.java @@ -21,9 +21,9 @@ package org.onap.dmaap.dbcapi.service; import org.onap.dmaap.dbcapi.model.*; import org.onap.dmaap.dbcapi.aaf.*; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.resources.*; import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; import static org.junit.Assert.*; diff --git a/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java b/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java index 1827594..d601bc4 100644 --- a/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java +++ b/src/test/java/org/onap/dmaap/dbcapi/service/FeedServiceTest.java @@ -21,9 +21,9 @@ package org.onap.dmaap.dbcapi.service; import org.onap.dmaap.dbcapi.model.*; import org.onap.dmaap.dbcapi.aaf.*; +import org.onap.dmaap.dbcapi.authentication.AuthenticationErrorException; import org.onap.dmaap.dbcapi.resources.*; import org.onap.dmaap.dbcapi.testframework.ReflectionHarness; -import org.onap.dmaap.dbcapi.aaf.authentication.AuthenticationErrorException; import static org.junit.Assert.*; -- cgit