aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/org/openecomp')
-rw-r--r--src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java117
-rw-r--r--src/main/java/org/openecomp/dmaapbc/aaf/AafDecrypt.java56
-rw-r--r--src/main/java/org/openecomp/dmaapbc/aaf/AafService.java75
-rw-r--r--src/main/java/org/openecomp/dmaapbc/aaf/ClearDecrypt.java (renamed from src/main/java/org/openecomp/dmaapbc/aaf/AndrewDecryptor.java)98
-rw-r--r--src/main/java/org/openecomp/dmaapbc/aaf/DecryptionInterface.java30
-rw-r--r--src/main/java/org/openecomp/dmaapbc/authentication/ApiPermissionInterface.java28
-rw-r--r--src/main/java/org/openecomp/dmaapbc/authentication/ApiPerms.java166
-rw-r--r--src/main/java/org/openecomp/dmaapbc/authentication/ApiPolicy.java57
-rw-r--r--src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java157
-rw-r--r--src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java338
-rw-r--r--src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java47
-rw-r--r--src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java20
-rw-r--r--src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java12
-rw-r--r--src/main/java/org/openecomp/dmaapbc/database/DBException.java8
-rw-r--r--src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java14
-rw-r--r--src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java47
-rw-r--r--src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java12
-rw-r--r--src/main/java/org/openecomp/dmaapbc/logging/BaseLoggingClass.java36
-rw-r--r--src/main/java/org/openecomp/dmaapbc/logging/DmaapbcLogMessageEnum.java81
-rw-r--r--src/main/java/org/openecomp/dmaapbc/logging/logmsg.properties240
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java3
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java36
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/Dmaap.java3
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java61
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/Feed.java34
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/MR_Client.java7
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java17
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java3
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/ReplicationType.java83
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java4
-rw-r--r--src/main/java/org/openecomp/dmaapbc/model/Topic.java58
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/Authorization.java (renamed from src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java)68
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/AuthorizationFilter.java61
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java51
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java170
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java237
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java212
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java157
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java93
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java168
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java237
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java178
-rw-r--r--src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java183
-rw-r--r--src/main/java/org/openecomp/dmaapbc/server/ApplicationConfig.java36
-rw-r--r--src/main/java/org/openecomp/dmaapbc/server/JettyServer.java25
-rw-r--r--src/main/java/org/openecomp/dmaapbc/server/Main.java76
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/ApiService.java226
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java139
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java12
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java96
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java8
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/DmaapService.java45
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/FeedService.java9
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java215
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java18
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java63
-rw-r--r--src/main/java/org/openecomp/dmaapbc/service/TopicService.java288
-rw-r--r--src/main/java/org/openecomp/dmaapbc/util/Graph.java8
58 files changed, 3441 insertions, 1586 deletions
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java
index 421e948..3ff7a01 100644
--- a/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java
+++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java
@@ -37,16 +37,17 @@ import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLHandshakeException;
import org.apache.commons.codec.binary.Base64;
-import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.service.DmaapService;
-public class AafConnection {
+public class AafConnection extends BaseLoggingClass {
+
- static final Logger logger = Logger.getLogger(AafConnection.class);
- private String dmaapName;
+
private String aafCred;
@@ -54,10 +55,6 @@ public class AafConnection {
public AafConnection( String cred ) {
- dmaapName = new DmaapService().getDmaap().getDmaapName();
- if ( dmaapName.length() < 1 ) {
- logger.fatal( "Attempting to access AAF before dmaap object is set");
- }
aafCred = cred;
}
@@ -71,7 +68,7 @@ public class AafConnection {
logger.info( "successful connect to " + pURL );
return(true);
} catch (Exception e) {
- logger.error("Unexpected error during openConnection of " + pURL );
+ errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR, pURL, e.getMessage() );
e.printStackTrace();
return(false);
}
@@ -87,7 +84,7 @@ public class AafConnection {
sb.append( line );
}
} catch (IOException ex ) {
- logger.error( "IOexception:" + ex);
+ errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION, ex.getMessage());
}
return sb.toString();
@@ -96,11 +93,10 @@ public class AafConnection {
public int postAaf( AafObject obj, String pURL ) {
-
+ logger.info( "entry: postAaf() to " + pURL );
String auth = "Basic " + Base64.encodeBase64String(aafCred.getBytes());
int rc = -1;
- // TODO Auto-generated method stub
- logger.info( "entry: setPerm() " );
+
if ( ! makeConnection( pURL ) ) {
return rc;
@@ -139,16 +135,12 @@ public class AafConnection {
} catch (Exception e) {
}
} catch ( SSLHandshakeException she ) {
- logger.error( "SSLHandshakeException from AAF URL " + pURL);
- } catch ( UnknownHostException uhe ) {
- logger.error( "UnknownHostException from AAF for URL " + pURL );
- rc = 500;
- return rc;
- }
+ errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
+ }
try {
rc = uc.getResponseCode();
} catch ( SSLHandshakeException she ) {
- logger.error( "SSLHandshakeException from AAF URL " + pURL);
+ errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
rc = 500;
return rc;
}
@@ -190,5 +182,90 @@ public class AafConnection {
}
+ public int delAaf(AafObject obj, String pURL) {
+ logger.info( "entry: delAaf() to " + pURL );
+ String auth = "Basic " + Base64.encodeBase64String(aafCred.getBytes());
+ int rc = -1;
+
+
+ if ( ! makeConnection( pURL ) ) {
+ return rc;
+ };
+
+
+ byte[] postData = obj.getBytes();
+ //logger.info( "post fields=" + postData ); //byte isn't very readable
+ String responsemessage = null;
+ String responseBody = null;
+
+ try {
+ if (auth != null) {
+ uc.setRequestProperty("Authorization", auth);
+ }
+ uc.setRequestMethod("DELETE");
+ 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 ( SSLHandshakeException she ) {
+ errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
+ }
+ try {
+ rc = uc.getResponseCode();
+ } catch ( SSLHandshakeException she ) {
+ errorLogger.error( DmaapbcLogMessageEnum.SSL_HANDSHAKE_ERROR, pURL);
+ rc = 500;
+ return rc;
+ }
+ 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 {
+ logger.warn( "Unsuccessful response: " + responsemessage );
+ }
+
+ } catch (Exception e) {
+ System.err.println("Unable to read response " );
+ e.printStackTrace();
+ }
+ //return responseBody;
+
+ return rc;
+
+ }
+
}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafDecrypt.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafDecrypt.java
new file mode 100644
index 0000000..3e078e1
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafDecrypt.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.aaf;
+
+import java.io.IOException;
+
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+public class AafDecrypt extends BaseLoggingClass {
+ String dClass = null;
+ DecryptionInterface dec = null;
+
+ public AafDecrypt() {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ dClass = p.getProperty( "AafDecryption.Class", "org.openecomp.dmaapbc.aaf.ClearDecrypt");
+ try {
+ dec = (DecryptionInterface) (Class.forName(dClass).newInstance());
+ dec.init( p.getProperty("CredentialCodecKeyfile", "LocalKey"));
+ } catch (Exception ee ) {
+ errorLogger.error(DmaapbcLogMessageEnum.UNEXPECTED_CONDITION, "attempting to instantiate " + dClass );
+ }
+ }
+
+ public String decrypt( String encPwd ) {
+
+ String pwd = "notDecrypted";
+ try {
+ pwd = dec.decrypt( encPwd );
+ } catch( IOException io ) {
+ errorLogger.error(DmaapbcLogMessageEnum.DECRYPT_IO_ERROR, dClass, encPwd );
+ }
+
+ return pwd;
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java
index 4de41e3..8e0dce8 100644
--- a/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java
+++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java
@@ -23,14 +23,15 @@ package org.openecomp.dmaapbc.aaf;
import java.io.IOException;
import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.util.DmaapConfig;
-public class AafService {
+public class AafService extends BaseLoggingClass {
public enum ServiceType {
AAF_Admin,
AAF_TopicMgr
}
- static final Logger logger = Logger.getLogger(AafService.class);
private AafConnection aaf;
private ServiceType ctype;
@@ -40,6 +41,7 @@ public class AafService {
String mechIdProperty = null;
String pwdProperty = null;
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ AafDecrypt decryptor = new AafDecrypt();
if ( ctype == ServiceType.AAF_Admin ) {
mechIdProperty = "aaf.AdminUser";
@@ -52,7 +54,23 @@ public class AafService {
return null;
}
String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
- String pwd = AndrewDecryptor.valueOf(p.getProperty( pwdProperty, "notSet" ));
+ //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);
if ( wPwd ) {
return user + ":" + pwd;
@@ -66,6 +84,14 @@ public class AafService {
public AafService(ServiceType t ) {
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
aafURL = p.getProperty( "aaf.URL", "https://authentication.domain.netset.com:8095/proxy/");
+ initAafService( t );
+ }
+ public AafService( ServiceType t, String url ) {
+ aafURL = url;
+ initAafService( t );
+ }
+
+ private void initAafService( ServiceType t ) {
ctype = t;
aaf = new AafConnection( getCred( true ) );
}
@@ -73,17 +99,14 @@ public class AafService {
public int addPerm(DmaapPerm perm) {
int rc = -1;
- logger.info( "entry: setPerm() " );
+ logger.info( "entry: addPerm() " );
String pURL = aafURL + "authz/perm";
rc = aaf.postAaf( perm, pURL );
switch( rc ) {
case 401:
- logger.fatal( "Service credentials (" + getCred( false ) + ") are not valid for AAF connection");
- break;
case 403:
- logger.fatal( "Service credentials (" + getCred( false ) + ") are not authorized for requested action");
- break;
-
+ errorLogger.error(DmaapbcLogMessageEnum.AAF_CREDENTIAL_ERROR, getCred( false ) );
+ System.exit(1);
case 409:
logger.warn( "Perm already exists. Possible conflict.");
break;
@@ -101,16 +124,15 @@ public class AafService {
public int addGrant(DmaapGrant grant ) {
int rc = -1;
- logger.info( "entry: setPerm() " );
+ logger.info( "entry: addGrant() " );
String pURL = aafURL + "authz/role/perm";
rc = aaf.postAaf( grant, pURL );
switch( rc ) {
case 401:
- logger.fatal( "Service credentials (" + getCred( false ) + ") are not valid for AAF connection");
- break;
case 403:
- logger.fatal( "Service credentials (" + getCred( false ) + ") are not authorized for requested action");
+ errorLogger.error(DmaapbcLogMessageEnum.AAF_CREDENTIAL_ERROR, getCred( false ) );
+ System.exit(1);
break;
case 409:
@@ -128,4 +150,31 @@ public class AafService {
return rc;
}
+ public int delGrant( DmaapGrant grant ) {
+ int rc = -1;
+ logger.info( "entry: delGrant() " );
+
+ String pURL = aafURL + "authz/role/:" + grant.getRole() + "/perm";
+ rc = aaf.delAaf( grant, pURL );
+ switch( rc ) {
+ case 401:
+ case 403:
+ errorLogger.error(DmaapbcLogMessageEnum.AAF_CREDENTIAL_ERROR, getCred( false ) );
+ System.exit(1);
+ break;
+
+ case 404:
+ logger.warn( "Perm not found...ignore");
+ break;
+
+ case 200:
+ logger.info( "expected response" );
+ break;
+ default :
+ logger.error( "Unexpected response: " + rc );
+ break;
+ }
+
+ return rc;
+ }
}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AndrewDecryptor.java b/src/main/java/org/openecomp/dmaapbc/aaf/ClearDecrypt.java
index a4f6d9d..3ba2d82 100644
--- a/src/main/java/org/openecomp/dmaapbc/aaf/AndrewDecryptor.java
+++ b/src/main/java/org/openecomp/dmaapbc/aaf/ClearDecrypt.java
@@ -1,68 +1,42 @@
-/*-
+/*-
* ============LICENSE_START=======================================================
* OpenECOMP - org.openecomp.dmaapbc
* ================================================================================
* 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
+ * 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.openecomp.dmaapbc.aaf;
-
-import java.io.*;
-
-import org.openecomp.dmaapbc.util.DmaapConfig;
-
-// Commented out this package and the code that uses it until it becomes available.
-
-//import com.xxx.cadi.*;
-
-public class AndrewDecryptor {
- private static AndrewDecryptor instance;
- //private Symm symm;
-
- private AndrewDecryptor() {
- InputStream is = null;
- try {
- is = new FileInputStream(DmaapConfig.getConfig().getProperty("CredentialCodecKeyfile", "LocalKey"));
- //symm = Symm.obtain(is);
- } catch (Exception e) {
- } finally {
- try {
- if (is != null) {
- is.close();
- }
- } catch (Exception x) {
-
- }
- }
- }
- public String decrypt(String enc) throws IOException {
- return(enc);
- //return((enc != null && enc.startsWith(Symm.ENC))? symm.depass(enc): enc);
- }
- public static AndrewDecryptor getInstance() {
- if (instance == null) {
- instance = new AndrewDecryptor();
- }
- return(instance);
- }
- public static String valueOf(String enc) {
- try {
- return(getInstance().decrypt(enc));
- } catch (Exception e) {
- return(null);
- }
- }
-}
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.dmaapbc.aaf;
+
+import java.io.IOException;
+
+public class ClearDecrypt implements DecryptionInterface {
+
+ @Override
+ public String decrypt(String enc) throws IOException {
+ return enc;
+ }
+
+ @Override
+ public String valueOf(String s) {
+ return s;
+ }
+
+ @Override
+ public boolean init(String codecFname) {
+ return false;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/DecryptionInterface.java b/src/main/java/org/openecomp/dmaapbc/aaf/DecryptionInterface.java
new file mode 100644
index 0000000..f07bcd0
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/aaf/DecryptionInterface.java
@@ -0,0 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.aaf;
+
+import java.io.IOException;
+
+public interface DecryptionInterface {
+ public boolean init( String codecFname );
+ public String decrypt(String enc) throws IOException;
+ public String valueOf( String s);
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/authentication/ApiPermissionInterface.java b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPermissionInterface.java
new file mode 100644
index 0000000..ac29cae
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPermissionInterface.java
@@ -0,0 +1,28 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.authentication;
+
+import org.openecomp.dmaapbc.aaf.DmaapPerm;
+
+public interface ApiPermissionInterface {
+ public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException;
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/authentication/ApiPerms.java b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPerms.java
new file mode 100644
index 0000000..54e90dd
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPerms.java
@@ -0,0 +1,166 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.authentication;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.openecomp.dmaapbc.aaf.AafService;
+import org.openecomp.dmaapbc.aaf.DmaapGrant;
+import org.openecomp.dmaapbc.aaf.DmaapPerm;
+import org.openecomp.dmaapbc.aaf.AafService.ServiceType;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.model.Dmaap;
+import org.openecomp.dmaapbc.service.DmaapService;
+import org.openecomp.dmaapbc.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/openecomp/dmaapbc/authentication/ApiPolicy.java b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPolicy.java
new file mode 100644
index 0000000..d8be7a8
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/authentication/ApiPolicy.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.authentication;
+
+import org.openecomp.dmaapbc.aaf.DmaapPerm;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.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 );
+ }
+ }
+
+ 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/openecomp/dmaapbc/authentication/DecisionPolicy.java b/src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java
deleted file mode 100644
index 4384c56..0000000
--- a/src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * OpenECOMP - org.openecomp.dmaapbc
- * ================================================================================
- * 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.openecomp.dmaapbc.authentication;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.UUID;
-
-
-
-
-
-
-
-
-
-
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.aaf.DmaapPerm;
-import org.openecomp.dmaapbc.util.DmaapConfig;
-
-/* disable until available...
-import org.openecomp.policy.api.DecisionRequestParameters;
-import org.openecomp.policy.api.PolicyDecision;
-import org.openecomp.policy.api.DecisionResponse;
-import org.openecomp.policy.api.PolicyDecisionException;
-import org.openecomp.policy.api.PolicyEngine;
-import org.openecomp.policy.api.PolicyEngineException;
-*/
-
-public class DecisionPolicy {
- static final Logger logger = Logger.getLogger(DecisionPolicy.class);
- //PolicyEngine policyEngine = null;
- String aafEnvironment;
-
- public DecisionPolicy() {
- logger.info("Constructing DecisionPolicy using property");
- DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
- String config = p.getProperty("PolicyEngineProperties", "etc/PolicyEngineApi.properties");
- aafEnvironment = p.getProperty("PeAafEnvironment", "PROD"); // TEST= UAT, PROD = PROD, DEVL = TEST
- logger.info( "Initializing DecisionPolicy for env " + aafEnvironment + " using " + config);
- this.init( config );
- }
- public DecisionPolicy( String config ) {
- logger.info("Constructing DecisionPolicy using arg " + config );
- this.init( config );
- }
-
- public void init( String config ) {
- logger.info( "stubbed out PolicyEngine()" );
-/*
- try {
- policyEngine = new PolicyEngine( config );
- } catch (PolicyEngineException e) {
- logger.error( "Trying to read " + config + " and caught PolicyEngineException" + e );
- }
-*/
- }
- public void check( String mechid, String pwd, DmaapPerm p ) throws AuthenticationErrorException {
- logger.debug( mechid + " Permitted to do action " + p.getPermission() + "|" + p.getPtype() + "|" + p.getAction());
-
-/*
- // Create a Decision Policy Request.
- DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
- decisionRequestParameters.setECOMPComponentName("DMaaP"); // Required ECOMP Name
- decisionRequestParameters.setRequestID(UUID.randomUUID()); // Optional UUID Request
- // Put all the required Attributes into Decision Attributes.
-
- HashMap<String,String> decisionAttributes = new HashMap<String, String>();
- decisionAttributes.put("AAF_ID", mechid); // Fully qualified ID.
- decisionAttributes.put("AAF_PASS", pwd);
- decisionAttributes.put("AAF_TYPE", p.getPermission());
- decisionAttributes.put("AAF_INSTANCE", p.getPtype());
- decisionAttributes.put("AAF_ACTION", p.getAction());
- decisionAttributes.put("AAF_ENVIRONMENT", aafEnvironment); // TEST= UAT, PROD = PROD, DEVL = TEST
- decisionRequestParameters.setDecisionAttributes(decisionAttributes);
- // Send the request to Policy Engine and that returns a PolicyDecision Object.
- try {
- DecisionResponse response = policyEngine.getDecision(decisionRequestParameters);
- if(response.getDecision().equals(PolicyDecision.PERMIT)){
- logger.debug( mechid + " Permitted to do action " + p.getPermission() + "|" + p.getPtype() + "|" + p.getAction());
- }else{
- logger.debug( mechid + " NOT Permited to do action "+ p.getPermission() + "|" + p.getPtype() + "|" + p.getAction());
- logger.debug(response.getDetails());
- throw new AuthenticationErrorException();
- }
- } catch (PolicyDecisionException e) {
- System.err.println(e);
- logger.error(e);
- throw new AuthenticationErrorException();
- }
-*/
-
-
-
- }
-
-/*
- public static void main(String args[]){
- DecisionPolicy d = new DecisionPolicy();
- d.test();
- }
-
- public void test() {
-
- // TODO: pass in users and pwd from cmd line
- String[] ids = {"user1@namespace1",
- "user2@namespace2"};
- String[] pwds = {
- "pwd1",
- "pwd2"
- };
- List<DmaapPerm> perms = new ArrayList<DmaapPerm>();
-
-
- perms.add( new DmaapPerm("org.openecomp.dmaapBC.dmaap", "mtnje2", "POST"));
- perms.add( new DmaapPerm("org.openecomp.dmaapBC.dcaeLocations", "mtnje2", "POST"));
- perms.add( new DmaapPerm("org.openecomp.dmaapBC.dmaap", "mtnje2", "GET"));
- perms.add( new DmaapPerm("org.openecomp.dmaapBC.dmaap", "mtnje2", "PUT"));
- perms.add( new DmaapPerm("org.openecomp.dmaapBC.dmaap", "mtnje2", "DELETE"));
-
-
-
- for( DmaapPerm p : perms ) {
- for( int i = 0; i < ids.length; i++) {
- try {
- this.check( ids[i], pwds[i], p);
- System.out.println( "PERMIT! for "+ ids[i] + " " + p.getPermission() + "|" + p.getPtype() + "|" + p.getAction());
- } catch ( AuthenticationErrorException aee ) {
- System.out.println( "FAILED! for "+ ids[i] + " " + p.getPermission() + "|" + p.getPtype() + "|" + p.getAction());
- }
- }
- }
-
- }
-*/
-
-}
diff --git a/src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java b/src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java
index e4fe3cc..0e5d412 100644
--- a/src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java
+++ b/src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java
@@ -35,6 +35,8 @@ import javax.net.ssl.HttpsURLConnection;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DR_Sub;
@@ -44,8 +46,7 @@ import org.openecomp.dmaapbc.util.RandomInteger;
-public class DrProvConnection {
- static final Logger logger = Logger.getLogger(DrProvConnection.class);
+public class DrProvConnection extends BaseLoggingClass {
private String provURL;
@@ -56,7 +57,7 @@ public class DrProvConnection {
public DrProvConnection() {
provURL = new DmaapService().getDmaap().getDrProvUrl();
if ( provURL.length() < 1 ) {
- logger.error( "Attempting to access PROV before dmaap object is set");
+ errorLogger.error( DmaapbcLogMessageEnum.PREREQ_DMAAP_OBJECT, "getDrProvUrl");
}
}
@@ -67,17 +68,44 @@ public class DrProvConnection {
public boolean makeFeedConnection(String feedId) {
return makeConnection( provURL + "/feed/" + feedId );
}
- public boolean makeSubConnection( String subURL ) {
+ 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 ) {
@@ -88,7 +116,7 @@ public class DrProvConnection {
logger.info( "successful connect to " + pURL );
return(true);
} catch (Exception e) {
- logger.error("Unexpected error during openConnection of " + pURL );
+ errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_ERROR, pURL, e.getMessage() );
e.printStackTrace();
return(false);
}
@@ -105,7 +133,7 @@ public class DrProvConnection {
sb.append( line );
}
} catch (IOException ex ) {
- logger.error( "IOexception:" + ex);
+ errorLogger.error( DmaapbcLogMessageEnum.IO_EXCEPTION, ex.getMessage());
}
return sb.toString();
@@ -173,11 +201,11 @@ public class DrProvConnection {
}
} catch (ConnectException ce) {
- logger.error("Connection refused " );
+ errorLogger.error(DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
err.setCode( 500 );
err.setMessage("Backend connection refused");
} catch (SocketException se) {
- logger.error( "Socket exception: unexpected end of file from server" );
+ 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) {
@@ -202,7 +230,8 @@ public class DrProvConnection {
// the POST for /internal/route/ingress doesn't return any data, so needs a different function
- public int doIngressPost( ApiError err ) {
+ // 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;
@@ -256,7 +285,7 @@ public class DrProvConnection {
}
- public String doPostDr_Sub( DR_Sub postSub ) {
+ public String doPostDr_Sub( DR_Sub postSub, ApiError err ) {
logger.info( "entry: doPostDr_Sub() " );
byte[] postData = postSub.getBytes();
logger.info( "post fields=" + postData );
@@ -312,7 +341,10 @@ public class DrProvConnection {
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 " );
@@ -326,35 +358,6 @@ public class DrProvConnection {
}
- 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<DR_Pub> pubs = new ArrayList<DR_Pub>();
- 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);
- }
-
-
- }
public String doPutFeed(Feed putFeed, ApiError err) {
byte[] postData = putFeed.getBytes();
@@ -415,7 +418,7 @@ public class DrProvConnection {
err.setFields( "feedid");
String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?";
err.setMessage( message );
- logger.warn(message);
+ errorLogger.error( DmaapbcLogMessageEnum.PROV_OUT_OF_SYNC, "Feed", putFeed.getFeedId() );
} else {
err.setCode( rc );
@@ -423,11 +426,11 @@ public class DrProvConnection {
}
} catch (ConnectException ce) {
- logger.error("Connection refused " );
+ errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
err.setCode( 500 );
err.setMessage("Backend connection refused");
} catch (SocketException se) {
- logger.error( "Socket exception: unexpected end of file from server" );
+ 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) {
@@ -447,7 +450,256 @@ public class DrProvConnection {
}
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;
+ try {
+
+ 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;
+
+ 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); // 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);
+ }
+
+ } 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 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.printStackTrace();
+ } finally {
+ uc.disconnect();
+ }
+ 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<DR_Pub> pubs = new ArrayList<DR_Pub>();
+ 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/openecomp/dmaapbc/client/MrProvConnection.java b/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java
index 420c315..6647a1c 100644
--- a/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java
+++ b/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java
@@ -29,18 +29,24 @@ 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.openecomp.dmaapbc.aaf.AafDecrypt;
+import org.openecomp.dmaapbc.aaf.AafService;
+import org.openecomp.dmaapbc.aaf.AafService.ServiceType;
+import org.openecomp.dmaapbc.aaf.DecryptionInterface;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.Topic;
import org.openecomp.dmaapbc.util.DmaapConfig;
-public class MrProvConnection {
- static final Logger logger = Logger.getLogger(MrProvConnection.class);
-
-
+public class MrProvConnection extends BaseLoggingClass{
+
private String provURL;
private HttpsURLConnection uc;
@@ -48,11 +54,28 @@ public class MrProvConnection {
private String topicMgrCred;
+ private String getCred( ) {
+ String mechIdProperty = "aaf.TopicMgrUser";
+ String pwdProperty = "aaf.TopicMgrPassword";
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
- public MrProvConnection() {
- DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
- topicMgrCred = p.getProperty("aaf.TopicMgrUser", "noIdSet") + ":" + p.getProperty("aaf.TopicMgrPassword", "noPwdSet" );
+ String pwd = "";
+ String encPwd = p.getProperty( pwdProperty, "notSet" );
+
+ AafDecrypt decryptor = new AafDecrypt();
+ pwd = decryptor.decrypt(encPwd);
+
+ return user + ":" + pwd;
+
+
+
+ }
+
+
+ public MrProvConnection( ) {
+ topicMgrCred = getCred();
}
@@ -94,13 +117,13 @@ public class MrProvConnection {
sb.append( line );
}
} catch (IOException ex ) {
- logger.error( "IOexception:" + ex);
+ errorLogger.error( "IOexception:" + ex);
}
return sb.toString();
}
- public String doPostTopic( Topic postTopic ) {
+ public String doPostTopic( Topic postTopic, ApiError err ) {
String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
@@ -136,16 +159,18 @@ public class MrProvConnection {
} catch (Exception e) {
}
} catch ( UnknownHostException uhe ) {
- logger.error( "UnknownHostException: " + uhe.getMessage() );
+ errorLogger.error( DmaapbcLogMessageEnum.UNKNOWN_HOST_EXCEPTION , uhe.getMessage() , provURL );
return new String( "500: " + uhe.getMessage());
}catch ( ConnectException ce ) {
- logger.error( "ConnectException: " + ce.getMessage() );
+ errorLogger.error( DmaapbcLogMessageEnum.HTTP_CONNECTION_EXCEPTION, provURL, ce.getMessage() );
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) {
diff --git a/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java b/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java
index 1ab2431..0fdf109 100644
--- a/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java
+++ b/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java
@@ -27,15 +27,17 @@ 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.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.MR_Cluster;
-public class MrTopicConnection {
- static final Logger logger = Logger.getLogger(MrTopicConnection.class);
+public class MrTopicConnection extends BaseLoggingClass {
private String topicURL;
private HttpsURLConnection uc;
@@ -50,11 +52,12 @@ public class MrTopicConnection {
}
- public boolean makeTopicConnection( MR_Cluster cluster, String topic ) {
- logger.info( "connect to cluster: " + cluster.getFqdn() + " for topic: " + topic );
+ 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() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/events/" + topic ;
+ topicURL = cluster.getTopicProtocol() + "://" + fqdn + ":" + cluster.getTopicPort() + "/events/" + topic ;
return makeConnection( topicURL );
}
@@ -85,7 +88,7 @@ public class MrTopicConnection {
sb.append( line );
}
} catch (IOException ex ) {
- logger.error( "IOexception:" + ex);
+ errorLogger.error( "IOexception:" + ex);
}
return sb.toString();
@@ -124,6 +127,11 @@ public class MrTopicConnection {
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());
diff --git a/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java b/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java
index 7dd54ae..b378edb 100644
--- a/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java
+++ b/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java
@@ -24,10 +24,20 @@ 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.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.util.DmaapConfig;
public class ConnectionFactory {
- static final Logger logger = Logger.getLogger(ConnectionFactory.class);
+ 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");
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBException.java b/src/main/java/org/openecomp/dmaapbc/database/DBException.java
index 91193d8..950d451 100644
--- a/src/main/java/org/openecomp/dmaapbc/database/DBException.java
+++ b/src/main/java/org/openecomp/dmaapbc/database/DBException.java
@@ -20,12 +20,14 @@
package org.openecomp.dmaapbc.database;
-import org.apache.log4j.Logger;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
public class DBException extends RuntimeException {
- static final Logger logger = Logger.getLogger(DBException.class);
+ static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
public DBException(Exception e) {
super(e);
- logger.error("Database access problem " + e, e);
+ errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_ERROR, e.getMessage());
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java b/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java
index 46e0fb5..d9079d9 100644
--- a/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java
+++ b/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java
@@ -25,8 +25,14 @@ 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.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+
+
public class DBFieldHandler {
- static final Logger logger = Logger.getLogger(DBFieldHandler.class);
+ 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;
@@ -106,7 +112,7 @@ public class DBFieldHandler {
try {
sqlset.invoke(ps, index, val);
} catch (Exception e) {
- logger.error("Problem setting field " + index + " to " + val + " statement is " + ps);
+ errorLogger.error(DmaapbcLogMessageEnum.DB_FIELD_INIT_ERROR, Integer.toString(index), val.toString(), ps.toString());
throw e;
}
}
@@ -126,7 +132,7 @@ public class DBFieldHandler {
new SqlType("Short");
new SqlType("String");
} catch (Exception e) {
- logger.error("Problem initializing sql access methods " + e, e);
+ errorLogger.error(DmaapbcLogMessageEnum.DB_ACCESS_INIT_ERROR, e.getMessage() );
}
}
private Method objget;
@@ -177,7 +183,7 @@ public class DBFieldHandler {
if (sqlop != null) {
return;
}
- logger.error("No field handler for class " + c.getName() + " field " + fieldname + " index " + fieldnum + " type " + x.getName());
+ errorLogger.error(DmaapbcLogMessageEnum.DB_NO_FIELD_HANDLER, c.getName(), fieldname, Integer.toString(fieldnum), x.getName());
}
public static String fesc(String s) {
if (s == null) {
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java b/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java
index 973d592..f7da850 100644
--- a/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java
+++ b/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java
@@ -23,7 +23,8 @@ package org.openecomp.dmaapbc.database;
import java.util.*;
import java.sql.*;
-import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.DR_Node;
import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DR_Sub;
@@ -35,18 +36,14 @@ import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.MirrorMaker;
import org.openecomp.dmaapbc.model.ReplicationVector;
import org.openecomp.dmaapbc.model.Topic;
-import org.openecomp.dmaapbc.service.DmaapService;
import org.openecomp.dmaapbc.util.DmaapConfig;
import org.openecomp.dmaapbc.util.Singleton;
-
import org.openecomp.dmaapbc.model.*;
-public class DatabaseClass {
-
- static final Logger logger = Logger.getLogger(DatabaseClass.class);
+public class DatabaseClass extends BaseLoggingClass {
private static Singleton<Dmaap> dmaap;
private static Map<String, DcaeLocation> dcaeLocations;
@@ -128,6 +125,22 @@ public class DatabaseClass {
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<Dmaap> getDmaap() {
return dmaap;
}
@@ -170,15 +183,15 @@ public class DatabaseClass {
static {
try {
- logger.info( "begin static initialization");
- logger.info( "initializing dmaap" );
+ appLogger.info( "begin static initialization");
+ appLogger.info( "initializing dmaap" );
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
if ("true".equalsIgnoreCase(p.getProperty("UsePGSQL", "false"))) {
- logger.info("Data from database");
+ appLogger.info("Data from database");
try {
LoadSchema.upgrade();
} catch (Exception e) {
- logger.warn("Problem updating DB schema", e);
+ appLogger.warn("Problem updating DB schema", e);
}
try {
dmaap = new DBSingleton<Dmaap>(Dmaap.class, "dmaap");
@@ -189,16 +202,17 @@ public class DatabaseClass {
mr_clients = new DBMap<MR_Client>(MR_Client.class, "mr_client", "mr_client_id");
mr_clusters = new DBMap<MR_Cluster>(MR_Cluster.class, "mr_cluster", "dcae_location_name");
feeds = new DBMap<Feed>(Feed.class, "feed", "feed_id");
+ TableHandler.setSpecialCase("topic", "replication_case", new TopicReplicationTypeHandler());
topics = new DBMap<Topic>(Topic.class, "topic", "fqtn");
//TableHandler.setSpecialCase("mirror_maker", "vectors", new MirrorVectorHandler());
TableHandler.setSpecialCase("mirror_maker", "topics", new MirrorTopicsHandler());
mirrors = new DBMap<MirrorMaker>(MirrorMaker.class, "mirror_maker", "mm_name");
} catch (Exception e) {
- logger.fatal("Error initializing database access " + e, e);
+ errorLogger.error("Error initializing database access " + e, e);
System.exit(1);
}
} else {
- logger.info("Data from memory");
+ appLogger.info("Data from memory");
dmaap = new Singleton<Dmaap>() {
private Dmaap dmaap;
public void remove() {
@@ -240,15 +254,14 @@ public class DatabaseClass {
dmx = new Dmaap("0", "", "", "", "", "", "", "");
dmx.setDmaapName(p.getProperty("DmaapName"));
- dmx.setDrProvUrl("https://" + p.getProperty("DR.provhost"));
- dmx.setVersion("1");
- dmx.setTopicNsRoot("org.openecomp.dcae.dmaap");
+ dmx.setDrProvUrl("https://" + p.getProperty("DR.provhost", "notSet"));
+ dmx.setTopicNsRoot(p.getProperty("topicNsRoot"));
dmx.setBridgeAdminTopic("DCAE_MM_AGENT");
- (new DmaapService()).addDmaap(dmx);
+ dmaap.update(dmx);
}
} catch (Exception e) {
- logger.error("Error loading database " + e, e);
+ errorLogger.error(DmaapbcLogMessageEnum.DB_UPDATE_ERROR, e.getMessage());
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java b/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java
index bcf838a..e8b3e5b 100644
--- a/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java
+++ b/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java
@@ -24,8 +24,18 @@ 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.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+
public class LoadSchema {
- static Logger logger = Logger.getLogger(LoadSchema.class);
+ 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 {
diff --git a/src/main/java/org/openecomp/dmaapbc/logging/BaseLoggingClass.java b/src/main/java/org/openecomp/dmaapbc/logging/BaseLoggingClass.java
new file mode 100644
index 0000000..9afd7b6
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/logging/BaseLoggingClass.java
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.logging;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+public abstract class BaseLoggingClass {
+ protected EELFLogger logger = EELFManager.getInstance().getLogger( super.getClass());
+ protected static final EELFLogger appLogger = EELFManager.getInstance().getApplicationLogger();
+ protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+ protected static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+ protected static final EELFLogger errorLogger = EELFManager.getInstance().getErrorLogger();
+ protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
+ protected static final EELFLogger serverLogger = EELFManager.getInstance().getServerLogger();
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/logging/DmaapbcLogMessageEnum.java b/src/main/java/org/openecomp/dmaapbc/logging/DmaapbcLogMessageEnum.java
new file mode 100644
index 0000000..08f7c4c
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/logging/DmaapbcLogMessageEnum.java
@@ -0,0 +1,81 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.logging;
+
+import com.att.eelf.i18n.EELFResourceManager;
+import com.att.eelf.i18n.EELFResolvableErrorEnum;
+
+public enum DmaapbcLogMessageEnum implements EELFResolvableErrorEnum {
+//0xx sample stock messages
+ MESSAGE_SAMPLE_NOARGS,
+ MESSAGE_SAMPLE_ONE_ARG,
+ MESSAGE_SAMPLE_TWO_ARGS,
+
+// 1xx Permission Errors
+ AAF_CREDENTIAL_ERROR,
+ CODEC_CREDENTIAL_ERROR,
+ PE_AUTHENTICATION_ERROR,
+ DR_PROV_AUTHORIZATION,
+
+// 2xx Availability Errors/Timeouts
+ DRIVER_UNAVAILABLE,
+ HTTP_CONNECTION_ERROR,
+ HTTP_CONNECTION_EXCEPTION,
+ UNKNOWN_HOST_EXCEPTION,
+
+
+// 3xx Data Errors
+ IO_EXCEPTION,
+ SSL_HANDSHAKE_ERROR,
+ AAF_UNEXPECTED_RESPONSE,
+ PE_EXCEPTION,
+ SOCKET_EXCEPTION,
+ JSON_PARSING_ERROR,
+ DECRYPT_IO_ERROR,
+
+//4xx Schema Errors
+ DB_UPGRADE_ERROR,
+ DB_INIT_ERROR,
+ DB_UPDATE_ERROR,
+ DB_ACCESS_ERROR,
+ DB_FIELD_INIT_ERROR,
+ DB_ACCESS_INIT_ERROR,
+ DB_NO_FIELD_HANDLER,
+
+
+// 5xx Business Process Errors
+ PREREQ_DMAAP_OBJECT,
+ PROV_OUT_OF_SYNC,
+ MM_CIRCULAR_REF,
+ TOPIC_CREATE_ERROR,
+ INGRESS_CREATE_ERROR,
+ FEED_PUB_PROV_ERROR,
+ FEED_SUB_PROV_ERROR,
+ MM_PUBLISH_ERROR,
+ EGRESS_CREATE_ERROR,
+
+// 900 Unknown Errors
+ UNEXPECTED_CONDITION;
+
+ static {
+ EELFResourceManager.loadMessageBundle("logmsg");
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/logging/logmsg.properties b/src/main/java/org/openecomp/dmaapbc/logging/logmsg.properties
new file mode 100644
index 0000000..0e1222b
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/logging/logmsg.properties
@@ -0,0 +1,240 @@
+###
+# ============LICENSE_START=======================================================
+# OpenECOMP - org.openecomp.dmaapbc
+# ================================================================================
+# 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=========================================================
+###
+
+# 0xx sample stock messages
+MESSAGE_SAMPLE_NOARGS=\
+ 01|\
+ Ignore: demo msg with no arg|\
+ No resolution|\
+ An example of a message with no args
+
+MESSAGE_SAMPLE_ONE_ARG=\
+ 02|\
+ Ignore: demo msg with 1 arg {0}|\
+ No resolution|\
+ An example of a message with 1 arg
+
+MESSAGE_SAMPLE_TWO_ARGS=\
+ 03|\
+ Ignore: demo msg with arg1 {0} and arg2 {1}|\
+ No resolution|\
+ An example of a message with 2 args
+
+
+
+# 1xx Permission Errors
+AAF_CREDENTIAL_ERROR=\
+ 101|\
+ Service credentials ({0}) are not valid for AAF connection|\
+ Check credentials are valid in appropriate AAF environment.|\
+ Connection to AAF was not allowed for the specified credentials.
+
+CODEC_CREDENTIAL_ERROR=\
+ 102|\
+ Failed to read CredentialCodecKeyfile {0} with error {1}|\
+ Check if CredentialCodecKeyfile has been corrupted.|\
+ CredentialCodecKeyfile is not in sync with application
+
+PE_AUTHENTICATION_ERROR=\
+ 103|\
+ User {0} perms {1} caught PolicyEngineException {1}|\
+ User needs to be granted perm before access.|\
+ Identified user was not authorized for the specific perm.
+
+DR_PROV_AUTHORIZATION=\
+ 104|\
+ Not authorized for API {0}|\
+ Bus Controller host needs to be provisioned as a Node and an AUTHORIZED_HOST.|\
+ DR Prov indicates that Bus Controller host is not authorized for the specified API.
+
+# 2xx Availability Errors/Timeouts
+DRIVER_UNAVAILABLE=\
+ 201|\
+ Unable to load driver {0}. Error {1}|\
+ Check that specified driver is installed and accessible to application.|\
+ The software attempted to load a driver and was not successful.
+
+HTTP_CONNECTION_ERROR=\
+ 202|\
+ Exception during openConnection to {0} failed with {1}|\
+ Confirm syntax of URL is correct and network access from this host is allowed.|\
+ An attempt to URL.openConnection failed
+
+HTTP_CONNECTION_EXCEPTION=\
+ 203|\
+ Connection to {0} refused because {1}|\
+ Check if this is the proper server.|\
+ Application caught a ConnectionException
+
+UNKNOWN_HOST_EXCEPTION=\
+ 204|\
+ Caught exception {0} attempting to access {1}|\
+ Confirm that host is in DNS|\
+ Caught UnknownHostException when connecting to the designated host name.
+
+# 3xx Data Errors
+IO_EXCEPTION=\
+ 301|\
+ IOexception {0}|\
+ No resolution.|\
+ Generic IO Exception condition
+
+SSL_HANDSHAKE_ERROR=\
+ 302|\
+ SSLHandshakeException from URL {0}|\
+ Confirm that target host has proper SSL certificate for DNS value used to access it.|\
+ SSLHandshake exception thrown on HttpsURLConnection method
+
+AAF_UNEXPECTED_RESPONSE=\
+ 303|\
+ rc= {0} :unable to {1} for {2}|\
+ Check configuration for this AAF instance.|\
+ Unexpected response from AAF for the intended action
+
+PE_EXCEPTION=\
+ 304|\
+ Trying to read {0} and caught PolicyEngineException {1}|\
+ Check config file exists and has proper settings.|\
+ An unexpected exception from PE was caught.
+
+SOCKET_EXCEPTION=\
+ 305|\
+ Caught exception {0} while {1}|\
+ No comment.|\
+ An unexpected socket exception was caught while performing the specified action.
+
+JSON_PARSING_ERROR=\
+ 306|\
+ ParsingException for object {0} using data:{1}|\
+ No comment.|\
+ The JSON data provided to the object was not in the expected format
+
+ DECRYPT_IO_ERROR=\
+ 307|\
+ IO Error attempting using {0} to decrypt value {1}|\
+ Check permissions of file set for property CredentialCodecKeyfile.|\
+ Error using codec file for decryption.
+
+# 4xx Schema Errors
+
+DB_UPGRADE_ERROR=\
+ 401|\
+ Problem updating DB schema. {0}|\
+ Examine stack trace for clues.|\
+ The software was not able to process the sql file resources in the jar file.
+
+DB_INIT_ERROR=\
+ 402|\
+ Error initializing database access: {0}|\
+ Correct configuration based on detail.|\
+ The software was not able initialize objects from the DB.
+
+DB_UPDATE_ERROR=\
+ 403|\
+ Error while updating DB: {0}|\
+ Correct configuration based on detail.|\
+ The software was not able to update record(s) in the DB.
+
+DB_ACCESS_ERROR=\
+ 404|\
+ Database access problem: {0}|\
+ Correct configuration based on detail.|\
+ An exception related to DB access was caught and logged.
+
+DB_FIELD_INIT_ERROR=\
+ 405|\
+ Problem setting field {0} to {1} statement is {2}|\
+ DB schema may be out of sync with code.|\
+ SQLDate.set() failed to set field value.
+
+DB_ACCESS_INIT_ERROR=\
+ 406|\
+ Problem initializing sql access methods {0} |\
+ No comment.|\
+ Error encountered while initializing basic field types.
+
+DB_NO_FIELD_HANDLER=\
+ 407|\
+ No field handler for class {0} field {1} index {2} type {3}|\
+ No comment.|\
+ Missing field handler for specified code.
+
+
+# 5xx Business Process Errors
+PREREQ_DMAAP_OBJECT=\
+ 501|\
+ Attempt to access {} before dmaap object resource is available.|\
+ No remediation.|\
+ The dmaap object needs to be defined before attempting the desired access
+
+PROV_OUT_OF_SYNC=\
+ 502|\
+ Resource {0} with id {1} was not in sync with DR Prov.\
+ May need manual sync steps.\
+ The Bus Controller view of a resource does not match what was found on DR Prov
+
+MM_CIRCULAR_REF=\
+ 503|\
+ Trying to add edge from source {0} into Map belonging to {1}|\
+ May indicate a provisioning error.|\
+ Some error in logic is attempting to add an edge to a Map that is an edge.
+
+TOPIC_CREATE_ERROR=\
+ 504|\
+ Unable to create topic for {0} err={1} fields={2} msg={3}|\
+ No comment.|\
+ Reporting an error caught while creating a topic
+
+INGRESS_CREATE_ERROR=\
+ 505|\
+ rc={0} unable to create ingress rule for {1} on feed {2} to {3}|\
+ No comment.|\
+ Unexpected response while creating ingress rule
+
+FEED_PUB_PROV_ERROR=\
+ 506|\
+ For feed {0} resulting set of publishers do not match requested set of publishers {1} vs {2}|\
+ No comment.|\
+ The number of publishers on a feed do not match after provisioning request.
+
+FEED_SUB_PROV_ERROR=\
+ 507|\
+ For feed {0} i={1} url={2} err={3}|\
+ No comment.|\
+ An error occurred when provisioning subs on a feed.
+
+MM_PUBLISH_ERROR=\
+ 508|\
+ Unable to publish {0} provisioning message. rc={1} msg={2}|\
+ No comment.|\
+ An error occurred when publishing a message to MM
+
+EGRESS_CREATE_ERROR=\
+ 509|\
+ rc={0} unable to create egress rule for {1} on feed {2} to {3}|\
+ No comment.|\
+ Unexpected response while creating egress rule
+
+# 900 Unknown Errors
+UNEXPECTED_CONDITION=\
+ 901|\
+ Unexpected exception encountered {0}|\
+ No resolution|\
+ An error to catch unexpected conditions. Hopefully a clue in the stack trace.
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java b/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java
index 2e3e894..3343954 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java
@@ -22,12 +22,11 @@ package org.openecomp.dmaapbc.model;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.util.RandomString;
@XmlRootElement
public class DR_Pub extends DmaapObject {
- static final Logger logger = Logger.getLogger(DR_Pub.class);
+
private String dcaeLocationName;
private String username;
private String userpwd;
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java b/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java
index 0184a14..ce90e5a 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java
@@ -24,14 +24,13 @@ import java.nio.charset.StandardCharsets;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
@XmlRootElement
public class DR_Sub extends DmaapObject {
- static final Logger logger = Logger.getLogger(DR_Sub.class);
private String dcaeLocationName;
private String username;
@@ -100,7 +99,7 @@ public class DR_Sub extends DmaapObject {
try {
jsonObj = (JSONObject) parser.parse( json );
} catch ( ParseException pe ) {
- logger.error( "Error parsing provisioning data: " + json );
+ errorLogger.error( DmaapbcLogMessageEnum.JSON_PARSING_ERROR, "DR_Sub", json );
this.setStatus( DmaapObject_Status.INVALID );
return;
}
@@ -194,13 +193,40 @@ public class DR_Sub extends DmaapObject {
// in DR 3.0, API v2.1 a new groupid field is added. We are not using this required field so just set it to 0.
// we send this regardless of DR Release because older versions of DR seem to safely ignore it
// and soon those versions won't be around anyway...
- String postJSON = String.format("{\"delivery\": {\"url\": \"%s\", \"user\": \"%s\", \"password\": \"%s\", \"use100\": \"%s\"}, \"metadataOnly\": false, \"groupid\": \"0\"}",
+ // Similarly, in the 1704 Release, a new subscriber attribute "follow_redirect" was introduced.
+ // We are setting it to "true" because that is the general behavior desired in OpenDCAE.
+ // But it is really a no-op for OpenDCAE because we've deployed DR with the SYSTEM-level parameter for FOLLOW_REDIRECTS set to true.
+ // In the event we abandon that, then setting the sub attribute to true will be a good thing.
+ // TODO:
+ // - introduce Bus Controller API support for these attributes
+ // - store the default values in the DB
+ String postJSON = String.format("{\"delivery\": {\"url\": \"%s\", \"user\": \"%s\", \"password\": \"%s\", \"use100\": \"%s\"}, \"metadataOnly\": %s, \"groupid\": \"%s\", \"follow_redirect\": %s }",
this.getDeliveryURL(),
this.getUsername(),
this.getUserpwd(),
- this.isUse100() );
+ this.isUse100(),
+ "false",
+ "0",
+ "true");
logger.info( postJSON );
return postJSON;
}
+
+ @Override
+ public String toString() {
+ String rc = String.format ( "DR_Sub: {dcaeLocationName=%s username=%s userpwd=%s feedId=%s deliveryURL=%s logURL=%s subid=%s use100=%s suspended=%s owner=%s}",
+ dcaeLocationName,
+ username,
+ userpwd,
+ feedId,
+ deliveryURL,
+ logURL,
+ subId,
+ use100,
+ suspended,
+ owner
+ );
+ return rc;
+ }
}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java b/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java
index 362c184..b6478fe 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java
@@ -26,8 +26,7 @@ import org.apache.log4j.Logger;
@XmlRootElement
public class Dmaap extends DmaapObject {
- static final Logger logger = Logger.getLogger(Dmaap.class);
-
+
private String version;
private String topicNsRoot;
private String dmaapName;
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java b/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java
index 39d4181..b34dabc 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java
@@ -20,14 +20,18 @@
package org.openecomp.dmaapbc.model;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.xml.bind.annotation.XmlRootElement;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+
@XmlRootElement
-public abstract class DmaapObject {
+public abstract class DmaapObject extends BaseLoggingClass {
protected Date lastMod;
protected DmaapObject_Status status;
@@ -65,4 +69,59 @@ public abstract class DmaapObject {
}
return false;
}
+
+ /*
+ * TODO: get this working so arrays and sub-class within an Object can be logged
+ *
+ public String toString() {
+ return classToString( this );
+ }
+
+ private String classToString( Object obj ) {
+ Field[] fields = obj.getClass().getDeclaredFields();
+ StringBuilder res = new StringBuilder( "{");
+ boolean first = true;
+ for ( Field field: fields ) {
+ logger.info( field.getName() + " toString=" + field.toString() + " toGenericString=" + field.toGenericString());
+ if ( first ) {
+ first = false;
+ } else {
+ res.append( ", ");
+ }
+
+
+ field.setAccessible(true); // avoid IllegalAccessException
+
+
+ Class<?> t = field.getType();
+
+ if ( t == String.class ) {
+ res.append( "\"" ).append( field.getName() ).append( "\": \"");
+
+ try {
+ res.append(field.get(this));
+ } catch ( IllegalAccessException iae) {
+ res.append( "UNK(iae)");
+ } catch (IllegalArgumentException iae2 ) {
+ res.append( "UNK(iae2)");
+ } catch ( NullPointerException npe ) {
+ res.append( "UNK(npe)");
+ } catch ( ExceptionInInitializerError eie ) {
+ res.append( "UNK(eie)");
+ }
+ res.append( "\"");
+ } else if ( t == ArrayList.class ){
+ res.append( "[");
+ res.append( classToString( field ));
+ res.append( "]");
+
+ }
+ }
+ res.append( "}");
+ return( res.toString());
+
+
+ }
+ */
+
}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Feed.java b/src/main/java/org/openecomp/dmaapbc/model/Feed.java
index c445b65..5d89331 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/Feed.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/Feed.java
@@ -23,21 +23,14 @@ package org.openecomp.dmaapbc.model;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
-
-
import org.json.simple.*;
import org.json.simple.parser.*;
import org.openecomp.dmaapbc.service.DmaapService;
-import org.openecomp.dmaapbc.util.RandomString;
@XmlRootElement
public class Feed extends DmaapObject {
- static final Logger logger = Logger.getLogger(Feed.class);
-
private String feedId;
@@ -276,4 +269,31 @@ public class Feed extends DmaapObject {
return ret;
}
+ @Override
+ public String toString() {
+ String rc = String.format ( "Feed: {feedId=%s feedName=%s feedVersion=%s feedDescription=%s owner=%s asprClassification=%s publishURL=%s subscriberURL=%s suspended=%s logURL=%s formatUuid=%s}",
+ feedId,
+ feedName,
+ feedVersion,
+ feedDescription,
+ owner,
+ asprClassification,
+ publishURL,
+ subscribeURL,
+ suspended,
+ logURL,
+ formatUuid
+
+
+ );
+
+ for( DR_Pub pub: pubs) {
+ rc += "\n" + pub.toString();
+ }
+
+ for( DR_Sub sub: subs ) {
+ rc += "\n" + sub.toString();
+ }
+ return rc;
+ }
}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java b/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java
index 684424a..73f9f3e 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java
@@ -24,12 +24,11 @@ import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
+
import org.openecomp.dmaapbc.database.DatabaseClass;
@XmlRootElement
public class MR_Client extends DmaapObject {
- static final Logger logger = Logger.getLogger(MR_Client.class);
private String dcaeLocationName;
private String topicURL;
@@ -43,7 +42,7 @@ public class MR_Client extends DmaapObject {
this.mrClientId = DatabaseClass.getNextClientId();
this.lastMod = new Date();
this.setLastMod();
- logger.debug( "MR_Client constructor " + this.lastMod );
+ debugLogger.debug( "MR_Client constructor " + this.lastMod );
}
@@ -65,7 +64,7 @@ public class MR_Client extends DmaapObject {
this.setStatus( DmaapObject_Status.NEW );
this.mrClientId = DatabaseClass.getNextClientId();
this.setLastMod();
- logger.debug( "MR_Client constructor w initialization " + this.lastMod );
+ debugLogger.debug( "MR_Client constructor w initialization " + this.lastMod );
}
public String getDcaeLocationName() {
diff --git a/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java b/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java
index fcaf007..c74dc4e 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java
@@ -21,14 +21,14 @@
package org.openecomp.dmaapbc.model;
import java.util.Date;
+
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
@XmlRootElement
public class MR_Cluster extends DmaapObject {
- static final Logger logger = Logger.getLogger(MR_Cluster.class);
+
private String dcaeLocationName;
private String fqdn;
private String[] hosts;
@@ -49,7 +49,7 @@ public class MR_Cluster extends DmaapObject {
this.topicPort = defaultTopicPort;
this.lastMod = new Date();
- logger.info( "MR_Cluster constructor " + this.lastMod );
+ debugLogger.debug( "MR_Cluster constructor " + this.lastMod );
}
@@ -65,7 +65,7 @@ public class MR_Cluster extends DmaapObject {
this.topicProtocol = defaultTopicProtocol;
this.topicPort = defaultTopicPort;
- logger.info( "MR_Cluster constructor w initialization complete" + this.lastMod );
+ debugLogger.debug( "MR_Cluster constructor w initialization complete" + this.lastMod );
}
public String getDcaeLocationName() {
@@ -108,16 +108,21 @@ public class MR_Cluster extends DmaapObject {
this.topicPort = topicPort;
}
- public String genTopicURL( String topic ) {
+
+
+ public String genTopicURL(String overideFqdn, String topic) {
+
StringBuilder str = new StringBuilder( topicProtocol );
str.append("://")
- .append(fqdn)
+ .append( overideFqdn != null ? overideFqdn : fqdn)
.append(":")
.append(topicPort)
.append("/events/")
.append(topic);
return str.toString();
+
+
}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java b/src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java
index 828e9e0..37885c5 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java
@@ -25,6 +25,7 @@ import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.service.MirrorMakerService;
public class MirrorMaker extends DmaapObject {
@@ -63,7 +64,7 @@ public class MirrorMaker extends DmaapObject {
public void addVector( String fqtn, String source, String target ) {
logger.info( "addVector: fqtn=" + fqtn + " source=" + source + " target=" + target );
if ( ! sourceCluster.equals( source ) ){
- logger.error( "trying to add edge from source " + source + " into Map belonging to " + sourceCluster );
+ errorLogger.error( DmaapbcLogMessageEnum.MM_CIRCULAR_REF, source, sourceCluster );
}
vectors.add(new ReplicationVector( fqtn, source, target ));
}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/ReplicationType.java b/src/main/java/org/openecomp/dmaapbc/model/ReplicationType.java
new file mode 100644
index 0000000..b7a49c5
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/model/ReplicationType.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.model;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+
+@XmlRootElement
+public enum ReplicationType {
+ REPLICATION_NOT_SPECIFIED(0),
+ REPLICATION_NONE(1),
+ REPLICATION_EDGE_TO_CENTRAL(10),
+ REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL(110),
+ REPLICATION_CENTRAL_TO_EDGE(20),
+ REPLICATION_CENTRAL_TO_GLOBAL(21),
+ REPLICATION_GLOBAL_TO_CENTRAL(30),
+ REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE(120);
+
+ private int value;
+ private static Map map = new HashMap<>();
+
+ private ReplicationType(int value) {
+ this.value = value;
+ }
+
+ static {
+ for (ReplicationType repType : ReplicationType.values()) {
+ map.put(repType.value, repType);
+ }
+ }
+
+ public static ReplicationType valueOf(int repType) {
+ return (ReplicationType) map.get(repType);
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ static public ReplicationType Validator( String input ){
+
+ ReplicationType t;
+ try {
+ t = ReplicationType.valueOf( input );
+ } catch ( IllegalArgumentException e ) {
+ t = REPLICATION_NOT_SPECIFIED;
+ }
+ return t;
+ }
+
+ public boolean involvesGlobal() {
+ if ( this.compareTo(REPLICATION_CENTRAL_TO_GLOBAL) == 0 ||
+ this.compareTo(REPLICATION_GLOBAL_TO_CENTRAL) == 0 ||
+ this.compareTo(REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL) == 0 ||
+ this.compareTo(REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE) == 0) {
+ return true;
+ }
+ return false;
+ }
+
+
+
+} \ No newline at end of file
diff --git a/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java b/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java
index 60f25e5..623d9f9 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java
@@ -19,13 +19,9 @@
*/
package org.openecomp.dmaapbc.model;
-import org.apache.log4j.Logger;
public class ReplicationVector {
-
-
- static final Logger logger = Logger.getLogger(ReplicationVector.class);
public enum ReplicationVector_Status {
EMPTY,
NEW,
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Topic.java b/src/main/java/org/openecomp/dmaapbc/model/Topic.java
index 3d9ea6f..2c817fd 100644
--- a/src/main/java/org/openecomp/dmaapbc/model/Topic.java
+++ b/src/main/java/org/openecomp/dmaapbc/model/Topic.java
@@ -26,22 +26,20 @@ import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.service.DmaapService;
@XmlRootElement
public class Topic extends DmaapObject {
- static final Logger logger = Logger.getLogger(Topic.class);
private String fqtn;
private String topicName;
private String topicDescription;
- // I don't think this field is needed for this object. Rather, it applies to each MR_Client
- //private String dcaeLocationName;
private String tnxEnabled;
private String owner;
private String formatUuid;
+ private ReplicationType replicationCase;
+ private String globalMrURL; // optional: URL of global MR to replicate to/from
private ArrayList<MR_Client> clients;
@@ -52,7 +50,14 @@ public class Topic extends DmaapObject {
//
// utility function to generate the FQTN of a topic
public static String genFqtn( String name ) {
- String ret = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + name;
+ CharSequence signal = ".";
+ String ret;
+ if ( name.contains( signal )) {
+ // presence of a dot indicates the name is already fully qualified
+ ret = name;
+ } else {
+ ret = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + name;
+ }
return ret;
}
@@ -62,8 +67,9 @@ public class Topic extends DmaapObject {
super();
this.clients = new ArrayList<MR_Client>();
this.lastMod = new Date();
+ this.replicationCase = ReplicationType.Validator("none");
this.setLastMod();
- logger.info( "Topic constructor " + this.lastMod );
+ logger.debug( "Topic constructor " + this.lastMod );
}
public Topic(String fqtn, String topicName, String topicDescription,
String tnxEnabled, String owner) {
@@ -76,7 +82,8 @@ public class Topic extends DmaapObject {
this.owner = owner;
this.setLastMod();
this.setStatus( DmaapObject_Status.NEW );
- logger.info( "Topic constructor " + this.getLastMod() );
+ this.replicationCase = ReplicationType.Validator("none");
+ logger.debug( "Topic constructor " + this.getLastMod() );
}
public String getFqtn() {
return fqtn;
@@ -96,14 +103,7 @@ public class Topic extends DmaapObject {
public void setTopicDescription(String topicDescription) {
this.topicDescription = topicDescription;
}
- /*
- public String getDcaeLocationName() {
- return dcaeLocationName;
- }
- public void setDcaeLocationName(String dcaeLocationName) {
- this.dcaeLocationName = dcaeLocationName;
- }
- */
+
public String getTnxEnabled() {
return tnxEnabled;
}
@@ -147,6 +147,34 @@ public class Topic extends DmaapObject {
}
+ public ReplicationType getReplicationCase() {
+ return replicationCase;
+ }
+
+
+
+ /*
+ public void setReplicationCase(String val) {
+ this.replicationCase = ReplicationType.Validator(val);
+ }
+ */
+
+ public void setReplicationCase(ReplicationType t) {
+ this.replicationCase = t;
+ }
+
+
+ public String getGlobalMrURL() {
+ return globalMrURL;
+ }
+
+
+
+ public void setGlobalMrURL(String globalMrURL) {
+ this.globalMrURL = globalMrURL;
+ }
+
+
public String toProvJSON() {
StringBuilder str = new StringBuilder();
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java b/src/main/java/org/openecomp/dmaapbc/resources/Authorization.java
index a2a9e71..f98db39 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/Authorization.java
@@ -1,45 +1,35 @@
-/*-
+/*-
* ============LICENSE_START=======================================================
* OpenECOMP - org.openecomp.dmaapbc
* ================================================================================
* 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
+ * 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.openecomp.dmaapbc.resources;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.ws.rs.core.Response.Status;
-
-import org.openecomp.dmaapbc.model.ApiError;
-
-//TODO: Retire this class
-public class ApiResource {
-
- static void checkRequired( String name, Object val, String expr, ApiError err ) throws RequiredFieldException {
- if ( val == null ) {
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage("missing required field");
- err.setFields( name );
- throw new RequiredFieldException();
- }
-
-
- }
-
-
-}
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.dmaapbc.resources;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+
+import javax.ws.rs.NameBinding;
+
+// @Authorization annotation
+@NameBinding
+@Retention(RetentionPolicy.RUNTIME)
+@Target({ElementType.METHOD, ElementType.TYPE})
+public @interface Authorization {
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/AuthorizationFilter.java b/src/main/java/org/openecomp/dmaapbc/resources/AuthorizationFilter.java
new file mode 100644
index 0000000..85f7aba
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/resources/AuthorizationFilter.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.resources;
+
+import java.io.IOException;
+
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+
+import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+
+@Authorization
+public class AuthorizationFilter implements ContainerRequestFilter {
+
+
+
+ @Override
+ public void filter(ContainerRequestContext requestContext)
+ throws IOException {
+
+ ApiService apiResp = new ApiService()
+ .setAuth( requestContext.getHeaderString("Authorization") )
+ .setUriPath(requestContext.getUriInfo().getPath())
+ .setHttpMethod( requestContext.getMethod() )
+ .setRequestId( requestContext.getHeaderString("X-ECOMP-RequestID") );
+
+ try {
+ apiResp.checkAuthorization();
+ } catch ( AuthenticationErrorException ae ) {
+ requestContext.abortWith( apiResp.unauthorized( apiResp.getErr().getMessage() ) );
+ return ;
+ } catch ( Exception e ) {
+ requestContext.abortWith( apiResp.unavailable() );
+ return;
+ }
+
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java b/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java
index 0c5782a..a9df73e 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java
@@ -20,6 +20,11 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
@@ -34,38 +39,40 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.BrTopic;
+import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.model.MirrorMaker;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.MirrorMakerService;
@Path("/bridge")
+@Api( value= "bridge", description = "Endpoint for retreiving MR Bridge metrics" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class BridgeResource {
-
- static final Logger logger = Logger.getLogger(BridgeResource.class);
+@Authorization
+public class BridgeResource extends BaseLoggingClass {
private MirrorMakerService mmService = new MirrorMakerService();
@GET
+ @ApiOperation( value = "return BrTopic details",
+ notes = "Returns array of `BrTopic` objects.",
+ response = BrTopic.class)
+@ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+})
public Response getBridgedTopics(@QueryParam("source") String source,
- @QueryParam("target") String target,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ @QueryParam("target") String target){
ApiService check = new ApiService();
+
BrTopic brTopic = new BrTopic();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
-
logger.info( "getBridgeTopics():" + " source=" + source + ", target=" + target);
// System.out.println("getBridgedTopics() " + "source=" + source + ", target=" + target );
if (source != null && target != null) { // get topics between 2 bridged locations
@@ -95,17 +102,15 @@ public class BridgeResource {
logger.info( "topicCount [all locations]: " + totCnt );
brTopic.setTopicCount(totCnt);
-// System.out.println("BridgeResource() d.getBrSource()=" + d.getBrSource());
+
}
else {
-// System.out.println("A source or target Parameter is missing");
-// return Response.serverError().build();
+
logger.error( "source or target is missing");
- return Response.status(Status.BAD_REQUEST)
- .entity( "Either 2 locations or no location must be provided")
- .build();
+ check.setCode(Status.BAD_REQUEST.getStatusCode());
+ check.setMessage("Either 2 locations or no location must be provided");
+ return check.error();
}
- return Response.ok(brTopic).
- build();
+ return check.success(brTopic);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java
index 73506f6..f481856 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java
@@ -20,164 +20,164 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Node;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.DR_NodeService;
@Path("/dr_nodes")
+@Api( value= "dr_nodes", description = "Endpoint for a Data Router Node server" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class DR_NodeResource extends ApiResource {
- static final Logger logger = Logger.getLogger(DR_NodeResource.class);
+@Authorization
+public class DR_NodeResource extends BaseLoggingClass {
+
DR_NodeService dr_nodeService = new DR_NodeService();
@GET
- public List<DR_Node> getDr_Nodes(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return DR_Node details",
+ notes = "Returns array of `DR_Node` object array. Need to add filter by dcaeLocation.",
+ response = DR_Node.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Node.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getDr_Nodes() {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
- return dr_nodeService.getAllDr_Nodes();
+
+ List<DR_Node> nodes = dr_nodeService.getAllDr_Nodes();
+
+ GenericEntity<List<DR_Node>> list = new GenericEntity<List<DR_Node>>(nodes) {
+ };
+ return resp.success(list);
}
@POST
- public Response addDr_Node( DR_Node node,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return DR_Node details",
+ notes = "create a `DR_Node` in a *dcaeLocation*. Note that multiple `DR_Node`s may exist in the same `dcaeLocation`.",
+ response = DR_Node.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Node.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addDr_Node(
+ DR_Node node
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "dcaeLocation", node.getDcaeLocationName(), "");
resp.required( "fqdn", node.getFqdn(), "");
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST).entity( resp ).build();
+ resp.setCode(Status.BAD_REQUEST.getStatusCode());
+ resp.setMessage("missing required field");
+ resp.setFields("dcaeLocation, fqdn");
+
+ return resp.error();
}
DR_Node nNode = dr_nodeService.addDr_Node(node, resp.getErr());
if ( resp.getErr().is2xx()) {
- return Response.status(Status.OK.getStatusCode())
- .entity(nNode)
- .build();
+ return resp.success(nNode);
}
- return Response.status( resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
@PUT
+ @ApiOperation( value = "return DR_Node details",
+ notes = "Update a single `DR_Node` object.",
+ response = DR_Node.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Node.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{fqdn}")
- public Response updateDr_Node( @PathParam("fqdn") String name, DR_Node node,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response updateDr_Node(
+ @PathParam("fqdn") String name,
+ DR_Node node
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "dcaeLocation", name, "");
resp.required( "fqdn", node.getFqdn(), "");
} catch ( RequiredFieldException rfe ) {
- logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST).entity( resp ).build();
+ return resp.error();
}
node.setFqdn(name);
DR_Node nNode = dr_nodeService.updateDr_Node(node, resp.getErr());
if ( resp.getErr().is2xx()) {
- return Response.status(Status.OK.getStatusCode())
- .entity(nNode)
- .build();
+ return resp.success(nNode);
}
- return Response.status( resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
@DELETE
+ @ApiOperation( value = "No Content",
+ notes = "Delete a single `DR_Node` object.",
+ response = DR_Node.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Node.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{fqdn}")
- public Response deleteDr_Node( @PathParam("fqdn") String name,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ public Response deleteDr_Node(
+ @PathParam("fqdn") String name
+ ){
ApiService resp = new ApiService();
try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
- try {
resp.required( "fqdn", name, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST).entity( resp ).build();
+ return resp.error();
}
dr_nodeService.removeDr_Node(name, resp.getErr());
if ( resp.getErr().is2xx() ) {
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null);
}
- return Response.status( resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
@GET
+ @ApiOperation( value = "return DR_Node details",
+ notes = "Retrieve a single `DR_Node` object.",
+ response = DR_Node.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Node.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{fqdn}")
- public Response get( @PathParam("fqdn") String name,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response get(
+ @PathParam("fqdn") String name
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
DR_Node nNode = dr_nodeService.getDr_Node( name, resp.getErr() );
if ( resp.getErr().is2xx() ) {
- return Response.status(Status.OK.getStatusCode())
- .entity(nNode)
- .build();
+ return resp.success(nNode);
}
- return Response.status( resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java
index 108a18b..0078a6d 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java
@@ -20,6 +20,11 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -27,20 +32,17 @@ import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.Feed;
@@ -50,75 +52,65 @@ import org.openecomp.dmaapbc.service.FeedService;
@Path("/dr_pubs")
+@Api( value= "dr_pubs", description = "Endpoint for a Data Router client that implements a Publisher" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class DR_PubResource extends ApiResource {
- static final Logger logger = Logger.getLogger(DR_PubResource.class);
+@Authorization
+public class DR_PubResource extends BaseLoggingClass {
+
DR_PubService dr_pubService = new DR_PubService();
@GET
- public List<DR_Pub> getDr_Pubs(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return DR_Pub details",
+ notes = "Returns array of `DR_Pub` objects. Add filter for feedId.",
+ response = DR_Pub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getDr_Pubs() {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
+
logger.info( "Entry: GET /dr_pubs");
- return dr_pubService.getAllDr_Pubs();
+ List<DR_Pub> pubs = dr_pubService.getAllDr_Pubs();
+
+ GenericEntity<List<DR_Pub>> list = new GenericEntity<List<DR_Pub>>(pubs) {
+ };
+ return resp.success(list);
}
@POST
- public Response addDr_Pub( DR_Pub pub,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return DR_Pub details",
+ notes = "create a DR Publisher in the specified environment.",
+ response = DR_Pub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addDr_Pub(
+ DR_Pub pub
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
logger.info( "Entry: POST /dr_pubs");
ApiError err = new ApiError();
try {
- checkRequired( "feedId", pub.getFeedId(), "", err);
- checkRequired( "dcaeLocationName", pub.getDcaeLocationName(), "", err);
+ resp.required( "feedId", pub.getFeedId(), "");
+ resp.required( "dcaeLocationName", pub.getDcaeLocationName(), "");
} catch ( RequiredFieldException rfe ) {
logger.debug( err.toString() );
- return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ return resp.error();
}
FeedService feeds = new FeedService();
Feed fnew = feeds.getFeed( pub.getFeedId(), err);
if ( fnew == null ) {
logger.info( "Specified feed " + pub.getFeedId() + " not known to Bus Controller");
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ return resp.error();
}
ArrayList<DR_Pub> pubs = fnew.getPubs();
logger.info( "num existing pubs before = " + pubs.size() );
-/*
- DR_Pub pnew = new DR_Pub( pub.getDcaeLocationName());
- pnew.setFeedId(pub.getFeedId());
- pnew.setPubId(pub.getPubId());
- String tmp = pub.getUsername();
- if ( tmp != null ) {
- pub.setUsername(tmp);
- }
- tmp = pub.getUserpwd();
- if ( tmp != null ) {
- pub.setUserpwd(tmp);
- }
- pnew.setNextPubId();
-*/
-
logger.info( "update feed");
pub.setNextPubId();
@@ -133,138 +125,117 @@ public class DR_PubResource extends ApiResource {
fnew = feeds.updateFeed( fnew, err );
if ( ! err.is2xx()) {
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ return resp.error();
}
pubs = fnew.getPubs();
logger.info( "num existing pubs after = " + pubs.size() );
DR_Pub pnew = dr_pubService.getDr_Pub(pub.getPubId(), err);
- return Response.status(Status.CREATED.getStatusCode())
- .entity(pnew)
- .build();
+ return resp.success(Status.CREATED.getStatusCode(), pnew);
}
@PUT
+ @ApiOperation( value = "return DR_Pub details",
+ notes = "update a DR Publisher in the specified environment. Update a `DR_Pub` object by pubId",
+ response = DR_Pub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{pubId}")
- public Response updateDr_Pub( @PathParam("pubId") String name, DR_Pub pub,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response updateDr_Pub(
+ @PathParam("pubId") String name,
+ DR_Pub pub
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
logger.info( "Entry: PUT /dr_pubs");
pub.setPubId(name);
DR_Pub res = dr_pubService.updateDr_Pub(pub);
- return Response.ok()
- .entity(res)
- .build();
+ return resp.success(res);
}
@DELETE
+ @ApiOperation( value = "return DR_Pub details",
+ notes = "delete a DR Publisher in the specified environment. Delete a `DR_Pub` object by pubId",
+ response = DR_Pub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{pubId}")
- public Response deleteDr_Pub( @PathParam("pubId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
- logger.info( "Entry: DELETE /dr_pubs");
+ public Response deleteDr_Pub(
+ @PathParam("pubId") String id
+ ){
+
ApiService resp = new ApiService();
+
try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
- ApiError err = new ApiError();
- try {
- checkRequired( "feedId", id, "", err);
+ resp.required( "pubId", id, "");
} catch ( RequiredFieldException rfe ) {
- logger.debug( err.toString() );
- return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ return resp.error();
}
- DR_Pub pub = dr_pubService.getDr_Pub( id, err );
- if ( ! err.is2xx()) {
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ DR_Pub pub = dr_pubService.getDr_Pub( id, resp.getErr() );
+ if ( ! resp.getErr().is2xx()) {
+ return resp.error();
}
FeedService feeds = new FeedService();
- Feed fnew = feeds.getFeed( pub.getFeedId(), err);
+ Feed fnew = feeds.getFeed( pub.getFeedId(), resp.getErr() );
if ( fnew == null ) {
logger.info( "Specified feed " + pub.getFeedId() + " not known to Bus Controller");
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ return resp.error();
}
ArrayList<DR_Pub> pubs = fnew.getPubs();
if ( pubs.size() == 1 ) {
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage( "Can't delete the last publisher of a feed");
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ resp.setCode(Status.BAD_REQUEST.getStatusCode());
+ resp.setMessage( "Can't delete the last publisher of a feed");
+ return resp.error();
}
- Iterator<DR_Pub> i = pubs.iterator();
- while( i.hasNext() ) {
+
+ for( Iterator<DR_Pub> i = pubs.iterator(); i.hasNext(); ) {
DR_Pub listItem = i.next();
if ( listItem.getPubId().equals(id)) {
pubs.remove( listItem );
}
}
fnew.setPubs(pubs);
- fnew = feeds.updateFeed( fnew, err );
- if ( ! err.is2xx()) {
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ fnew = feeds.updateFeed( fnew, resp.getErr() );
+ if ( ! resp.getErr().is2xx()) {
+ return resp.error();
}
- dr_pubService.removeDr_Pub(id, err);
- if ( ! err.is2xx()) {
- return Response.status(err.getCode())
- .entity( err )
- .build();
+ dr_pubService.removeDr_Pub(id, resp.getErr() );
+ if ( ! resp.getErr().is2xx()) {
+ return resp.error();
}
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null);
}
@GET
+ @ApiOperation( value = "return DR_Pub details",
+ notes = "returns a DR Publisher in the specified environment. Gets a `DR_Pub` object by pubId",
+ response = DR_Pub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{pubId}")
- public Response get( @PathParam("pubId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response get(
+ @PathParam("pubId") String id
+ ) {
ApiService resp = new ApiService();
+
try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
- ApiError err = new ApiError();
- try {
- checkRequired( "feedId", id, "", err);
+ resp.required( "feedId", id, "");
} catch ( RequiredFieldException rfe ) {
- logger.debug( err.toString() );
- return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ return resp.error();
}
- logger.info( "Entry: GET /dr_pubs");
- DR_Pub pub = dr_pubService.getDr_Pub( id, err );
- if ( ! err.is2xx()) {
- return Response.status(err.getCode())
- .entity( err )
- .build();
+
+ DR_Pub pub = dr_pubService.getDr_Pub( id, resp.getErr() );
+ if ( ! resp.getErr().is2xx()) {
+ resp.getErr();
}
- return Response.status(Status.OK.getStatusCode())
- .entity(pub)
- .build();
+ return resp.success(Status.OK.getStatusCode(), pub);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java
index e0b42ce..b1eb7a3 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java
@@ -20,43 +20,30 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DR_Sub;
import org.openecomp.dmaapbc.model.Feed;
import org.openecomp.dmaapbc.service.ApiService;
@@ -65,41 +52,45 @@ import org.openecomp.dmaapbc.service.FeedService;
@Path("/dr_subs")
+@Api( value= "dr_subs", description = "Endpoint for a Data Router client that implements a Subscriber" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class DR_SubResource extends ApiResource {
- static final Logger logger = Logger.getLogger(DR_SubResource.class);
-
+@Authorization
+public class DR_SubResource extends BaseLoggingClass {
@GET
- public List<DR_Sub> getDr_Subs(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info( "Entry: GET /dr_subs");
+ @ApiOperation( value = "return DR_Sub details",
+ notes = "Returns array of `DR_Sub` objects. Add filter for feedId.",
+ response = DR_Sub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getDr_Subs() {
+
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
+
DR_SubService dr_subService = new DR_SubService();
- return dr_subService.getAllDr_Subs();
+ List<DR_Sub> subs = dr_subService.getAllDr_Subs();
+
+ GenericEntity<List<DR_Sub>> list = new GenericEntity<List<DR_Sub>>(subs) {
+ };
+ return resp.success(list);
}
@POST
- public Response addDr_Sub( DR_Sub sub,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info( "Entry: POST /dr_subs");
+ @ApiOperation( value = "return DR_Sub details",
+ notes = "Create a `DR_Sub` object. ",
+ response = DR_Sub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addDr_Sub(
+ DR_Sub sub
+ ) {
+
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
try {
resp.required( "feedId", sub.getFeedId(), "");
@@ -107,18 +98,15 @@ public class DR_SubResource extends ApiResource {
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST)
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
FeedService feeds = new FeedService();
Feed fnew = feeds.getFeed( sub.getFeedId(), resp.getErr() );
if ( fnew == null ) {
logger.warn( "Specified feed " + sub.getFeedId() + " not known to Bus Controller");
- return Response.status( resp.getErr().getCode() )
- .entity( resp.getErr() )
- .build();
+ resp.setCode(Status.NOT_FOUND.getStatusCode());
+ return resp.error();
}
DR_SubService dr_subService = new DR_SubService( fnew.getSubscribeURL());
@@ -126,9 +114,7 @@ public class DR_SubResource extends ApiResource {
logger.info( "num existing subs before = " + subs.size() );
DR_Sub snew = dr_subService.addDr_Sub(sub, resp.getErr() );
if ( ! resp.getErr().is2xx() ) {
- return Response.status( resp.getErr().getCode() )
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
subs.add( snew );
logger.info( "num existing subs after = " + subs.size() );
@@ -137,26 +123,25 @@ public class DR_SubResource extends ApiResource {
logger.info( "update feed");
//feeds.updateFeed( fnew, err );
- return Response.status(Status.CREATED)
- .entity(snew)
- .build();
+ return resp.success(Status.CREATED.getStatusCode(), snew);
}
@PUT
+ @ApiOperation( value = "return DR_Sub details",
+ notes = "Update a `DR_Sub` object, selected by subId",
+ response = DR_Sub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{subId}")
- public Response updateDr_Sub( @PathParam("subId") String name, DR_Sub sub,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info( "Entry: PUT /dr_subs");
+ public Response updateDr_Sub(
+ @PathParam("subId") String name,
+ DR_Sub sub
+ ) {
+
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
try {
resp.required( "subId", name, "");
@@ -165,89 +150,78 @@ public class DR_SubResource extends ApiResource {
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST)
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
+ FeedService feeds = new FeedService();
+ Feed fnew = feeds.getFeed( sub.getFeedId(), resp.getErr() );
+ if ( fnew == null ) {
+ logger.warn( "Specified feed " + sub.getFeedId() + " not known to Bus Controller");
+ return resp.error();
+ }
+
DR_SubService dr_subService = new DR_SubService();
sub.setSubId(name);
DR_Sub nsub = dr_subService.updateDr_Sub(sub, resp.getErr() );
if ( nsub != null && nsub.isStatusValid() ) {
- return Response.status(Status.OK)
- .entity(nsub)
- .build();
+ return resp.success(nsub);
}
- return Response.status(resp.getErr().getCode())
- .entity(resp.getErr())
- .build();
+ return resp.error();
}
@DELETE
+ @ApiOperation( value = "return DR_Sub details",
+ notes = "Delete a `DR_Sub` object, selected by subId",
+ response = DR_Sub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{subId}")
- public Response deleteDr_Sub( @PathParam("subId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
- logger.info( "Entry: DELETE /dr_subs");
+ public Response deleteDr_Sub(
+ @PathParam("subId") String id
+ ){
+
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
-
+
try {
resp.required( "subId", id, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST.getStatusCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
DR_SubService dr_subService = new DR_SubService();
dr_subService.removeDr_Sub(id, resp.getErr() );
if ( ! resp.getErr().is2xx() ) {
- return Response.status( resp.getErr().getCode() )
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null );
}
@GET
+ @ApiOperation( value = "return DR_Sub details",
+ notes = "Retrieve a `DR_Sub` object, selected by subId",
+ response = DR_Sub.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{subId}")
- public Response get( @PathParam("subId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info( "Entry: GET /dr_subs");
+ public Response get(
+ @PathParam("subId") String id
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
try {
resp.required( "subId", id, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST.getStatusCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
DR_SubService dr_subService = new DR_SubService();
DR_Sub sub = dr_subService.getDr_Sub( id, resp.getErr() );
if ( sub != null && sub.isStatusValid() ) {
- return Response.status(Status.OK.getStatusCode())
- .entity(sub)
- .build();
+ return resp.success(sub);
}
- return Response.status(resp.getErr().getCode())
- .entity(resp.getErr())
- .build();
+ return resp.error();
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java
index 9d158fa..879af75 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java
@@ -21,99 +21,103 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
-
-
-
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.DcaeLocationService;
@Path("/dcaeLocations")
+@Api( value= "dcaeLocations", description = "an OpenStack tenant purposed for OpenDCAE (i.e. where OpenDCAE components might be deployed)" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class DcaeLocationResource {
+@Authorization
+public class DcaeLocationResource extends BaseLoggingClass {
static final Logger logger = Logger.getLogger(DcaeLocationResource.class);
DcaeLocationService locationService = new DcaeLocationService();
@GET
- public List<DcaeLocation> getDcaeLocations( @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return dcaeLocation details",
+ notes = "Returns array of `dcaeLocation` objects. All objects managed by DMaaP are deployed in some `dcaeLocation` which is a unique identifier for an *OpenStack* tenant purposed for a *dcaeLayer* (ecomp or edge).",
+ response = DcaeLocation.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getDcaeLocations() {
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //check.unavailable();
- }
- return locationService.getAllDcaeLocations();
+
+ List<DcaeLocation> locs = locationService.getAllDcaeLocations();
+
+ GenericEntity<List<DcaeLocation>> list = new GenericEntity<List<DcaeLocation>>(locs) {
+ };
+ return check.success(list);
}
@POST
- public Response addDcaeLocation( DcaeLocation location,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ @ApiOperation( value = "return dcaeLocation details",
+ notes = "Create some `dcaeLocation` which is a unique identifier for an *OpenStack* tenant purposed for a *dcaeLayer* (ecomp or edge).",
+ response = DcaeLocation.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addDcaeLocation(
+ DcaeLocation location
+ ) {
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
if ( locationService.getDcaeLocation(location.getDcaeLocationName()) != null ) {
- ApiError err = new ApiError();
- err.setCode(Status.CONFLICT.getStatusCode());
- err.setMessage("dcaeLocation already exists");
- err.setFields("dcaeLocation");
+ check.setCode(Status.CONFLICT.getStatusCode());
+ check.setMessage("dcaeLocation already exists");
+ check.setFields("dcaeLocation");
- logger.warn( err );
- return Response.status(Status.CONFLICT).entity( err ).build();
-
+ return check.error();
}
DcaeLocation loc = locationService.addDcaeLocation(location);
- return Response.status(Status.CREATED)
- .entity(loc)
- .build();
+ return check.success(Status.CREATED.getStatusCode(), loc);
}
@PUT
+ @ApiOperation( value = "return dcaeLocation details",
+ notes = "update the openStackAvailabilityZone of a dcaeLocation",
+ response = DcaeLocation.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{locationName}")
- public Response updateDcaeLocation( @PathParam("locationName") String name, DcaeLocation location,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response updateDcaeLocation(
+ @PathParam("locationName") String name,
+ DcaeLocation location
+ ) {
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
location.setDcaeLocationName(name);
if ( locationService.getDcaeLocation(location.getDcaeLocationName()) == null ) {
ApiError err = new ApiError();
@@ -122,48 +126,42 @@ public class DcaeLocationResource {
err.setMessage("dcaeLocation does not exist");
err.setFields("dcaeLocation");
- logger.warn( err );
- return Response.status(Status.NOT_FOUND).entity( err ).build();
+ return check.notFound();
}
DcaeLocation loc = locationService.updateDcaeLocation(location);
- return Response.status(Status.CREATED)
- .entity(loc)
- .build();
+ return check.success(Status.CREATED.getStatusCode(), loc );
}
@DELETE
+ @ApiOperation( value = "return dcaeLocation details", notes = "delete a dcaeLocation", response = Dmaap.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{locationName}")
- public Response deleteDcaeLocation( @PathParam("locationName") String name,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ public Response deleteDcaeLocation(
+ @PathParam("locationName") String name
+ ){
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
locationService.removeDcaeLocation(name);
- return Response.status(Status.NO_CONTENT).build();
+ return check.success(Status.NO_CONTENT.getStatusCode(), null);
}
@GET
+ @ApiOperation( value = "return dcaeLocation details", notes = "Returns a specific `dcaeLocation` object with specified tag", response = Dmaap.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{locationName}")
- public Response getDcaeLocation( @PathParam("locationName") String name,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response getDcaeLocation(
+ @PathParam("locationName") String name
+ ) {
ApiService check = new ApiService();
- try {
- //List<PathSegment> segments = uriInfo.getPathSegments();
- check.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
DcaeLocation loc = locationService.getDcaeLocation( name );
if ( loc == null ) {
ApiError err = new ApiError();
@@ -172,14 +170,11 @@ public class DcaeLocationResource {
err.setMessage("dcaeLocation does not exist");
err.setFields("dcaeLocation");
- logger.warn( err );
- return Response.status(Status.NOT_FOUND).entity( err ).build();
+ return check.error();
}
- return Response.status(Status.OK)
- .entity(loc)
- .build();
+ return check.success(loc);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java
index 03c731f..07c178d 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java
@@ -25,9 +25,13 @@ package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@@ -36,10 +40,9 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.DmaapService;
@@ -47,92 +50,78 @@ import org.openecomp.dmaapbc.service.DmaapService;
@Path("/dmaap")
+@Api( value= "dmaap", description = "Endpoint for this instance of DMaaP object containing values for this OpenDCAE deployment" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class DmaapResource {
- static final Logger logger = Logger.getLogger(DmaapResource.class);
+@Authorization
+public class DmaapResource extends BaseLoggingClass {
+
DmaapService dmaapService = new DmaapService();
@GET
- public Response getDmaap(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
- logger.debug( "Entry: GET " + uriInfo.getPath() );
+ @ApiOperation( value = "return dmaap details", notes = "returns the `dmaap` object, which contains system wide configuration settings", response = Dmaap.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+
+ public Response getDmaap(@Context UriInfo uriInfo) {
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
Dmaap d = dmaapService.getDmaap();
- return Response.ok(d)
- .build();
+ return check.success(d);
}
@POST
- public Response addDmaap( Dmaap obj,@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
-
- ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+ @ApiOperation( value = "return dmaap details", notes = "Create a new DMaaP set system wide configuration settings for the *dcaeEnvironment*. Deprecated with introduction of persistence in 1610.", response = Dmaap.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addDmaap( Dmaap obj ) {
+ ApiService check = new ApiService();
+
try { //check for required fields
check.required( "dmaapName", obj.getDmaapName(), "^\\S+$" ); //no white space allowed in dmaapName
check.required( "dmaapProvUrl", obj.getDrProvUrl(), "" );
check.required( "topicNsRoot", obj.getTopicNsRoot(), "" );
check.required( "bridgeAdminTopic", obj.getBridgeAdminTopic(), "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
Dmaap d = dmaapService.addDmaap(obj);
if ( d == null ) {
- return Response.status(Status.NOT_FOUND)
- .build();
+ return check.notFound();
}
- return Response.ok(d)
- .build();
+ return check.success(d);
}
@PUT
- public Response updateDmaap( Dmaap obj, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ @ApiOperation( value = "return dmaap details", notes = "Update system settings for *dcaeEnvironment*.", response = Dmaap.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = Dmaap.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response updateDmaap( Dmaap obj ) {
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
try { //check for required fields
check.required( "dmaapName", obj.getDmaapName(), "^\\S+$" ); //no white space allowed in dmaapName
check.required( "dmaapProvUrl", obj.getDrProvUrl(), "" );
check.required( "topicNsRoot", obj.getTopicNsRoot(), "" );
check.required( "bridgeAdminTopic", obj.getBridgeAdminTopic(), "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
Dmaap d = dmaapService.updateDmaap(obj);
if ( d != null ) {
- return Response.ok(d)
- .build();
+ return check.success(d);
} else {
- return Response.status(Status.NOT_FOUND)
- .build();
+ return check.notFound();
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java b/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java
index b1dcd57..61130ec 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java
@@ -20,6 +20,11 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.jws.WebParam;
@@ -33,6 +38,7 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -59,56 +65,59 @@ import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
+import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
+import org.openecomp.dmaapbc.model.DR_Sub;
import org.openecomp.dmaapbc.model.Feed;
+import org.openecomp.dmaapbc.model.Topic;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.FeedService;
@Path("/feeds")
+@Api( value= "Feeds", description = "Endpoint for a Data Router Feed" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class FeedResource extends ApiResource {
- static final Logger logger = Logger.getLogger(FeedResource.class);
-
+@Authorization
+public class FeedResource extends BaseLoggingClass {
@GET
- public List<Feed> getFeeds(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.debug( "Entry: GET " + uriInfo.getPath() );
+ @ApiOperation( value = "return Feed details",
+ notes = "Returns array of `Feed` objects.",
+ response = Feed.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getFeeds() {
+
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
+
FeedService feedService = new FeedService();
List<Feed> nfeeds = feedService.getAllFeeds();
-// tried this: http://www.adam-bien.com/roller/abien/entry/jax_rs_returning_a_list
-// but still didn't seem to work...
-// GenericEntity<List<Feed>> list = new GenericEntity<List<Feed>>(nfeeds){};
-// return Response.status(Status.OK)
-// .entity( list )
-// .build();
- return nfeeds;
+ GenericEntity<List<Feed>> list = new GenericEntity<List<Feed>>(nfeeds) {
+ };
+ return resp.success(list);
}
@POST
- public Response addFeed( @WebParam(name = "feed") Feed feed , @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
- logger.debug( "Entry: POST " + uriInfo.getPath());
+ @ApiOperation( value = "return Feed details",
+ notes = "Create a of `Feed` object.",
+ response = Feed.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addFeed(
+ @WebParam(name = "feed") Feed feed
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "feedName", feed.getFeedName(), "");
resp.required( "feedVersion", feed.getFeedVersion(), "");
@@ -116,51 +125,47 @@ public class FeedResource extends ApiResource {
resp.required( "asprClassification", feed.getAsprClassification(), "" );
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST).entity( resp ).build();
+ return resp.error();
}
FeedService feedService = new FeedService();
Feed nfeed = feedService.addFeed( feed, resp.getErr() );
if ( nfeed != null ) {
- return Response.status(Status.OK)
- .entity(nfeed)
- .build();
+ return resp.success(nfeed);
} else {
logger.error( "Unable to create: " + feed.getFeedName() + ":" + feed.getFeedVersion());
- return Response.status(resp.getErr().getCode())
- .entity( resp )
- .build();
+ return resp.error();
}
}
@PUT
+ @ApiOperation( value = "return Feed details",
+ notes = "Update a `Feed` object, specified by id.",
+ response = Feed.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{id}")
- public Response updateFeed( @PathParam("id") String id, Feed feed, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.debug( "Entry: PUT " + uriInfo.getPath());
+ public Response updateFeed(
+ @PathParam("id") String id,
+ @WebParam(name = "feed") Feed feed
+ ) {
FeedService feedService = new FeedService();
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "feedId", id, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(Status.BAD_REQUEST.getStatusCode()).entity( resp ).build();
+ return resp.error();
}
Feed nfeed = feedService.getFeed( id, resp.getErr() );
if ( nfeed == null ) {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.notFound();
}
// we assume there is no updates allowed for pubs and subs objects via this api...
@@ -171,57 +176,54 @@ public class FeedResource extends ApiResource {
nfeed = feedService.updateFeed(nfeed, resp.getErr());
if ( nfeed != null ) {
- return Response.status(Status.OK)
- .entity(nfeed)
- .build();
+ return resp.success(nfeed);
} else {
logger.info( "Unable to update: " + feed.getFeedName() + ":" + feed.getFeedVersion());
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
}
@DELETE
+ @ApiOperation( value = "return Feed details",
+ notes = "Delete a `Feed` object, specified by id.",
+ response = Feed.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{id}")
- public Response deleteFeed( @PathParam("id") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ){
+ public Response deleteFeed(
+ @PathParam("id") String id
+ ){
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
- logger.debug( "Entry: DELETE " + uriInfo.getPath());
+
+ logger.debug( "Entry: DELETE " + id);
FeedService feedService = new FeedService();
feedService.removeFeed(id);
- return Response.status(Status.NO_CONTENT)
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null);
}
@GET
+ @ApiOperation( value = "return Feed details",
+ notes = "Retrieve a `Feed` object, specified by id.",
+ response = Feed.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{id}")
- public Response getFeed( @PathParam("id") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
- logger.debug( "Entry: GET " + uriInfo.getPath());
+ public Response getFeed(
+ @PathParam("id") String id
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
FeedService feedService = new FeedService();
Feed nfeed = feedService.getFeed( id, resp.getErr() );
if ( nfeed == null ) {
- return Response.status(Status.NOT_FOUND).entity( resp.getErr() ).build();
+ resp.setCode(Status.NOT_FOUND.getStatusCode());
+ return resp.error();
}
- return Response.status(Status.OK)
- .entity(nfeed)
- .build();
+ return resp.success(nfeed);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java
index 7acc0a4..058d66a 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java
@@ -20,27 +20,29 @@
package org.openecomp.dmaapbc.resources;
-import java.util.ArrayList;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.MR_Client;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.Topic;
@@ -51,38 +53,45 @@ import org.openecomp.dmaapbc.service.TopicService;
@Path("/mr_clients")
+@Api( value= "MR_Clients", description = "Endpoint for a Message Router Client that implements a Publisher or a Subscriber" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class MR_ClientResource extends ApiResource {
- static final Logger logger = Logger.getLogger(MR_ClientResource.class);
+@Authorization
+public class MR_ClientResource extends BaseLoggingClass {
+
private MR_ClientService mr_clientService = new MR_ClientService();
@GET
- public List<MR_Client> getMr_Clients(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return MR_Client details",
+ notes = "Returns array of `MR_Client` objects.",
+ response = MR_Client.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getMr_Clients() {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
- return mr_clientService.getAllMr_Clients();
+
+ List<MR_Client> clients = mr_clientService.getAllMr_Clients();
+
+ GenericEntity<List<MR_Client>> list = new GenericEntity<List<MR_Client>>(clients) {
+ };
+ return resp.success(list);
}
@POST
- public Response addMr_Client( MR_Client client,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return MR_Client details",
+ notes = "Create a `MR_Client` object.",
+ response = MR_Client.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addMr_Client(
+ MR_Client client
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "fqtn", client.getFqtn(), "");
resp.required( "dcaeLocationName", client.getDcaeLocationName(), "");
@@ -91,76 +100,60 @@ public class MR_ClientResource extends ApiResource {
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
MR_ClusterService clusters = new MR_ClusterService();
MR_Cluster cluster = clusters.getMr_Cluster(client.getDcaeLocationName(), resp.getErr());
if ( cluster == null ) {
- ApiError err = resp.getErr();
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage( "MR_Cluster alias not found for dcaeLocation: " + client.getDcaeLocationName());
- err.setFields("dcaeLocationName");
- logger.warn( err.getMessage() );
- return Response.status(err.getCode()).entity( err ).build();
+
+ resp.setCode(Status.BAD_REQUEST.getStatusCode());
+ resp.setMessage( "MR_Cluster alias not found for dcaeLocation: " + client.getDcaeLocationName());
+ resp.setFields("dcaeLocationName");
+ logger.warn( resp.toString() );
+ return resp.error();
}
String url = cluster.getFqdn();
if ( url == null || url.isEmpty() ) {
- ApiError err = resp.getErr();
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage("FQDN not set for dcaeLocation " + client.getDcaeLocationName() );
- err.setFields("fqdn");
- logger.warn( err.getMessage() );
- return Response.status(err.getCode()).entity( err ).build();
+
+ resp.setCode(Status.BAD_REQUEST.getStatusCode());
+ resp.setMessage("FQDN not set for dcaeLocation " + client.getDcaeLocationName() );
+ resp.setFields("fqdn");
+ logger.warn( resp.toString() );
+ return resp.error();
}
TopicService topics = new TopicService();
- ApiError err = resp.getErr();
- Topic t = topics.getTopic(client.getFqtn(), err);
+
+ Topic t = topics.getTopic(client.getFqtn(), resp.getErr() );
if ( t == null ) {
- return Response.status(err.getCode()).entity( err ).build();
+ return resp.error();
}
- MR_Client nClient = mr_clientService.addMr_Client(client, t, err);
- if ( err.is2xx()) {
- int n;
- ArrayList<MR_Client> tc = t.getClients();
- if ( tc == null ) {
- n = 0;
- tc = new ArrayList<MR_Client>();
- } else {
- n = tc.size();
- }
- logger.info( "number of existing clients for topic is " + n );
-
-
- logger.info( "n=" + n + " tc=" + tc + " client=" + client );
- tc.add( client );
- t.setClients(tc);
- topics.updateTopic( t );
- return Response.ok(nClient)
- .build();
+ MR_Client nClient = mr_clientService.addMr_Client(client, t, resp.getErr());
+ if ( resp.getErr().is2xx()) {
+ t = topics.getTopic(client.getFqtn(), resp.getErr());
+ topics.checkForBridge(t, resp.getErr());
+ return resp.success(nClient);
}
else {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
}
@PUT
+ @ApiOperation( value = "return MR_Client details",
+ notes = "Update a `MR_Client` object, specified by clientId",
+ response = MR_Client.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{clientId}")
- public Response updateMr_Client( @PathParam("clientId") String clientId, MR_Client client,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response updateMr_Client(
+ @PathParam("clientId") String clientId,
+ MR_Client client
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "fqtn", client.getFqtn(), "");
resp.required( "dcaeLocationName", client.getDcaeLocationName(), "");
@@ -169,9 +162,7 @@ public class MR_ClientResource extends ApiResource {
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
client.setMrClientId(clientId);
MR_Client nClient = mr_clientService.updateMr_Client(client, resp.getErr() );
@@ -185,83 +176,57 @@ public class MR_ClientResource extends ApiResource {
}
@DELETE
+ @ApiOperation( value = "return MR_Client details",
+ notes = "Delete a `MR_Client` object, specified by clientId",
+ response = MR_Client.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{subId}")
- public Response deleteMr_Client( @PathParam("subId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ public Response deleteMr_Client(
+ @PathParam("subId") String id
+ ){
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "clientId", id, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
- MR_Client client = mr_clientService.removeMr_Client(id, resp.getErr() );
+ mr_clientService.removeMr_Client(id, true, resp.getErr() );
if ( resp.getErr().is2xx()) {
- TopicService topics = new TopicService();
- ApiError err = resp.getErr();
- Topic t = topics.getTopic(client.getFqtn(), err);
- if ( t == null ) {
- logger.info( err.getMessage() );
- return Response.status(err.getCode()).entity( err ).build();
- }
-
- ArrayList<MR_Client> tc = t.getClients();
- for( MR_Client c: tc) {
- if ( c.getMrClientId().equals(id)) {
- tc.remove(c);
- break;
- }
- }
- t.setClients(tc);
- topics.updateTopic( t );
-
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null);
}
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
@GET
+ @ApiOperation( value = "return MR_Client details",
+ notes = "Retrieve a `MR_Client` object, specified by clientId",
+ response = MR_Client.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{subId}")
- public Response test( @PathParam("subId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response test(
+ @PathParam("subId") String id
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "clientId", id, "");
} catch ( RequiredFieldException rfe ) {
logger.debug( resp.toString() );
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
MR_Client nClient = mr_clientService.getMr_Client( id, resp.getErr() );
if ( resp.getErr().is2xx()) {
- return Response.ok(nClient)
- .build();
+ return resp.success(nClient);
}
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java
index a7b8f37..d7173b8 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java
@@ -20,176 +20,168 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.MR_ClientService;
import org.openecomp.dmaapbc.service.MR_ClusterService;
@Path("/mr_clusters")
+@Api( value= "MR_Clusters", description = "Endpoint for a Message Router servers in a Cluster configuration" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class MR_ClusterResource {
- static final Logger logger = Logger.getLogger(MR_ClusterResource.class);
+@Authorization
+public class MR_ClusterResource extends BaseLoggingClass {
MR_ClusterService mr_clusterService = new MR_ClusterService();
+ MR_ClientService mr_clients = new MR_ClientService();
@GET
- public List<MR_Cluster> getMr_Clusters(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ @ApiOperation( value = "return MR_Cluster details",
+ notes = "Returns array of `MR_Cluster` objects.",
+ response = MR_Cluster.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getMr_Clusters() {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; //resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //resp.unavailable();
- }
- return mr_clusterService.getAllMr_Clusters();
+
+ List<MR_Cluster> clusters = mr_clusterService.getAllMr_Clusters();
+
+ GenericEntity<List<MR_Cluster>> list = new GenericEntity<List<MR_Cluster>>(clusters) {
+ };
+ return resp.success(list);
}
@POST
- public Response addMr_Cluster( MR_Cluster cluster,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info("Entry: /POST" );
+ @ApiOperation( value = "return MR_Cluster details",
+ notes = "Create an `MR_Cluster` object.",
+ response = MR_Cluster.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addMr_Cluster(
+ MR_Cluster cluster
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "dcaeLocationName", cluster.getDcaeLocationName(), "" );
resp.required( "fqdn", cluster.getFqdn(), "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
MR_Cluster mrc = mr_clusterService.addMr_Cluster(cluster, resp.getErr() );
if ( mrc != null && mrc.isStatusValid() ) {
- return Response.status(Status.CREATED)
- .entity(mrc)
- .build();
+ return resp.success(Status.CREATED.getStatusCode(), mrc);
}
- return Response.status(resp.getErr().getCode())
- .entity(resp.getErr())
- .build();
+ return resp.error();
}
@PUT
+ @ApiOperation( value = "return MR_Cluster details",
+ notes = "Update an `MR_Cluster` object, specified by clusterId.",
+ response = MR_Cluster.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{clusterId}")
- public Response updateMr_Cluster( @PathParam("clusterId") String clusterId, MR_Cluster cluster,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response updateMr_Cluster(
+ @PathParam("clusterId") String clusterId,
+ MR_Cluster cluster
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "PUT");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "fqdn", clusterId, "" );
resp.required( "dcaeLocationName", cluster.getDcaeLocationName(), "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
cluster.setDcaeLocationName(clusterId);
MR_Cluster mrc = mr_clusterService.updateMr_Cluster(cluster, resp.getErr() );
if ( mrc != null && mrc.isStatusValid() ) {
- return Response.status(Status.CREATED)
- .entity(mrc)
- .build();
+ return resp.success(Status.CREATED.getStatusCode(), mrc);
}
- return Response.status(resp.getErr().getCode())
- .entity(resp.getErr())
- .build();
+ return resp.error();
}
@DELETE
+ @ApiOperation( value = "return MR_Cluster details",
+ notes = "Delete an `MR_Cluster` object, specified by clusterId.",
+ response = MR_Cluster.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{clusterId}")
- public Response deleteMr_Cluster( @PathParam("clusterId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ public Response deleteMr_Cluster(
+ @PathParam("clusterId") String id
+ ){
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "fqdn", id, "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
mr_clusterService.removeMr_Cluster(id, resp.getErr() );
if ( resp.getErr().is2xx()) {
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return resp.success(Status.NO_CONTENT.getStatusCode(), null);
}
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
@GET
+ @ApiOperation( value = "return MR_Cluster details",
+ notes = "Retrieve an `MR_Cluster` object, specified by clusterId.",
+ response = MR_Cluster.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{clusterId}")
- public Response getMR_Cluster( @PathParam("clusterId") String id,
- @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response getMR_Cluster(
+ @PathParam("clusterId") String id
+ ) {
ApiService resp = new ApiService();
- try {
- resp.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return resp.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return resp.unavailable();
- }
+
try {
resp.required( "dcaeLocationName", id, "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(resp.getErr().getCode())
- .entity( resp.getErr() )
- .build();
+ return resp.error();
}
MR_Cluster mrc = mr_clusterService.getMr_Cluster( id, resp.getErr() );
if ( mrc != null && mrc.isStatusValid() ) {
- return Response.status(Status.CREATED)
- .entity(mrc)
- .build();
+ return resp.success(Status.CREATED.getStatusCode(), mrc);
}
- return Response.status(resp.getErr().getCode())
- .entity(resp.getErr())
- .build();
+ return resp.error();
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java b/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java
index 5d4b9a7..47983c8 100644
--- a/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java
+++ b/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java
@@ -20,165 +20,172 @@
package org.openecomp.dmaapbc.resources;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
-import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
+import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
-import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
+import org.openecomp.dmaapbc.model.ReplicationType;
import org.openecomp.dmaapbc.model.Topic;
import org.openecomp.dmaapbc.service.ApiService;
import org.openecomp.dmaapbc.service.TopicService;
@Path("/topics")
+@Api( value= "topics", description = "Endpoint for retreiving MR Topics" )
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
-public class TopicResource {
-
- static final Logger logger = Logger.getLogger(TopicResource.class);
+@Authorization
+public class TopicResource extends BaseLoggingClass {
TopicService mr_topicService = new TopicService();
@GET
- public List<Topic> getTopics(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
- logger.info("Entry: /GET" );
+ @ApiOperation( value = "return Topic details",
+ notes = "Returns array of `Topic` objects.",
+ response = Topic.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response getTopics() {
+
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return null; // check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return null; //check.unavailable();
- }
- return mr_topicService.getAllTopics();
+
+ List<Topic> allTopics = mr_topicService.getAllTopics();
+
+ GenericEntity<List<Topic>> list = new GenericEntity<List<Topic>>(allTopics) {
+ };
+ return check.success(list);
+
}
@POST
- public Response addTopic( Topic topic, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
- logger.info("Entry: /POST" );
+ @ApiOperation( value = "return Topic details",
+ notes = "Create `Topic` object.",
+ response = Topic.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
+ public Response addTopic(
+ Topic topic
+ ) {
+ logger.info( "addTopic request: " + String.valueOf(topic) );
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPath(), "POST");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
try {
check.required( "topicName", topic.getTopicName(), "^\\S+$" ); //no white space allowed in topicName
check.required( "topicDescription", topic.getTopicDescription(), "" );
check.required( "owner", topic.getOwner(), "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
- //String fqtn = Topic.genFqtn(topic.getTopicName());
- ApiError err = check.getErr();
-
+
+ //String repReq = topic.getReplicationRequest();
+ ReplicationType t = topic.getReplicationCase();
+ if ( t == null || t == ReplicationType.REPLICATION_NOT_SPECIFIED ) {
+ topic.setReplicationCase( mr_topicService.reviewTopic(topic));
+ }
+
topic.setLastMod();
- Topic mrc = mr_topicService.addTopic(topic, err);
+ Topic mrc = mr_topicService.addTopic(topic, check.getErr());
if ( mrc != null && mrc.isStatusValid() ) {
- return Response.status(Status.CREATED)
- .entity(mrc)
- .build();
+ return check.success(Status.CREATED.getStatusCode(), mrc);
}
- return Response.status(err.getCode())
- .entity(err)
- .build();
-
+ return check.error();
}
@PUT
+ @ApiOperation( value = "return Topic details",
+ notes = "Update a `Topic` object, identified by topicId",
+ response = Topic.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{topicId}")
- public Response updateTopic( @PathParam("topicId") String topicId, Topic topic, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
- logger.info("Entry: /PUT " + topic );
- ApiError err = new ApiError();
- err.setCode(Status.BAD_REQUEST.getStatusCode());
- err.setMessage( "Method /PUT not supported for /topics");
+ public Response updateTopic(
+ @PathParam("topicId") String topicId
+ ) {
+ ApiService check = new ApiService();
+
+ check.setCode(Status.BAD_REQUEST.getStatusCode());
+ check.setMessage( "Method /PUT not supported for /topics");
- return Response.status(err.getCode())
- .entity( err )
- .build();
- //return mr_topicService.updateTopic(topic);
+ return check.error();
}
@DELETE
+ @ApiOperation( value = "return Topic details",
+ notes = "Delete a `Topic` object, identified by topicId",
+ response = Topic.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 204, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{topicId}")
- public Response deleteTopic( @PathParam("topicId") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ){
- logger.info("Entry: /DELETE " + id );
+ public Response deleteTopic(
+ @PathParam("topicId") String id
+ ){
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "DELETE");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
try {
check.required( "fqtn", id, "" );
} catch( RequiredFieldException rfe ) {
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
- Topic topic = mr_topicService.removeTopic(id, check.getErr());
+ mr_topicService.removeTopic(id, check.getErr());
if ( check.getErr().is2xx()) {
- return Response.status(Status.NO_CONTENT.getStatusCode())
- .build();
+ return check.success(Status.NO_CONTENT.getStatusCode(), null);
}
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
@GET
+ @ApiOperation( value = "return Topic details",
+ notes = "Retrieve a `Topic` object, identified by topicId",
+ response = Topic.class)
+ @ApiResponses( value = {
+ @ApiResponse( code = 200, message = "Success", response = DR_Pub.class),
+ @ApiResponse( code = 400, message = "Error", response = ApiError.class )
+ })
@Path("/{topicId}")
- public Response getTopic( @PathParam("topicId") String id , @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ public Response getTopic(
+ @PathParam("topicId") String id
+ ) {
logger.info("Entry: /GET " + id);
ApiService check = new ApiService();
- try {
- check.checkAuthorization( basicAuth, uriInfo.getPathSegments().get(0).getPath(), "GET");
- } catch ( AuthenticationErrorException ae ) {
- return check.unauthorized();
- } catch ( Exception e ) {
- logger.error( "Unexpected exception " + e );
- return check.unavailable();
- }
+
try {
check.required( "topicName", id, "^\\S+$" ); //no white space allowed in topicName
} catch( RequiredFieldException rfe ) {
- return Response.status(check.getErr().getCode())
- .entity( check.getErr() )
- .build();
+ return check.error();
}
Topic mrc = mr_topicService.getTopic( id, check.getErr() );
if ( mrc == null ) {
- return Response.status(check.getErr().getCode())
- .entity(check.getErr())
- .build();
+ return check.error();
}
- return Response.ok(mrc)
- .build();
+ return check.success(mrc);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/server/ApplicationConfig.java b/src/main/java/org/openecomp/dmaapbc/server/ApplicationConfig.java
new file mode 100644
index 0000000..95467e9
--- /dev/null
+++ b/src/main/java/org/openecomp/dmaapbc/server/ApplicationConfig.java
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * OpenECOMP - org.openecomp.dmaapbc
+ * ================================================================================
+ * 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.openecomp.dmaapbc.server;
+
+import org.glassfish.jersey.server.ResourceConfig;
+
+
+
+public class ApplicationConfig extends ResourceConfig {
+
+ /*
+ * Register JAX-RS application components
+ */
+ public ApplicationConfig() {
+
+ register(org.openecomp.dmaapbc.resources.AuthorizationFilter.class);
+
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java b/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java
index cef19a8..f8e05b1 100644
--- a/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java
+++ b/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java
@@ -39,15 +39,17 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.ssl.SslContextFactory;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.openecomp.dmaapbc.database.LoadSchema;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
/**
* A Jetty server which supports:
* - http and https (simultaneously for dev env)
* - REST API context
* - static html pages (for documentation).
*/
-public class JettyServer {
-
- static final Logger logger = Logger.getLogger(JettyServer.class);
+public class JettyServer extends BaseLoggingClass {
public JettyServer( Properties params ) throws Exception {
@@ -55,8 +57,8 @@ public class JettyServer {
int httpPort = Integer.valueOf(params.getProperty("IntHttpPort", "80" ));
int sslPort = Integer.valueOf(params.getProperty("IntHttpsPort", "443" ));
boolean allowHttp = Boolean.valueOf(params.getProperty("HttpAllowed", "false"));
- logger.info( "port params: http=" + httpPort + " https=" + sslPort );
- logger.info( "allowHttp=" + allowHttp );
+ serverLogger.info( "port params: http=" + httpPort + " https=" + sslPort );
+ serverLogger.info( "allowHttp=" + allowHttp );
// HTTP Server
@@ -105,9 +107,9 @@ public class JettyServer {
}
}
else {
- logger.info("NOT starting sslConnector on port " + sslPort + " for https");
+ serverLogger.info("NOT starting sslConnector on port " + sslPort + " for https");
if ( allowHttp ) {
- logger.info("Starting httpConnector on port " + httpPort );
+ serverLogger.info("Starting httpConnector on port " + httpPort );
server.setConnectors( new Connector[] { httpConnector });
}
}
@@ -119,7 +121,8 @@ public class JettyServer {
ServletHolder jerseyServlet = context.addServlet( org.glassfish.jersey.servlet.ServletContainer.class, "/webapi/*");
jerseyServlet.setInitOrder(1);
- jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "org.openecomp.dmaapbc.resources" );
+ jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "org.openecomp.dmaapbc.resources" );
+ jerseyServlet.setInitParameter("javax.ws.rs.Application", "org.openecomp.dmaapbc.server.ApplicationConfig" );
// also serve up some static pages...
ServletHolder staticServlet = context.addServlet(DefaultServlet.class,"/*");
@@ -128,13 +131,13 @@ public class JettyServer {
try {
- logger.info("Starting jetty server");
+ serverLogger.info("Starting jetty server");
server.start();
server.dumpStdErr();
server.join();
} catch ( Exception e ) {
- logger.error( "Exception " + e );
- logger.error( "possibly unable to use keystore " + keystore + " with passwords " + keystorePwd + " and " + keyPwd );
+ errorLogger.error( "Exception " + e );
+ errorLogger.error( "possibly unable to use keystore " + keystore + " with passwords " + keystorePwd + " and " + keyPwd );
//System.exit(1);
} finally {
server.destroy();
diff --git a/src/main/java/org/openecomp/dmaapbc/server/Main.java b/src/main/java/org/openecomp/dmaapbc/server/Main.java
index 2143670..11b6976 100644
--- a/src/main/java/org/openecomp/dmaapbc/server/Main.java
+++ b/src/main/java/org/openecomp/dmaapbc/server/Main.java
@@ -19,15 +19,24 @@
*/
package org.openecomp.dmaapbc.server;
-
-import java.io.FileInputStream;
+import java.net.InetAddress;
import java.util.Properties;
-import org.apache.log4j.Logger;
-import org.apache.log4j.PropertyConfigurator;
+import java.util.UUID;
+
+import org.openecomp.dmaapbc.authentication.ApiPerms;
+import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.util.DmaapConfig;
+import org.openecomp.dmaapbc.util.Singleton;
+import org.openecomp.dmaapbc.logging.*;
+
+
+import static com.att.eelf.configuration.Configuration.*;
+import org.slf4j.MDC;
+
+public class Main extends BaseLoggingClass {
-public class Main {
private Properties parameters;
private static String provFQDN;
@@ -44,24 +53,61 @@ public class Main {
(new Main()).main();
}
- static final Logger logger = Logger.getLogger(Main.class);
private void main() {
- String log = System.getProperty( "log4j.configuration");
- if ( log.isEmpty() ) {
- log = "log4j.properties";
- }
- PropertyConfigurator.configure( log );
- logger.info("Started.");
+
+ MDC.clear();
+
+ MDC.put(MDC_SERVICE_INSTANCE_ID, "");
+ try {
+ MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
+ MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ MDC.put(MDC_INSTANCE_UUID, UUID.randomUUID().toString());
+ MDC.put(MDC_ALERT_SEVERITY, "0");
+
+
+ MDC.put(MDC_TARGET_ENTITY, "DCAE");
+
+
+/*
+ String msg = "This is a sample {} message to demo EELF logging.";
+
+ appLogger.info( msg, "appLogger.info");
+
+ auditLogger.auditEvent( msg, "auditLogger.auditEvent");
+ errorLogger.error(DmaapbcLogMessageEnum.MESSAGE_SAMPLE_NOARGS);
+ errorLogger.error(DmaapbcLogMessageEnum.MESSAGE_SAMPLE_ONE_ARG, "errorLogger.error");
+ errorLogger.error(DmaapbcLogMessageEnum.MESSAGE_SAMPLE_TWO_ARGS, new Date().toString(), "errorLogger.error" );
+ metricsLogger.metricsEvent( msg, "metricsLogger.metricsEvent" );
+ debugLogger.debug( msg, "debugLogger.debug");
+
+ //String log = System.getProperty( "log4j.configuration");
+ //if ( log.isEmpty() ) {
+ // log = "log4j.properties";
+ //}
+ //PropertyConfigurator.configure( log );
+ *
+ */
+ appLogger.info("Started.");
parameters = DmaapConfig.getConfig();
setProvFQDN( parameters.getProperty("ProvFQDN", "ProvFQDN.notset.com"));
+
+
+ // for fresh installs, we may come up with no dmaap name so need to have a way for Controller to talk to us
+ Singleton<Dmaap> dmaapholder = DatabaseClass.getDmaap();
+ String name = dmaapholder.get().getDmaapName();
+ if ( name == null || name.isEmpty()) {
+ ApiPerms p = new ApiPerms();
+ p.setBootMap();
+ }
try {
- //new JettyServer( Integer.valueOf(parameters.getProperty("IntHttpPort", "80" )),
- // Integer.valueOf(parameters.getProperty("IntHttpsPort","443")));
new JettyServer( parameters );
} catch (Exception e) {
- logger.fatal("Unable to start Jetty " + DmaapConfig.getConfigFileName(), e);
+ errorLogger.error("Unable to start Jetty " + DmaapConfig.getConfigFileName(), e);
System.exit(1);
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/ApiService.java b/src/main/java/org/openecomp/dmaapbc/service/ApiService.java
index 8690bb0..824fc71 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/ApiService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/ApiService.java
@@ -20,6 +20,19 @@
package org.openecomp.dmaapbc.service;
+import static com.att.eelf.configuration.Configuration.MDC_BEGIN_TIMESTAMP;
+import static com.att.eelf.configuration.Configuration.MDC_ELAPSED_TIME;
+import static com.att.eelf.configuration.Configuration.MDC_END_TIMESTAMP;
+import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
+import static com.att.eelf.configuration.Configuration.MDC_PARTNER_NAME;
+import static com.att.eelf.configuration.Configuration.MDC_RESPONSE_CODE;
+import static com.att.eelf.configuration.Configuration.MDC_RESPONSE_DESC;
+import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
+import static com.att.eelf.configuration.Configuration.MDC_STATUS_CODE;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -27,33 +40,116 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.xml.bind.DatatypeConverter;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.aaf.DmaapPerm;
+import org.openecomp.dmaapbc.authentication.ApiPolicy;
import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
-import org.openecomp.dmaapbc.authentication.DecisionPolicy;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.resources.RequiredFieldException;
import org.openecomp.dmaapbc.util.DmaapConfig;
+import org.openecomp.dmaapbc.util.RandomString;
+import org.slf4j.MDC;
+
+public class ApiService extends BaseLoggingClass {
+ private class StopWatch {
+ private long clock = 0;
+ private long elapsed = 0;
+
-public class ApiService {
- static final Logger logger = Logger.getLogger(ApiService.class);
- static private String apiNamespace;
- static private boolean usePE;
+
+ public StopWatch() {
+ clock = 0;
+ elapsed = 0;
+ }
+
+ public void reset() {
+ clock = System.currentTimeMillis();
+ elapsed = 0;
+ }
+ public void stop() {
+ Long stopTime = System.currentTimeMillis();
+ elapsed += stopTime - clock;
+ clock = 0;
+ MDC.put( MDC_END_TIMESTAMP, isoFormatter.format(new Date(stopTime)));
+ MDC.put( MDC_ELAPSED_TIME, String.valueOf(elapsed));
+ }
+ public void start() {
+ if ( clock != 0 ) {
+ //not stopped
+ return;
+ }
+ clock = System.currentTimeMillis();
+ MDC.put( MDC_BEGIN_TIMESTAMP, isoFormatter.format(new Date(clock)));
+ }
+ private long getElapsed() {
+ return elapsed;
+ }
+ }
+ private String apiNamespace;
+ private boolean usePE;
+ private String uri;
+ private String uriPath;
+ private String method;
+ private String authorization;
+ private String requestId;
private ApiError err;
+ private StopWatch stopwatch;
+ public static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+ public final static TimeZone utc = TimeZone.getTimeZone("UTC");
+ public final static SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
+
+ static {
+ isoFormatter.setTimeZone(utc);
+ }
public ApiService() {
+
+ stopwatch = new StopWatch();
+ stopwatch.start();
err = new ApiError();
+ requestId = (new RandomString(10)).nextString();
if (apiNamespace == null) {
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
usePE = "true".equalsIgnoreCase(p.getProperty("UsePE", "false"));
apiNamespace = p.getProperty("ApiNamespace", "org.openecomp.dmaapBC.api");
}
-
+
+ logger.info( "usePE=" + usePE + " apiNamespace=" + apiNamespace);
}
-
+
+ public ApiService setAuth( String auth ) {
+ this.authorization = auth;
+ logger.info( "setAuth: authorization={} ", authorization);
+ return this;
+ }
+ private void setServiceName(){
+ String svcRequest = new String( this.method + " " + this.uriPath );
+ MDC.put(MDC_SERVICE_NAME, svcRequest );
+ }
+ public ApiService setHttpMethod( String httpMethod ) {
+ this.method = httpMethod;
+ logger.info( "setHttpMethod: method={} ", method);
+ setServiceName();
+ return this;
+ }
+ public ApiService setUriPath( String uriPath ) {
+ this.uriPath = uriPath;
+ this.uri = setUriFromPath( uriPath );
+ logger.info( "setUriPath: uriPath={} uri={}", uriPath, uri);
+ setServiceName();
+ return this;
+ }
+ private String setUriFromPath( String uriPath ) {
+ int ch = uriPath.indexOf("/");
+ if ( ch > 0 ) {
+ return( (String) uriPath.subSequence(0, ch ) );
+ } else {
+ return uriPath;
+ }
+ }
public ApiError getErr() {
return err;
@@ -105,41 +201,87 @@ public class ApiService {
err.setFields(string);
}
- private Response buildResponse() {
+ private Response buildResponse( Object obj ) {
+ stopwatch.stop();
+ MDC.put( MDC_RESPONSE_CODE, String.valueOf(err.getCode()) );
+
+ auditLogger.auditEvent( "" );
return Response.status( err.getCode())
- .entity(getErr())
+ .entity(obj)
.build();
}
- public Response response(int statusCode) {
- err.setCode(statusCode);
- return buildResponse();
+ private Response buildSuccessResponse(Object d) {
+ MDC.put( MDC_STATUS_CODE, "COMPLETE");
+ MDC.put( MDC_RESPONSE_DESC, "");
+ return buildResponse( d );
+ }
+ private Response buildErrResponse() {
+
+ MDC.put( MDC_STATUS_CODE, "ERROR");
+ MDC.put( MDC_RESPONSE_DESC, err.getMessage());
+
+ return buildResponse(getErr());
+ }
+ public Response success( Object d ) {
+ err.setCode(Status.OK.getStatusCode());
+ return buildSuccessResponse(d);
+
+ }
+ public Response success( int code, Object d ) {
+ err.setCode(code);
+ return buildSuccessResponse(d);
+ }
+
+ public Response unauthorized( String msg ) {
+ err.setCode(Status.UNAUTHORIZED.getStatusCode());
+ err.setFields( "Authorization");
+ err.setMessage( msg );
+ return buildErrResponse();
}
public Response unauthorized() {
err.setCode(Status.UNAUTHORIZED.getStatusCode());
err.setFields( "Authorization");
err.setMessage( "User credentials in HTTP Header field Authorization are not authorized for the requested action");
- return buildResponse();
+ return buildErrResponse();
}
public Response unavailable() {
err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
err.setMessage( "Request is unavailable due to unexpected condition");
- return buildResponse();
+ return buildErrResponse();
+ }
+ public Response notFound() {
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setMessage( "Requested object not found");
+ return buildErrResponse();
+ }
+ public Response error() {
+ return buildErrResponse();
}
- public void checkAuthorization( String authorization, String uriPath, String method ) throws AuthenticationErrorException, Exception {
- if ( ! usePE ) return; // skip authorization if not enabled
- if ( authorization == null || authorization.isEmpty()) {
- String errmsg = "No basic authorization value provided ";
- logger.info( errmsg );
- throw new AuthenticationErrorException( );
- }
- if ( uriPath == null || uriPath.isEmpty()) {
+ public void checkAuthorization( String auth, String uriPath, String httpMethod ) throws AuthenticationErrorException, Exception {
+ authorization = auth;
+ setUriFromPath( uriPath );
+ method = httpMethod;
+
+ checkAuthorization();
+ }
+
+
+ public void checkAuthorization() throws AuthenticationErrorException, Exception {
+
+ MDC.put(MDC_KEY_REQUEST_ID, requestId);
+
+ logger.info("request: uri={} method={} auth={}", uri, method, authorization );
+
+ if ( uri == null || uri.isEmpty()) {
String errmsg = "No URI value provided ";
+ err.setMessage(errmsg);
logger.info( errmsg );
throw new AuthenticationErrorException( );
}
if ( method == null || method.isEmpty()) {
String errmsg = "No method value provided ";
+ err.setMessage(errmsg);
logger.info( errmsg );
throw new AuthenticationErrorException( );
}
@@ -152,25 +294,45 @@ public class ApiService {
if ( env.isEmpty() ) {
env = "boot";
}
-
- String credentials = authorization.substring("Basic".length()).trim();
+ if ( ! usePE ) return; // skip authorization if not enabled
+ if ( authorization == null || authorization.isEmpty()) {
+ String errmsg = "No basic authorization value provided ";
+ err.setMessage(errmsg);
+ logger.info( errmsg );
+ throw new AuthenticationErrorException( );
+ }
+ String credentials = authorization.substring("Basic".length()).trim();
byte[] decoded = DatatypeConverter.parseBase64Binary(credentials);
String decodedString = new String(decoded);
String[] actualCredentials = decodedString.split(":");
String ID = actualCredentials[0];
String Password = actualCredentials[1];
-
-logger.info( "User " + ID + " allowed - DecisionPolicy() not compiled in yet!" );
-/* disable until PolicyEngine avail...
+ MDC.put(MDC_PARTNER_NAME, ID);
try {
- DecisionPolicy d = new DecisionPolicy();
- DmaapPerm p = new DmaapPerm( apiNamespace + "." + uriPath, env, method );
+ ApiPolicy d = new ApiPolicy();
+ DmaapPerm p = new DmaapPerm( apiNamespace + "." + uri, env, method );
d.check( ID, Password, p);
} catch ( AuthenticationErrorException ae ) {
- logger.info( "User " + ID + " failed authentication/authorization");
+ String errmsg = "User " + ID + " failed authentication/authorization for " + apiNamespace + "." + uriPath + " " + env + " " + method;
+ logger.info( errmsg );
+ err.setMessage(errmsg);
throw ae;
}
-*/
+
+
+ }
+ public String getRequestId() {
+ return requestId;
+ }
+ public ApiService setRequestId(String requestId) {
+ if ( requestId == null || requestId.isEmpty()) {
+ this.requestId = (new RandomString(10)).nextString();
+ logger.warn( "X-ECOMP-RequestID not set in HTTP Header. Setting RequestId value to: " + this.requestId );
+ } else {
+ this.requestId = requestId;
+ }
+ MDC.put(MDC_KEY_REQUEST_ID, this.requestId);
+ return this;
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java b/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java
index c1e36aa..f791896 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java
@@ -27,13 +27,109 @@ import java.util.Map;
import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.client.DrProvConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Node;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
-public class DR_NodeService {
- static final Logger logger = Logger.getLogger(DR_NodeService.class);
+public class DR_NodeService extends BaseLoggingClass {
+ private class DrProv {
+ String currentNodes;
+ String currentStaticNodes;
+
+ private String getX( String X, ApiError apiError ) {
+
+ DrProvConnection prov = new DrProvConnection();
+ prov.makeNodesConnection( X );
+ String resp = prov.doGetNodes( apiError );
+ logger.info( "rc=" + apiError.getCode() );
+ return resp;
+ }
+
+ private void setX( String X, String list, ApiError apiError ) {
+ DrProvConnection prov = new DrProvConnection();
+ prov.makeNodesConnection( X, list );
+ String resp = prov.doPutNodes( apiError );
+ }
+
+ private String removeFromList( String aNode, String aList ) {
+ String[] nodeList = aList.split("\\|");
+ StringBuilder res = new StringBuilder();
+ for ( String n: nodeList ) {
+ logger.info( "compare existing node " + n + " vs " + aNode );
+ if ( ! n.equals(aNode)) {
+ if (res.length() > 0 ) {
+ res.append( "|" );
+ }
+ res.append(n);
+ }
+ }
+ logger.info( "result=" + res.toString() );
+ return res.toString();
+ }
+
+ boolean containsNode( String aNode , ApiError apiError ){
+
+ //DrProvConnection prov = new DrProvConnection();
+ //prov.makeNodesConnection();
+ currentNodes = getX( "NODES", apiError );
+ if ( ! apiError.is2xx() || currentNodes == null ) {
+ return false;
+ }
+ logger.info( "NODES now=" + currentNodes );
+ String[] nodeList = currentNodes.split("\\|");
+ for( String n: nodeList ) {
+ logger.info( "compare existing node " + n + " vs " + aNode );
+ if ( n.equals(aNode) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void addNode( String aNode, ApiError apiError ) {
+
+ currentNodes = currentNodes + "|" + aNode;
+ setX( "NODES", currentNodes, apiError );
+
+
+ }
+ void removeNode( String aNode, ApiError apiError ) {
+ currentNodes = removeFromList( aNode, currentNodes );
+ setX( "NODES", currentNodes, apiError );
+ }
+
+ public boolean containsStaticNode(String aNode, ApiError apiError) {
+
+ //DrProvConnection prov = new DrProvConnection();
+ //prov.makeNodesConnection();
+ currentStaticNodes = getX( "STATIC_ROUTING_NODES", apiError );
+ if (! apiError.is2xx() || currentStaticNodes == null ) {
+ return false;
+ }
+ logger.info( "STATIC_ROUTING_NODES now=" + currentNodes );
+ String[] nodeList = currentStaticNodes.split("\\|");
+ for( String n: nodeList ) {
+ logger.info( "compare existing node " + n + " vs " + aNode );
+ if ( n.equals(aNode) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+
+ public void addStaticNode(String aNode, ApiError apiError) {
+ currentStaticNodes = currentStaticNodes + "|" + aNode;
+ setX( "STATIC_ROUTING_NODES", currentStaticNodes, apiError );
+ }
+ void removeStaticNode( String aNode, ApiError apiError ) {
+ currentStaticNodes = removeFromList( aNode, currentStaticNodes );
+ setX( "STATIC_ROUTING_NODES", currentStaticNodes, apiError );
+ }
+ }
private Map<String, DR_Node> dr_nodes = DatabaseClass.getDr_nodes();
public Map<String, DR_Node> getDr_Nodes() {
@@ -65,6 +161,25 @@ public class DR_NodeService {
apiError.setMessage( "Node " + fqdn + " already exists");
return null;
}
+
+ DrProv drProv = new DrProv();
+
+ if ( ! drProv.containsNode( node.getFqdn(), apiError ) && apiError.is2xx() ) {
+ drProv.addNode( node.getFqdn(), apiError );
+ }
+ if ( ! apiError.is2xx()) {
+ return null;
+ }
+ DcaeLocationService locService = new DcaeLocationService();
+ if ( locService.isEdgeLocation( node.getDcaeLocationName()) && ! drProv.containsStaticNode( node.getFqdn(), apiError ) ) {
+ if ( apiError.is2xx() ) {
+ drProv.addStaticNode( node.getFqdn(), apiError );
+ }
+ }
+ if ( ! apiError.is2xx()) {
+ return null;
+ }
+
node.setLastMod();
node.setStatus(DmaapObject_Status.VALID);
dr_nodes.put( node.getFqdn(), node );
@@ -94,11 +209,24 @@ public class DR_NodeService {
apiError.setMessage( "Node " + nodeName + " does not exist");
return null;
}
+
+ DrProv drProv = new DrProv();
+ if ( drProv.containsNode( old.getFqdn(), apiError ) && apiError.is2xx() ) {
+ drProv.removeNode( old.getFqdn(), apiError );
+ }
+ DcaeLocationService locService = new DcaeLocationService();
+ if ( locService.isEdgeLocation( old.getDcaeLocationName()) && drProv.containsStaticNode( old.getFqdn(), apiError ) ) {
+ if ( apiError.is2xx()) {
+ drProv.removeStaticNode( old.getFqdn(), apiError );
+ }
+
+ }
+
apiError.setCode(200);
return dr_nodes.remove(nodeName);
- }
+ }
- public String getNodePatternAtLocation( String loc ) {
+ public String getNodePatternAtLocation( String loc, boolean allowMult ) {
logger.info( "loc=" + loc );
if ( loc == null ) {
return null;
@@ -110,6 +238,9 @@ public class DR_NodeService {
str.append( ",");
}
str.append( node.getFqdn());
+ if ( ! allowMult ) {
+ break;
+ }
}
}
logger.info( "returning " + str.toString() );
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java b/src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java
index 8479e55..a1feb6d 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java
@@ -29,12 +29,14 @@ import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.client.DrProvConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
-public class DR_PubService {
- static final Logger logger = Logger.getLogger(DR_PubService.class);
+public class DR_PubService extends BaseLoggingClass{
+
private Map<String, DR_Pub> dr_pubs = DatabaseClass.getDr_pubs();
private DR_NodeService nodeService = new DR_NodeService();
private static DrProvConnection prov;
@@ -77,11 +79,11 @@ public class DR_PubService {
private void addIngressRoute( DR_Pub pub, ApiError err ) {
- String nodePattern = nodeService.getNodePatternAtLocation( pub.getDcaeLocationName());
+ String nodePattern = nodeService.getNodePatternAtLocation( pub.getDcaeLocationName(), true );
if ( nodePattern != null && nodePattern.length() > 0 ) {
logger.info( "creating ingress rule: pub " + pub.getPubId() + " on feed " + pub.getFeedId() + " to " + nodePattern);
prov.makeIngressConnection( pub.getFeedId(), pub.getUsername(), "-", nodePattern);
- int rc = prov.doIngressPost(err);
+ int rc = prov.doXgressPost(err);
logger.info( "rc=" + rc + " error code=" + err.getCode() );
if ( rc != 200 ) {
@@ -94,7 +96,7 @@ public class DR_PubService {
break;
default:
- logger.warn( "unable to create ingress rule for " + pub.getPubId() + " on feed " + pub.getFeedId() + " to " + nodePattern);
+ logger.info( DmaapbcLogMessageEnum.INGRESS_CREATE_ERROR, Integer.toString(rc), pub.getPubId(), pub.getFeedId(), nodePattern);
}
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java b/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java
index a360cff..f2fc99d 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java
@@ -26,38 +26,36 @@ import java.util.Map;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.client.DrProvConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
-import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DR_Sub;
-import org.openecomp.dmaapbc.model.Feed;
-public class DR_SubService {
- static final Logger logger = Logger.getLogger(DR_SubService.class);
+public class DR_SubService extends BaseLoggingClass {
+
private Map<String, DR_Sub> dr_subs = DatabaseClass.getDr_subs();
+ private DR_NodeService nodeService = new DR_NodeService();
private String provURL;
- //private DrProvConnection prov;
+ private static DrProvConnection prov;
+
public DR_SubService( ) {
- logger.info( "Entry: DR_SubService (with no args)" );
-// prov = new DrProvConnection();
+ logger.debug( "Entry: DR_SubService (with no args)" );
}
public DR_SubService( String subURL ) {
- logger.info( "Entry: DR_SubService " + subURL );
+ logger.debug( "Entry: DR_SubService " + subURL );
provURL = subURL;
-// prov = new DrProvConnection();
-// prov.makeSubConnection( subURL );
}
public Map<String, DR_Sub> getDR_Subs() {
- logger.info( "enter getDR_Subs()");
+ logger.debug( "enter getDR_Subs()");
return dr_subs;
}
public List<DR_Sub> getAllDr_Subs() {
- logger.info( "enter getAllDR_Subs()");
+ logger.debug( "enter getAllDR_Subs()");
return new ArrayList<DR_Sub>(dr_subs.values());
}
@@ -72,7 +70,7 @@ public class DR_SubService {
return someSubs;
}
public DR_Sub getDr_Sub( String key, ApiError apiError ) {
- logger.info( "enter getDR_Sub()");
+ logger.debug( "enter getDR_Sub()");
DR_Sub sub = dr_subs.get( key );
if ( sub == null ) {
apiError.setCode(Status.NOT_FOUND.getStatusCode());
@@ -85,11 +83,11 @@ public class DR_SubService {
}
public DR_Sub addDr_Sub( DR_Sub sub, ApiError apiError ) {
- logger.info( "enter addDR_Subs()");
- DrProvConnection prov = new DrProvConnection();
- prov.makeSubConnection( provURL );
- String resp = prov.doPostDr_Sub( sub );
- logger.info( "resp=" + resp );
+ logger.debug( "enter addDR_Subs()");
+ prov = new DrProvConnection();
+ prov.makeSubPostConnection( provURL );
+ String resp = prov.doPostDr_Sub( sub, apiError );
+ logger.debug( "resp=" + resp );
DR_Sub snew = null;
@@ -97,6 +95,7 @@ public class DR_SubService {
snew = new DR_Sub( resp );
snew.setDcaeLocationName(sub.getDcaeLocationName());
snew.setLastMod();
+ addEgressRoute( snew, apiError );
dr_subs.put( snew.getSubId(), snew );
apiError.setCode(200);
} else {
@@ -106,25 +105,58 @@ public class DR_SubService {
return snew;
}
+ private void addEgressRoute( DR_Sub sub, ApiError err ) {
+ String nodePattern = nodeService.getNodePatternAtLocation( sub.getDcaeLocationName(), false );
+ if ( nodePattern != null && nodePattern.length() > 0 ) {
+ logger.info( "creating egress rule: sub " + sub.getSubId() + " on feed " + sub.getFeedId() + " to " + nodePattern);
+ prov.makeEgressConnection( sub.getSubId(), nodePattern);
+ int rc = prov.doXgressPost(err);
+ logger.info( "rc=" + rc + " error code=" + err.getCode() );
+
+ if ( rc != 200 ) {
+ switch( rc ) {
+ case 403:
+ logger.error( "Not authorized for DR egress API");
+ err.setCode(500);
+ err.setMessage("API deployment/configuration error - contact support");
+ err.setFields( "PROV_AUTH_ADDRESSES");
+ break;
+
+ default:
+ logger.info( DmaapbcLogMessageEnum.EGRESS_CREATE_ERROR, Integer.toString(rc), sub.getSubId(), sub.getFeedId(), nodePattern);
+ }
+ }
+
+ }
+ }
+
public DR_Sub updateDr_Sub( DR_Sub obj, ApiError apiError ) {
- logger.info( "enter updateDR_Subs()");
+ logger.debug( "enter updateDR_Subs()");
- DR_Sub sub = dr_subs.get( obj.getSubId() );
- if ( sub == null ) {
- apiError.setCode(Status.NOT_FOUND.getStatusCode());
- apiError.setFields( "subId");
- apiError.setMessage("subId " + obj.getSubId() + " not found");
- return null;
- }
- sub.setLastMod();
- dr_subs.put( sub.getSubId(), sub );
- apiError.setCode(200);
- return sub;
+ DrProvConnection prov = new DrProvConnection();
+ prov.makeSubPutConnection( obj.getSubId() );
+ String resp = prov.doPutDr_Sub( obj, apiError );
+ logger.debug( "resp=" + resp );
+
+ DR_Sub snew = null;
+
+ if ( resp != null ) {
+ snew = new DR_Sub( resp );
+ snew.setDcaeLocationName(obj.getDcaeLocationName());
+ snew.setLastMod();
+ dr_subs.put( snew.getSubId(), snew );
+ apiError.setCode(200);
+ } else if ( apiError.is2xx()) {
+ apiError.setCode(400);
+ apiError.setMessage("unexpected empty response from DR Prov");
+ }
+
+ return snew;
}
public void removeDr_Sub( String key, ApiError apiError ) {
- logger.info( "enter removeDR_Subs()");
+ logger.debug( "enter removeDR_Subs()");
DR_Sub sub = dr_subs.get( key );
if ( sub == null ) {
apiError.setCode(Status.NOT_FOUND.getStatusCode());
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java b/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java
index f88852a..4451ff8 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java
@@ -82,5 +82,13 @@ public class DcaeLocationService {
}
return "aCentralLocation"; // default value that is obvious to see is wrong
}
+
+ public boolean isEdgeLocation(String aName) {
+ DcaeLocation loc = dcaeLocations.get(aName);
+ if ( ! loc.isCentral() ) {
+ return true;
+ }
+ return false;
+ }
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java b/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java
index 47cc271..c673427 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java
@@ -22,14 +22,17 @@ package org.openecomp.dmaapbc.service;
import java.util.ArrayList;
-import org.apache.log4j.Logger;
+
import org.openecomp.dmaapbc.aaf.AafService;
import org.openecomp.dmaapbc.aaf.DmaapGrant;
import org.openecomp.dmaapbc.aaf.DmaapPerm;
import org.openecomp.dmaapbc.aaf.AafService.ServiceType;
+import org.openecomp.dmaapbc.authentication.ApiPerms;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
-import org.openecomp.dmaapbc.model.DcaeLocation;
+
import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.model.MR_Client;
import org.openecomp.dmaapbc.model.Topic;
@@ -37,8 +40,8 @@ import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
import org.openecomp.dmaapbc.util.DmaapConfig;
import org.openecomp.dmaapbc.util.Singleton;
-public class DmaapService {
- static final Logger logger = Logger.getLogger(DmaapService.class);
+public class DmaapService extends BaseLoggingClass {
+
private Singleton<Dmaap> dmaapholder = DatabaseClass.getDmaap();
@@ -69,7 +72,8 @@ public class DmaapService {
dmaapholder.update(nd);
AafService aaf = new AafService( ServiceType.AAF_Admin);
-
+ ApiPerms p = new ApiPerms();
+ p.setEnvMap();
boolean anythingWrong = setTopicMgtPerms( nd, aaf ) || createMmaTopic();
if ( anythingWrong ) {
@@ -92,7 +96,7 @@ public class DmaapService {
logger.info( "entering updateDmaap()" );
boolean anythingWrong = false;
- AafService aaf = new AafService( ServiceType.AAF_Admin);
+
Dmaap dmaap = dmaapholder.get();
// some triggers for when we attempt to reprovision perms and MMA topic:
@@ -102,6 +106,9 @@ public class DmaapService {
if ( ! dmaap.isStatusValid() || ! nd.getDmaapName().equals(dmaap.getDmaapName()) || dmaap.getVersion().equals( "0") ) {
nd.setLastMod();
dmaapholder.update(nd); //need to set this so the following perms will pick up any new vals.
+ ApiPerms p = new ApiPerms();
+ p.setEnvMap();
+ AafService aaf = new AafService( ServiceType.AAF_Admin);
anythingWrong = setTopicMgtPerms( nd, aaf ) || createMmaTopic();
}
@@ -128,7 +135,14 @@ public class DmaapService {
public String getBridgeAdminFqtn(){
Dmaap dmaap = dmaapholder.get();
- return(dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + dmaap.getBridgeAdminTopic());
+ String topic = dmaap.getBridgeAdminTopic();
+
+ // check if this is already an fqtn (contains a dot)
+ // otherwise build it
+ if ( topic.indexOf('.') < 0 ) {
+ topic = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + dmaap.getBridgeAdminTopic();
+ }
+ return( topic );
}
private boolean setTopicMgtPerms( Dmaap nd, AafService aaf ){
@@ -164,14 +178,14 @@ public class DmaapService {
int rc = aaf.addPerm( perm );
if ( rc != 201 && rc != 409 ) {
- logger.error( "unable to add perm for "+ t + "|" + instance + "|" + action );
+ errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "add perm", t + "|" + instance + "|" + action );
return true;
}
DmaapGrant grant = new DmaapGrant( perm, topicMgrRole );
rc = aaf.addGrant( grant );
if ( rc != 201 && rc != 409 ) {
- logger.error( "unable to grant to " + topicMgrRole + " perm for "+ topicFactory + "|" + instance + "|" + action );
+ errorLogger.error( DmaapbcLogMessageEnum.AAF_UNEXPECTED_RESPONSE, Integer.toString(rc), "grant to " + topicMgrRole + " perm ", topicFactory + "|" + instance + "|" + action );
return true;
}
@@ -221,11 +235,16 @@ public class DmaapService {
ApiError err = new ApiError();
TopicService svc = new TopicService();
- Topic nTopic = svc.addTopic(mmaTopic, err);
- if ( err.is2xx() || err.getCode() == 409 ) {
- return false;
+ try {
+ @SuppressWarnings("unused")
+ Topic nTopic = svc.addTopic(mmaTopic, err);
+ if ( err.is2xx() || err.getCode() == 409 ) {
+ return false;
+ }
+ } catch ( Exception e) {
+ errorLogger.error( DmaapbcLogMessageEnum.UNEXPECTED_CONDITION, " while adding Topic: " + e.getMessage());
}
- logger.error( "Unable to create topic for " + dmaap.getBridgeAdminTopic() + " err=" + err.getFields() + " fields=" + err.getFields() + " msg=" + err.getMessage());
+ errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR, dmaap.getBridgeAdminTopic(), err.getFields(), err.getFields(), err.getMessage());
return rc;
diff --git a/src/main/java/org/openecomp/dmaapbc/service/FeedService.java b/src/main/java/org/openecomp/dmaapbc/service/FeedService.java
index a9af116..ae05016 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/FeedService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/FeedService.java
@@ -29,14 +29,15 @@ import javax.ws.rs.core.Response.Status;
import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.client.DrProvConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DR_Pub;
import org.openecomp.dmaapbc.model.DR_Sub;
import org.openecomp.dmaapbc.model.Feed;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
-public class FeedService {
- static final Logger logger = Logger.getLogger(FeedService.class);
+public class FeedService extends BaseLoggingClass {
+
private Map<String, Feed> feeds = DatabaseClass.getFeeds();
private DR_PubService pubService = new DR_PubService();
private DR_SubService subService = new DR_SubService();
@@ -146,7 +147,7 @@ public class FeedService {
int rSize = reqPubs.size();
logger.info( "reqPubs size=" + rSize + " newPubs size=" + nSize );
if ( nSize != rSize ) {
- logger.error( "Resulting set of publishers do not match requested set of publishers " + nSize + " vs " + rSize );
+ errorLogger.error( "Resulting set of publishers do not match requested set of publishers " + nSize + " vs " + rSize );
fnew.setStatus( DmaapObject_Status.INVALID);
return false;
}
@@ -160,7 +161,7 @@ public class FeedService {
reqPub.setFeedId(newPub.getFeedId());
reqPub.setStatus(DmaapObject_Status.VALID);
if ( reqPub.getDcaeLocationName() == null ) {
- reqPub.setDcaeLocationName("dcaeLocationNotSpecified");
+ reqPub.setDcaeLocationName("notSpecified");
}
pubSvc.addDr_Pub( reqPub );
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java b/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java
index ac4b5c8..6ea61d5 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java
@@ -26,27 +26,37 @@ import java.util.Map;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
+
import org.openecomp.dmaapbc.aaf.AafService;
import org.openecomp.dmaapbc.aaf.DmaapGrant;
import org.openecomp.dmaapbc.aaf.DmaapPerm;
import org.openecomp.dmaapbc.aaf.AafService.ServiceType;
import org.openecomp.dmaapbc.client.MrProvConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DcaeLocation;
import org.openecomp.dmaapbc.model.MR_Client;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.Topic;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
+import org.openecomp.dmaapbc.util.DmaapConfig;
-public class MR_ClientService {
- static final Logger logger = Logger.getLogger(MR_ClientService.class);
+public class MR_ClientService extends BaseLoggingClass{
+ private int deleteLevel;
private Map<String, MR_Client> mr_clients = DatabaseClass.getMr_clients();
private Map<String, MR_Cluster> clusters = DatabaseClass.getMr_clusters();
private Map<String, Topic> topics = DatabaseClass.getTopics();
+ private Map<String, DcaeLocation> locations = DatabaseClass.getDcaeLocations();
private DmaapService dmaap = new DmaapService();
+ public MR_ClientService() {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+
+ deleteLevel = Integer.valueOf(p.getProperty("MR.ClientDeleteLevel", "0" ));
+ }
+
public Map<String, MR_Client> getMR_Clients() {
return mr_clients;
}
@@ -67,6 +77,30 @@ public class MR_ClientService {
return results;
}
+ public ArrayList<MR_Client> getClientsByLocation(String location) {
+ ArrayList<MR_Client> results = new ArrayList<MR_Client>();
+ for (Map.Entry<String, MR_Client> entry : mr_clients.entrySet())
+ {
+ MR_Client client = entry.getValue();
+ if ( location.equals(client.getDcaeLocationName() ) ) {
+ results.add( client );
+ }
+ }
+ return results;
+ }
+
+ public void refreshClients( String location ) {
+ ApiError err = new ApiError();
+ ArrayList<MR_Client> clients = getClientsByLocation( location );
+ for( MR_Client client : clients ) {
+ Topic topic = topics.get(client.getFqtn());
+ if ( topic != null ) {
+ addMr_Client( client, topic, err);
+ }
+
+
+ }
+ }
public MR_Client getMr_Client( String key, ApiError apiError ) {
MR_Client c = mr_clients.get( key );
@@ -82,39 +116,40 @@ public class MR_ClientService {
public MR_Client addMr_Client( MR_Client client, Topic topic, ApiError err ) {
if ( client.getDcaeLocationName().isEmpty()) {
- logger.error( "Client dcaeLocation that doesn't exist or not specified" );
+ logger.info( "Client dcaeLocation that doesn't exist or not specified" );
+ return null;
+ }
+ grantClientPerms( client, err);
+ if ( ! client.isStatusValid()) {
return null;
}
+ String centralFqdn = null;
+ DcaeLocation candidate = locations.get(client.getDcaeLocationName());
+ if ( candidate != null && candidate.isCentral() ) {
+ DmaapConfig p = ( DmaapConfig)DmaapConfig.getConfig();
+ centralFqdn = p.getProperty("MR.CentralCname");
+ }
MR_Cluster cluster = clusters.get( client.getDcaeLocationName());
if ( cluster != null ) {
- client.setTopicURL(cluster.genTopicURL(client.getFqtn()));
- AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
-
- String instance = ":topic." + client.getFqtn();
- client.setStatus( DmaapObject_Status.VALID);
- for( String want : client.getAction() ) {
- int rc;
- DmaapPerm perm = new DmaapPerm( dmaap.getTopicPerm(), instance, want );
- DmaapGrant g = new DmaapGrant( perm, client.getClientRole() );
- rc = aaf.addGrant( g );
- if ( rc != 201 && rc != 409 ) {
- client.setStatus( DmaapObject_Status.INVALID);
- err.setCode(rc);
- err.setMessage( "Grant of " + dmaap.getTopicPerm() + "|" + instance + "|" + want + " failed for " + client.getClientRole() );
- logger.warn( err.getMessage());
+ client.setTopicURL(cluster.genTopicURL(centralFqdn, client.getFqtn()));
+ if ( centralFqdn == null ) {
+ client.setStatus( addTopicToCluster( cluster, topic, err));
+ if( ! err.is2xx() && err.getCode() != 409 ) {
+ topic.setFqtn(err.getMessage());
return null;
- }
- }
-
-
- logger.info( "cluster=" + cluster );
- MrProvConnection prov = new MrProvConnection();
- logger.info( "POST topic " + topic.getFqtn() + " to cluster " + cluster.getFqdn() + " in loc " + cluster.getDcaeLocationName());
- if ( prov.makeTopicConnection(cluster)) {
- String resp = prov.doPostTopic(topic);
- logger.info( "response: " + resp );
- if ( resp == null ) {
- client.setStatus( DmaapObject_Status.INVALID);
+ }
+
+ } else {
+ MR_ClusterService clusters = new MR_ClusterService();
+ // in 1610, MM should only exist for edge-to-central
+ // we use a cname for the central target
+ // but still need to provision topics on all central MRs
+ for( MR_Cluster central: clusters.getCentralClusters() ) {
+ client.setStatus( addTopicToCluster( central, topic, err));
+ if( ! err.is2xx() && err.getCode() != 409 ) {
+ topic.setFqtn(err.getMessage());
+ return null;
+ }
}
}
@@ -125,32 +160,66 @@ public class MR_ClientService {
}
mr_clients.put( client.getMrClientId(), client );
-
-
- //TODO: this section on updating an existing topic with a new client needs to belong someplace else
- //Topic t = topics.get(topic.getFqtn());
- /*
- int n;
- ArrayList<MR_Client> tc = topic.getClients();
- if ( tc == null ) {
- n = 0;
- tc = new ArrayList<MR_Client>();
- } else {
- n = tc.size();
- }
- logger.info( "number of existing clients for topic is " + n );
-
- logger.info( "n=" + n + " tc=" + tc + " client=" + client );
- tc.add( client );
- topic.setClients(tc);
- */
- topics.put(topic.getFqtn(), topic);
err.setCode(200);
return client;
}
+
+ private DmaapObject_Status addTopicToCluster( MR_Cluster cluster, Topic topic, ApiError err ){
+
+ MrProvConnection prov = new MrProvConnection();
+ logger.info( "POST topic " + topic.getFqtn() + " to cluster " + cluster.getFqdn() + " in loc " + cluster.getDcaeLocationName());
+ if ( prov.makeTopicConnection(cluster)) {
+ String resp = prov.doPostTopic(topic, err);
+ logger.info( "response code: " + err.getCode() );
+ if ( err.is2xx() || err.getCode() == 409 ) {
+ return DmaapObject_Status.VALID;
+ }
+ }
+ return DmaapObject_Status.INVALID;
+ }
+
+ private void grantClientPerms( MR_Client client, ApiError err) {
+ AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
+
+ String instance = ":topic." + client.getFqtn();
+ client.setStatus( DmaapObject_Status.VALID);
+ for( String want : client.getAction() ) {
+ int rc;
+ DmaapPerm perm = new DmaapPerm( dmaap.getTopicPerm(), instance, want );
+ DmaapGrant g = new DmaapGrant( perm, client.getClientRole() );
+ rc = aaf.addGrant( g );
+ if ( rc != 201 && rc != 409 ) {
+ client.setStatus( DmaapObject_Status.INVALID);
+ err.setCode(rc);
+ err.setMessage( "Grant of " + dmaap.getTopicPerm() + "|" + instance + "|" + want + " failed for " + client.getClientRole() );
+ logger.warn( err.getMessage());
+ return;
+ }
+ }
+ }
+
+ private void revokeClientPerms( MR_Client client, ApiError err) {
+ AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
+ String instance = ":topic." + client.getFqtn();
+ client.setStatus( DmaapObject_Status.VALID);
+ for( String want : client.getAction() ) {
+ int rc;
+ DmaapPerm perm = new DmaapPerm( dmaap.getTopicPerm(), instance, want );
+ DmaapGrant g = new DmaapGrant( perm, client.getClientRole() );
+ rc = aaf.delGrant( g );
+ if ( rc != 200 && rc != 404 ) {
+ client.setStatus( DmaapObject_Status.INVALID);
+ err.setCode(rc);
+ err.setMessage( "Revoke of " + dmaap.getTopicPerm() + "|" + instance + "|" + want + " failed for " + client.getClientRole() );
+ logger.warn( err.getMessage());
+ return;
+ }
+ }
+ }
+
public MR_Client updateMr_Client( MR_Client client, ApiError apiError ) {
MR_Client c = mr_clients.get( client.getMrClientId());
if ( c == null ) {
@@ -164,18 +233,50 @@ public class MR_ClientService {
return client;
}
- public MR_Client removeMr_Client( String key, ApiError apiError ) {
- MR_Client c = mr_clients.get( key );
- if ( c == null ) {
+ public void removeMr_Client( String key, boolean updateTopicView, ApiError apiError ) {
+ MR_Client client = mr_clients.get( key );
+ if ( client == null ) {
apiError.setCode(Status.NOT_FOUND.getStatusCode());
apiError.setFields( "mrClientId");
apiError.setMessage("mrClientId " + key + " not found" );
+ return;
} else {
apiError.setCode(200);
}
-
- return mr_clients.remove(key);
- }
+
+ if ( updateTopicView == true ) {
+
+ TopicService topics = new TopicService();
+
+ Topic t = topics.getTopic(client.getFqtn(), apiError );
+ if ( t != null ) {
+ ArrayList<MR_Client> tc = t.getClients();
+ for( MR_Client c: tc) {
+ if ( c.getMrClientId().equals(client.getMrClientId())) {
+ tc.remove(c);
+ break;
+ }
+ }
+ t.setClients(tc);
+ topics.updateTopic( t, apiError );
+ }
+ }
+
+
+ // remove from AAF
+ if ( deleteLevel >= 2 ) {
+ revokeClientPerms( client, apiError );
+ if ( ! apiError.is2xx()) {
+ return;
+ }
+ }
+ // remove from DB
+ if ( deleteLevel >= 1 ) {
+ mr_clients.remove(key);
+ }
+
+ return;
+ }
}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java b/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java
index d5cb402..d96b568 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java
@@ -26,15 +26,16 @@ import java.util.Map;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
+
+
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.DcaeLocation;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
-public class MR_ClusterService {
- static final Logger logger = Logger.getLogger(MR_ClusterService.class);
+public class MR_ClusterService extends BaseLoggingClass {
private Map<String, MR_Cluster> mr_clusters = DatabaseClass.getMr_clusters();
@@ -64,6 +65,17 @@ public class MR_ClusterService {
}
return null;
}
+
+ public List<MR_Cluster> getCentralClusters() {
+ DcaeLocationService locations = new DcaeLocationService();
+ List<MR_Cluster> result = new ArrayList<MR_Cluster>();
+ for( MR_Cluster c: mr_clusters.values() ) {
+ if ( locations.getDcaeLocation(c.getDcaeLocationName()).isCentral() ) {
+ result.add(c);
+ }
+ }
+ return result;
+ }
public MR_Cluster addMr_Cluster( MR_Cluster cluster, ApiError apiError ) {
logger.info( "Entry: addMr_Cluster");
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java b/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java
index 5d633b0..0370857 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java
@@ -21,43 +21,33 @@
package org.openecomp.dmaapbc.service;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import org.apache.log4j.Logger;
-
-
-
-
-
-
-
-
-
-
-
-
-import org.openecomp.dmaapbc.aaf.AndrewDecryptor;
+import org.openecomp.dmaapbc.aaf.AafDecrypt;
+//import org.openecomp.dmaapbc.aaf.AndrewDecryptor;
import org.openecomp.dmaapbc.client.MrTopicConnection;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.MirrorMaker;
-import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
import org.openecomp.dmaapbc.util.DmaapConfig;
import org.openecomp.dmaapbc.util.RandomInteger;
-public class MirrorMakerService {
- static final Logger logger = Logger.getLogger(MirrorMakerService.class);
+public class MirrorMakerService extends BaseLoggingClass {
private Map<String, MirrorMaker> mirrors = DatabaseClass.getMirrorMakers();
private static MrTopicConnection prov;
+ private static AafDecrypt decryptor;
public MirrorMakerService() {
super();
- // TODO Auto-generated constructor stub
+
+ decryptor = new AafDecrypt();
}
// will create a MM on MMagent if needed
@@ -66,34 +56,41 @@ public class MirrorMakerService {
logger.info( "updateMirrorMaker");
DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
String provUser = p.getProperty("MM.ProvUserMechId");
- String provUserPwd = AndrewDecryptor.valueOf(p.getProperty( "MM.ProvUserPwd", "notSet" ));
+ String provUserPwd = decryptor.decrypt(p.getProperty( "MM.ProvUserPwd", "notSet" ));
prov = new MrTopicConnection( provUser, provUserPwd );
- MR_ClusterService clusters = new MR_ClusterService();
- DmaapService dmaap = new DmaapService();
- //TODO: this should find the cluster!!!!
+
+ String centralFqdn = p.getProperty("MR.CentralCname", "notSet");
- MR_Cluster central = clusters.getMr_ClusterByFQDN(mm.getTargetCluster());
- if ( central != null ) {
- prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn() );
+ DmaapService dmaap = new DmaapService();
+ MR_ClusterService clusters = new MR_ClusterService();
+
+ // in 1610, MM should only exist for edge-to-central
+ // we use a cname for the central MR cluster that is active, and provision on agent topic on that target
+ // but only send 1 message so MM Agents can read it relying on kafka delivery
+ for( MR_Cluster central: clusters.getCentralClusters() ) {
+ prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn(), centralFqdn );
ApiError resp = prov.doPostMessage(mm.createMirrorMaker());
if ( ! resp.is2xx() ) {
- //logger.error( "Unable to publish MR Bridge provisioning message. rc=" + resp.getCode() + " msg=" + resp.getMessage());
- logger.error( "Unable to publish create MM provisioning message. rc=" + resp.getCode() + " msg=" + resp.getMessage());
+
+ errorLogger.error( DmaapbcLogMessageEnum.MM_PUBLISH_ERROR, "create MM", Integer.toString(resp.getCode()), resp.getMessage());
mm.setStatus(DmaapObject_Status.INVALID);
} else {
- prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn() );
+ prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn(), centralFqdn );
resp = prov.doPostMessage(mm.updateWhiteList());
if ( ! resp.is2xx()) {
- logger.error( "Unable to publish MR Bridge provisioning message. rc=" + resp.getCode() + " msg=" + resp.getMessage());
+ errorLogger.error( DmaapbcLogMessageEnum.MM_PUBLISH_ERROR,"MR Bridge", Integer.toString(resp.getCode()), resp.getMessage());
mm.setStatus(DmaapObject_Status.INVALID);
} else {
mm.setStatus(DmaapObject_Status.VALID);
}
}
+
+ // we only want to send one message even if there are multiple central clusters
+ break;
- } else {
- logger.warn( "target cluster " + mm.getTargetCluster() + " not found!");
- }
+ }
+
+
mm.setLastMod();
return mirrors.put( mm.getMmName(), mm);
diff --git a/src/main/java/org/openecomp/dmaapbc/service/TopicService.java b/src/main/java/org/openecomp/dmaapbc/service/TopicService.java
index 0240fab..887d234 100644
--- a/src/main/java/org/openecomp/dmaapbc/service/TopicService.java
+++ b/src/main/java/org/openecomp/dmaapbc/service/TopicService.java
@@ -26,37 +26,44 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.apache.log4j.Logger;
import org.openecomp.dmaapbc.aaf.AafService;
import org.openecomp.dmaapbc.aaf.DmaapPerm;
import org.openecomp.dmaapbc.aaf.AafService.ServiceType;
import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.logging.BaseLoggingClass;
+import org.openecomp.dmaapbc.logging.DmaapbcLogMessageEnum;
import org.openecomp.dmaapbc.model.ApiError;
import org.openecomp.dmaapbc.model.Dmaap;
import org.openecomp.dmaapbc.model.MR_Client;
import org.openecomp.dmaapbc.model.MR_Cluster;
import org.openecomp.dmaapbc.model.MirrorMaker;
+import org.openecomp.dmaapbc.model.ReplicationType;
import org.openecomp.dmaapbc.model.Topic;
import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
import org.openecomp.dmaapbc.util.DmaapConfig;
import org.openecomp.dmaapbc.util.Graph;
-public class TopicService {
- static final Logger logger = Logger.getLogger(TopicService.class);
+public class TopicService extends BaseLoggingClass {
+
- // TODO put these in properties file
- String topicFactory = "org.openecomp.dcae.dmaap.topicFactory";
+ // REF: https://wiki.web.att.com/pages/viewpage.action?pageId=519703122
+ private static String defaultGlobalMrHost;
+
private Map<String, Topic> mr_topics = DatabaseClass.getTopics();
private Map<String, MR_Cluster> clusters = DatabaseClass.getMr_clusters();
- private Dmaap dmaap = new DmaapService().getDmaap();
+ private static DmaapService dmaapSvc = new DmaapService();
+ private static Dmaap dmaap = new DmaapService().getDmaap();
private MR_ClientService clientService = new MR_ClientService();
private MirrorMakerService bridge = new MirrorMakerService();
-
+
+ public TopicService(){
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ defaultGlobalMrHost = p.getProperty("MR.globalHost", "global.host.not.set");
+ }
public Map<String, Topic> getTopics() {
return mr_topics;
@@ -99,7 +106,6 @@ public class TopicService {
logger.info( "fqtn: " + nFqtn );
topic.setFqtn( nFqtn );
- boolean anythingWrong = false;
AafService aaf = new AafService(ServiceType.AAF_TopicMgr);
String t = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + ".mr.topic";
String instance = ":topic." + topic.getFqtn();
@@ -136,72 +142,58 @@ public class TopicService {
}
topic.setClients(clients2);
- Graph graph = new Graph( clients2 );
-
- String centralFqdn = new String();
- if ( graph.isHasCentral() ) {
- centralFqdn = clusters.get( graph.getCentralLoc() ).getFqdn();
-
- }
-
- Collection<String> locations = graph.getKeys();
- for( String loc : locations ) {
- logger.info( "loc=" + loc );
- MR_Cluster cluster = clusters.get(loc);
- logger.info( "cluster=" + cluster );
-
- if ( graph.isHasCentral() && ! centralFqdn.equals(cluster.getFqdn())) {
- logger.info( "Create a MM from " + cluster.getFqdn() + " to " + centralFqdn );
- try {
- MirrorMaker mm = bridge.getMirrorMaker(cluster.getFqdn(), centralFqdn);
- if ( mm == null ) {
- mm = new MirrorMaker(cluster.getFqdn(), centralFqdn);
- }
- mm.addTopic(topic.getFqtn());
- bridge.updateMirrorMaker(mm);
- } catch ( Exception ex ) {
- err.setCode(500);
- err.setFields( "mirror_maker.topic");
- err.setMessage("Unexpected condition: " + ex );
- anythingWrong = true;
- break;
- }
-
- }
-
+ }
+ if ( topic.getReplicationCase().involvesGlobal() ) {
+ if ( topic.getGlobalMrURL() == null ) {
+ topic.setGlobalMrURL(defaultGlobalMrHost);
}
}
-
- if ( anythingWrong ) {
+ Topic ntopic = checkForBridge( topic, err );
+ if ( ntopic == null ) {
topic.setStatus( DmaapObject_Status.INVALID);
return null;
}
-
- topic.setStatus( DmaapObject_Status.VALID);
- mr_topics.put( nFqtn, topic );
- //String prov = bridge.commit();
- //logger.info( "prov=" + prov);
+ mr_topics.put( nFqtn, ntopic );
+
err.setCode(Status.OK.getStatusCode());
- return topic;
+ return ntopic;
}
- public Topic updateTopic( Topic topic ) {
+ public Topic updateTopic( Topic topic, ApiError err ) {
+ logger.info( "Entry: updateTopic");
if ( topic.getFqtn().isEmpty()) {
return null;
}
- mr_topics.put( topic.getFqtn(), topic );
- return topic;
+ Topic ntopic = checkForBridge( topic, err );
+ if ( ntopic == null ) {
+ topic.setStatus( DmaapObject_Status.INVALID);
+ return null;
+ }
+ mr_topics.put( ntopic.getFqtn(), ntopic );
+ err.setCode(Status.OK.getStatusCode());
+ return ntopic;
}
public Topic removeTopic( String pubId, ApiError apiError ) {
- if ( mr_topics.get(pubId) == null ) {
+ Topic topic = mr_topics.get(pubId);
+ if ( topic == null ) {
apiError.setCode(Status.NOT_FOUND.getStatusCode());
apiError.setMessage("Topic " + pubId + " does not exist");
apiError.setFields("fqtn");
return null;
}
+ ArrayList<MR_Client> clients = new ArrayList<MR_Client>(clientService.getAllMrClients( pubId ));
+ for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
+ MR_Client c = it.next();
+
+
+ clientService.removeMr_Client(c.getMrClientId(), false, apiError);
+ if ( ! apiError.is2xx()) {
+ return null;
+ }
+ }
apiError.setCode(Status.OK.getStatusCode());
return mr_topics.remove(pubId);
}
@@ -212,7 +204,7 @@ public class TopicService {
String[] Roles = { mmProvRole, mmAgentRole };
String[] actions = { "view", "pub", "sub" };
Topic bridgeAdminTopic = new Topic();
- bridgeAdminTopic.setTopicName( DatabaseClass.getDmaap().get().getBridgeAdminTopic());
+ bridgeAdminTopic.setTopicName( dmaapSvc.getBridgeAdminFqtn() );
bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
bridgeAdminTopic.setOwner( "DBC" );
ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
@@ -234,7 +226,191 @@ public class TopicService {
return err;
}
- logger.error( "Unable to create MM provisioning topic " + bridgeAdminTopic.getFqtn());
+ errorLogger.error( DmaapbcLogMessageEnum.TOPIC_CREATE_ERROR, bridgeAdminTopic.getFqtn(), Integer.toString(err.getCode()), err.getFields(), err.getMessage());
return err;
}
+
+
+ public Topic checkForBridge( Topic topic, ApiError err ) {
+
+ if ( topic.getReplicationCase() == ReplicationType.REPLICATION_NONE ) {
+ topic.setStatus( DmaapObject_Status.VALID);
+ return topic;
+ }
+
+ boolean anythingWrong = false;
+ String centralFqdn = new String();
+ Graph graph = new Graph( topic.getClients(), true );
+
+ if ( graph.isHasCentral() ) {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ centralFqdn = p.getProperty("MR.CentralCname");
+ logger.info( "CentralCname=" + centralFqdn );
+ } else {
+ logger.warn( "Topic " + topic.getFqtn() + " wants to be " + topic.getReplicationCase() + " but has no cental clients");
+ }
+ Collection<String> locations = graph.getKeys();
+ for( String loc : locations ) {
+ logger.info( "loc=" + loc );
+ MR_Cluster cluster = clusters.get(loc);
+ logger.info( "cluster=" + cluster );
+
+
+
+ String source = null;
+ String target = null;
+ /*
+ * all replication rules have 1 bridge...
+ */
+ switch( topic.getReplicationCase() ) {
+ case REPLICATION_EDGE_TO_CENTRAL:
+ case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL: // NOTE: this is for E2C portion only
+ if ( graph.isHasCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ break;
+ }
+ source = cluster.getFqdn();
+ target = centralFqdn;
+ break;
+ case REPLICATION_CENTRAL_TO_EDGE:
+ if ( graph.isHasCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ continue;
+ }
+ source = centralFqdn;
+ target = cluster.getFqdn();
+ break;
+ case REPLICATION_CENTRAL_TO_GLOBAL:
+ if ( graph.isHasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ continue;
+ }
+ source = centralFqdn;
+ target = topic.getGlobalMrURL();
+ break;
+ case REPLICATION_GLOBAL_TO_CENTRAL:
+ case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE: // NOTE: this is for G2C portion only
+ if ( graph.isHasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ continue;
+ }
+ source = topic.getGlobalMrURL();
+ target = centralFqdn;
+ break;
+ default:
+ logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
+ anythingWrong = true;
+ continue;
+ }
+ if ( source != null && target != null ) {
+ try {
+ logger.info( "Create a MM from " + source + " to " + target );
+ MirrorMaker mm = bridge.getMirrorMaker( source, target);
+ if ( mm == null ) {
+ mm = new MirrorMaker(source, target);
+ }
+ mm.addTopic(topic.getFqtn());
+ bridge.updateMirrorMaker(mm);
+ } catch ( Exception ex ) {
+ err.setCode(500);
+ err.setFields( "mirror_maker.topic");
+ err.setMessage("Unexpected condition: " + ex );
+ anythingWrong = true;
+ break;
+ }
+ }
+
+
+ /*
+ * some replication rules have a 2nd bridge!
+ */
+ source = target = null;
+ switch( topic.getReplicationCase() ) {
+ case REPLICATION_EDGE_TO_CENTRAL:
+ case REPLICATION_CENTRAL_TO_EDGE:
+ case REPLICATION_CENTRAL_TO_GLOBAL:
+ case REPLICATION_GLOBAL_TO_CENTRAL:
+ continue;
+ case REPLICATION_EDGE_TO_CENTRAL_TO_GLOBAL: // NOTE: this is for C2G portion only
+ if ( graph.isHasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ continue;
+ }
+ source = centralFqdn;
+ target = topic.getGlobalMrURL();
+ break;
+
+ case REPLICATION_GLOBAL_TO_CENTRAL_TO_EDGE: // NOTE: this is for C2E portion only
+ if ( graph.isHasCentral() && graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ continue;
+ }
+ source = centralFqdn;
+ target = cluster.getFqdn();
+ break;
+ default:
+ logger.error( "Unexpected value for ReplicationType ("+ topic.getReplicationCase() + ") for topic " + topic.getFqtn() );
+ anythingWrong = true;
+ break;
+ }
+ if ( source != null && target != null ) {
+ try {
+ logger.info( "Create a MM from " + source + " to " + target );
+ MirrorMaker mm = bridge.getMirrorMaker( source, target);
+ if ( mm == null ) {
+ mm = new MirrorMaker(source, target);
+ }
+ mm.addTopic(topic.getFqtn());
+ bridge.updateMirrorMaker(mm);
+ } catch ( Exception ex ) {
+ err.setCode(500);
+ err.setFields( "mirror_maker.topic");
+ err.setMessage("Unexpected condition: " + ex );
+ anythingWrong = true;
+ break;
+ }
+ }
+
+ }
+ if ( anythingWrong ) {
+ topic.setStatus( DmaapObject_Status.INVALID);
+ return null;
+ }
+
+ topic.setStatus( DmaapObject_Status.VALID);
+ return topic;
+ }
+
+ /*
+ * Prior to 1707, we only supported EDGE_TO_CENTRAL replication.
+ * This was determined automatically based on presence of edge publishers and central subscribers.
+ * The following method is a modification of that original logic, to preserve some backwards compatibility,
+ * i.e. to be used when no ReplicationType is specified.
+ */
+ public ReplicationType reviewTopic( Topic topic ) {
+
+
+ if ( topic.getNumClients() > 1 ) {
+ Graph graph = new Graph( topic.getClients(), false );
+
+ String centralFqdn = new String();
+ if ( graph.isHasCentral() ) {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ centralFqdn = p.getProperty("MR.CentralCname");
+ }
+
+ Collection<String> locations = graph.getKeys();
+ for( String loc : locations ) {
+ logger.info( "loc=" + loc );
+ MR_Cluster cluster = clusters.get(loc);
+ if ( cluster == null ) {
+ logger.info( "No MR cluster for location " + loc );
+ continue;
+ }
+ if ( graph.isHasCentral() && ! graph.getCentralLoc().equals(cluster.getDcaeLocationName())) {
+ logger.info( "Detected case for EDGE_TO_CENTRAL from " + cluster.getFqdn() + " to " + centralFqdn );
+ return ReplicationType.REPLICATION_EDGE_TO_CENTRAL;
+
+ }
+
+ }
+ }
+
+ return ReplicationType.REPLICATION_NONE;
+ }
+
}
diff --git a/src/main/java/org/openecomp/dmaapbc/util/Graph.java b/src/main/java/org/openecomp/dmaapbc/util/Graph.java
index bdb1f6e..f91f156 100644
--- a/src/main/java/org/openecomp/dmaapbc/util/Graph.java
+++ b/src/main/java/org/openecomp/dmaapbc/util/Graph.java
@@ -20,6 +20,7 @@
package org.openecomp.dmaapbc.util;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
@@ -39,20 +40,19 @@ public class Graph {
//TODO add to properties file
private static String centralDcaeLayerName = "central";
- public Graph() {
- }
+
public Graph(HashMap<String, String> graph) {
super();
this.graph = graph;
}
- public Graph( List<MR_Client> clients ) {
+ public Graph( List<MR_Client> clients, boolean strict ) {
if ( clients == null )
return;
this.graph = new HashMap<String, String>();
this.hasCentral = false;
for( MR_Client client: clients ) {
- if ( client.isStatusValid()) {
+ if ( ! strict || client.isStatusValid()) {
String loc = client.getDcaeLocationName();
for( String action : client.getAction() ){
DcaeLocation dcaeLoc = locations.get(loc);