diff options
Diffstat (limited to 'src/main')
77 files changed, 9562 insertions, 0 deletions
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java new file mode 100644 index 0000000..421e948 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafConnection.java @@ -0,0 +1,194 @@ +/*-
+ * ============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.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ProtocolException;
+import java.net.URL;
+import java.net.UnknownHostException;
+
+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.service.DmaapService;
+
+
+public class AafConnection {
+
+ static final Logger logger = Logger.getLogger(AafConnection.class);
+
+
+ private String dmaapName;
+ private String aafCred;
+
+
+ private HttpsURLConnection uc;
+
+
+ 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;
+ }
+
+
+ private boolean makeConnection( String pURL ) {
+
+ try {
+ URL u = new URL( pURL );
+ uc = (HttpsURLConnection) u.openConnection();
+ uc.setInstanceFollowRedirects(false);
+ logger.info( "successful connect to " + pURL );
+ return(true);
+ } catch (Exception e) {
+ logger.error("Unexpected error during openConnection of " + pURL );
+ e.printStackTrace();
+ return(false);
+ }
+
+ }
+
+ static String bodyToString( InputStream is ) {
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader( new InputStreamReader(is));
+ String line;
+ try {
+ while ((line = br.readLine()) != null ) {
+ sb.append( line );
+ }
+ } catch (IOException ex ) {
+ logger.error( "IOexception:" + ex);
+ }
+
+ return sb.toString();
+ }
+
+
+
+ public int postAaf( AafObject obj, String 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;
+ };
+
+
+ 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("POST");
+ uc.setRequestProperty("Content-Type", "application/json");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ } catch ( SSLHandshakeException she ) {
+ logger.error( "SSLHandshakeException from AAF URL " + pURL);
+ } catch ( UnknownHostException uhe ) {
+ logger.error( "UnknownHostException from AAF for URL " + pURL );
+ rc = 500;
+ return rc;
+ }
+ try {
+ rc = uc.getResponseCode();
+ } catch ( SSLHandshakeException she ) {
+ logger.error( "SSLHandshakeException from AAF URL " + 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();
+ }
+ finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ //return responseBody;
+
+ return rc;
+
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafObject.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafObject.java new file mode 100644 index 0000000..f674fa0 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafObject.java @@ -0,0 +1,33 @@ +/*-
+ * ============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.nio.charset.StandardCharsets;
+
+public abstract class AafObject {
+
+ abstract String toJSON();
+
+ public byte[] getBytes() {
+ return toJSON().getBytes(StandardCharsets.UTF_8);
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java b/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java new file mode 100644 index 0000000..4de41e3 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/AafService.java @@ -0,0 +1,131 @@ +/*-
+ * ============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.apache.log4j.Logger;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+public class AafService {
+ public enum ServiceType {
+ AAF_Admin,
+ AAF_TopicMgr
+ }
+ static final Logger logger = Logger.getLogger(AafService.class);
+
+ private AafConnection aaf;
+ private ServiceType ctype;
+ private String aafURL ;
+
+ private String getCred( boolean wPwd ) {
+ String mechIdProperty = null;
+ String pwdProperty = null;
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+
+ if ( ctype == ServiceType.AAF_Admin ) {
+ mechIdProperty = "aaf.AdminUser";
+ pwdProperty = "aaf.AdminPassword";
+ } else if ( ctype == ServiceType.AAF_TopicMgr ){
+ mechIdProperty = "aaf.TopicMgrUser";
+ pwdProperty = "aaf.TopicMgrPassword";
+ } else {
+ logger.error( "Unexpected case for AAF credential type: " + ctype );
+ return null;
+ }
+ String user = p.getProperty( mechIdProperty, "noMechId@domain.netset.com" );
+ String pwd = AndrewDecryptor.valueOf(p.getProperty( pwdProperty, "notSet" ));
+
+ if ( wPwd ) {
+ return user + ":" + pwd;
+ } else {
+ return user;
+ }
+
+
+ }
+
+ public AafService(ServiceType t ) {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ aafURL = p.getProperty( "aaf.URL", "https://authentication.domain.netset.com:8095/proxy/");
+ ctype = t;
+ aaf = new AafConnection( getCred( true ) );
+ }
+
+ public int addPerm(DmaapPerm perm) {
+
+ int rc = -1;
+ logger.info( "entry: setPerm() " );
+ 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;
+
+ case 409:
+ logger.warn( "Perm already exists. Possible conflict.");
+ break;
+
+ case 201:
+ logger.info( "expected response" );
+ break;
+ default :
+ logger.error( "Unexpected response: " + rc );
+ break;
+ }
+
+ return rc;
+ }
+ public int addGrant(DmaapGrant grant ) {
+
+ int rc = -1;
+ logger.info( "entry: setPerm() " );
+
+ 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");
+ break;
+
+ case 409:
+ logger.warn( "Perm already exists. Possible conflict.");
+ break;
+
+ case 201:
+ 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/AndrewDecryptor.java new file mode 100644 index 0000000..a4f6d9d --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/AndrewDecryptor.java @@ -0,0 +1,68 @@ +/*-
+ * ============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.*;
+
+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);
+ }
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/DmaapGrant.java b/src/main/java/org/openecomp/dmaapbc/aaf/DmaapGrant.java new file mode 100644 index 0000000..743dd83 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/DmaapGrant.java @@ -0,0 +1,67 @@ +/*-
+ * ============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 org.apache.log4j.Logger;
+
+public class DmaapGrant extends AafObject {
+ static final Logger logger = Logger.getLogger(DmaapGrant.class);
+
+ private DmaapPerm perm;
+ private String role;
+
+ public DmaapGrant(){
+
+ }
+
+ public DmaapGrant( DmaapPerm p, String r ) {
+ this.perm = p;
+ this.role = r;
+ }
+
+ public DmaapPerm getPerm() {
+ return perm;
+ }
+
+ public void setPerm(DmaapPerm perm) {
+ this.perm = perm;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public String toJSON() {
+
+ String postJSON = String.format(" { \"perm\": %s, \"role\": \"%s\"}",
+ this.perm.toJSON(),
+ this.getRole() );
+ logger.info( "returning JSON: " + postJSON);
+
+ return postJSON;
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/aaf/DmaapPerm.java b/src/main/java/org/openecomp/dmaapbc/aaf/DmaapPerm.java new file mode 100644 index 0000000..d53c270 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/aaf/DmaapPerm.java @@ -0,0 +1,71 @@ +/*-
+ * ============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 org.apache.log4j.Logger;
+
+
+public class DmaapPerm extends AafObject {
+ static final Logger logger = Logger.getLogger(DmaapPerm.class);
+
+ private String permission;
+ private String ptype;
+ private String action;
+
+ public DmaapPerm(String permission, String ptype, String action) {
+ super();
+ this.permission = permission;
+ this.ptype = ptype;
+ this.action = action;
+ }
+ public String getPermission() {
+ return permission;
+ }
+ public void setPermission(String permission) {
+ this.permission = permission;
+ }
+ public String getPtype() {
+ return ptype;
+ }
+ public void setPtype(String ptype) {
+ this.ptype = ptype;
+ }
+ public String getAction() {
+ return action;
+ }
+ public void setAction(String action) {
+ this.action = action;
+ }
+ public String toJSON() {
+
+ String postJSON = String.format(" { \"type\": \"%s\", \"instance\": \"%s\", \"action\": \"%s\"}",
+ this.getPermission(),
+ this.getPtype(),
+ this.getAction() );
+ logger.info( "returning JSON: " + postJSON);
+
+ return postJSON;
+ }
+
+
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/authentication/AuthenticationErrorException.java b/src/main/java/org/openecomp/dmaapbc/authentication/AuthenticationErrorException.java new file mode 100644 index 0000000..cce010c --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/authentication/AuthenticationErrorException.java @@ -0,0 +1,29 @@ +/*-
+ * ============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;
+
+public class AuthenticationErrorException extends Exception {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java b/src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java new file mode 100644 index 0000000..4384c56 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/authentication/DecisionPolicy.java @@ -0,0 +1,157 @@ +/*-
+ * ============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 new file mode 100644 index 0000000..e4fe3cc --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/client/DrProvConnection.java @@ -0,0 +1,453 @@ +/*-
+ * ============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.client;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ConnectException;
+import java.net.ProtocolException;
+import java.net.SocketException;
+import java.net.URL;
+import java.util.ArrayList;
+
+import javax.net.ssl.HttpsURLConnection;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.PropertyConfigurator;
+import org.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.DmaapService;
+import org.openecomp.dmaapbc.util.RandomInteger;
+
+
+
+public class DrProvConnection {
+ static final Logger logger = Logger.getLogger(DrProvConnection.class);
+
+
+ private String provURL;
+
+ private HttpsURLConnection uc;
+
+
+ public DrProvConnection() {
+ provURL = new DmaapService().getDmaap().getDrProvUrl();
+ if ( provURL.length() < 1 ) {
+ logger.error( "Attempting to access PROV before dmaap object is set");
+ }
+
+ }
+
+ public boolean makeFeedConnection() {
+ return makeConnection( provURL );
+ }
+ public boolean makeFeedConnection(String feedId) {
+ return makeConnection( provURL + "/feed/" + feedId );
+ }
+ public boolean makeSubConnection( String subURL ) {
+ String[] parts = subURL.split("/");
+ String revisedURL = provURL + "/" + parts[3] + "/" + parts[4];
+ logger.info( "mapping " + subURL + " 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 );
+ }
+
+ private boolean makeConnection( String pURL ) {
+
+ try {
+ URL u = new URL( pURL );
+ uc = (HttpsURLConnection) u.openConnection();
+ uc.setInstanceFollowRedirects(false);
+ logger.info( "successful connect to " + pURL );
+ return(true);
+ } catch (Exception e) {
+ logger.error("Unexpected error during openConnection of " + pURL );
+ e.printStackTrace();
+ return(false);
+ }
+
+ }
+
+ private String bodyToString( InputStream is ) {
+ logger.info( "is=" + is );
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader( new InputStreamReader(is));
+ String line;
+ try {
+ while ((line = br.readLine()) != null ) {
+ sb.append( line );
+ }
+ } catch (IOException ex ) {
+ logger.error( "IOexception:" + ex);
+ }
+
+ return sb.toString();
+ }
+
+
+ public String doPostFeed( Feed postFeed, ApiError err ) {
+
+ byte[] postData = postFeed.getBytes();
+ logger.info( "post fields=" + postData.toString() );
+ String responsemessage = null;
+ String responseBody = null;
+
+ try {
+ logger.info( "uc=" + uc );
+ uc.setRequestMethod("POST");
+ uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() );
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+ int rc = -1;
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ }
+ rc = uc.getResponseCode();
+ logger.info( "http response code:" + rc );
+ responsemessage = uc.getResponseMessage();
+ logger.info( "responsemessage=" + responsemessage );
+
+
+ if (responsemessage == null) {
+ // work around for glitch in Java 1.7.0.21 and likely others
+ // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
+ String h0 = uc.getHeaderField(0);
+ if (h0 != null) {
+ int i = h0.indexOf(' ');
+ int j = h0.indexOf(' ', i + 1);
+ if (i != -1 && j != -1) {
+ responsemessage = h0.substring(j + 1);
+ }
+ }
+ }
+ if (rc == 201 ) {
+ responseBody = bodyToString( uc.getInputStream() );
+ logger.info( "responseBody=" + responseBody );
+
+ } else {
+ err.setCode( rc );
+ err.setMessage(responsemessage);
+ }
+
+ } catch (ConnectException ce) {
+ logger.error("Connection refused " );
+ err.setCode( 500 );
+ err.setMessage("Backend connection refused");
+ } catch (SocketException se) {
+ logger.error( "Socket exception: unexpected end of file from server" );
+ err.setCode( 500 );
+ err.setMessage( "Unable to read response from DR");
+ } catch (Exception e) {
+ logger.warn("Unable to read response " );
+ e.printStackTrace();
+ try {
+ err.setCode( uc.getResponseCode());
+ err.setMessage(uc.getResponseMessage());
+ } catch (Exception e2) {
+ err.setCode( 500 );
+ err.setMessage("Unable to determine response message");
+ }
+ }
+ finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ return responseBody;
+
+ }
+
+
+ // the POST for /internal/route/ingress doesn't return any data, so needs a different function
+ public int doIngressPost( ApiError err ) {
+
+ String responsemessage = null;
+ int rc = -1;
+
+ try {
+ uc.setRequestMethod("POST");
+// uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed");
+// uc.setRequestProperty( "charset", "utf-8");
+// uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", postFeed.getOwner() );
+// uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+// uc.setUseCaches(false);
+// uc.setDoOutput(true);
+ OutputStream os = null;
+
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ }
+ rc = uc.getResponseCode();
+ logger.info( "http response code:" + rc );
+ responsemessage = uc.getResponseMessage();
+ logger.info( "responsemessage=" + responsemessage );
+
+
+
+ if (rc < 200 || rc >= 300 ) {
+ err.setCode( rc );
+ err.setMessage(responsemessage);
+ }
+ } catch (Exception e) {
+ System.err.println("Unable to read response " );
+ e.printStackTrace();
+ } finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+
+ return rc;
+
+ }
+
+ public String doPostDr_Sub( DR_Sub postSub ) {
+ logger.info( "entry: doPostDr_Sub() " );
+ byte[] postData = postSub.getBytes();
+ logger.info( "post fields=" + postData );
+ String responsemessage = null;
+ String responseBody = null;
+
+ try {
+
+ uc.setRequestMethod("POST");
+
+ uc.setRequestProperty("Content-Type", "application/vnd.att-dr.subscription");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", "DGL" );
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+ int rc = -1;
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ }
+ rc = uc.getResponseCode();
+ logger.info( "http response code:" + rc );
+ responsemessage = uc.getResponseMessage();
+ logger.info( "responsemessage=" + responsemessage );
+
+
+ if (responsemessage == null) {
+ // work around for glitch in Java 1.7.0.21 and likely others
+ // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
+ String h0 = uc.getHeaderField(0);
+ if (h0 != null) {
+ int i = h0.indexOf(' ');
+ int j = h0.indexOf(' ', i + 1);
+ if (i != -1 && j != -1) {
+ responsemessage = h0.substring(j + 1);
+ }
+ }
+ }
+ if (rc == 201 ) {
+ responseBody = bodyToString( uc.getInputStream() );
+ logger.info( "responseBody=" + responseBody );
+
+ }
+
+ } catch (Exception e) {
+ System.err.println("Unable to read response " );
+ e.printStackTrace();
+ } finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ return responseBody;
+
+ }
+
+ public static void main( String[] args ) throws Exception {
+ PropertyConfigurator.configure("log4j.properties");
+ logger.info("Started.");
+
+ RandomInteger ri = new RandomInteger(10000);
+ //String postJSON = String.format("{\"name\": \"dgl feed %d\", \"version\": \"v1.0\", \"description\": \"dgl feed N for testing\", \"authorization\": { \"classification\": \"unclassified\", \"endpoint_addrs\": [],\"endpoint_ids\": [{\"password\": \"test\",\"id\": \"test\"}]}}", ri.next()) ;
+ int i = ri.next();
+ Feed tst = new Feed( "dgl feed " + i,
+ "v1.0",
+ "dgl feed " + i + "for testing",
+ "TEST",
+ "unclassified"
+ );
+ ArrayList<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();
+ logger.info( "post fields=" + postData.toString() );
+ String responsemessage = null;
+ String responseBody = null;
+
+ try {
+ logger.info( "uc=" + uc );
+ uc.setRequestMethod("PUT");
+ uc.setRequestProperty("Content-Type", "application/vnd.att-dr.feed");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "X-ATT-DR-ON-BEHALF-OF", putFeed.getOwner() );
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+ int rc = -1;
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ }
+ rc = uc.getResponseCode();
+ logger.info( "http response code:" + rc );
+ responsemessage = uc.getResponseMessage();
+ logger.info( "responsemessage=" + responsemessage );
+
+
+ if (responsemessage == null) {
+ // work around for glitch in Java 1.7.0.21 and likely others
+ // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
+ String h0 = uc.getHeaderField(0);
+ if (h0 != null) {
+ int i = h0.indexOf(' ');
+ int j = h0.indexOf(' ', i + 1);
+ if (i != -1 && j != -1) {
+ responsemessage = h0.substring(j + 1);
+ }
+ }
+ }
+ if (rc >= 200 && rc < 300 ) {
+ responseBody = bodyToString( uc.getInputStream() );
+ logger.info( "responseBody=" + responseBody );
+
+ } else if ( rc == 404 ) {
+ err.setCode( rc );
+ err.setFields( "feedid");
+ String message = "FeedId " + putFeed.getFeedId() + " not found on DR to update. Out-of-sync condition?";
+ err.setMessage( message );
+ logger.warn(message);
+
+ } else {
+ err.setCode( rc );
+ err.setMessage(responsemessage);
+ }
+
+ } catch (ConnectException ce) {
+ logger.error("Connection refused " );
+ err.setCode( 500 );
+ err.setMessage("Backend connection refused");
+ } catch (SocketException se) {
+ logger.error( "Socket exception: unexpected end of file from server" );
+ err.setCode( 500 );
+ err.setMessage( "Unable to read response from DR");
+ } catch (Exception e) {
+ logger.warn("Unable to read response " );
+ e.printStackTrace();
+ try {
+ err.setCode( uc.getResponseCode());
+ err.setMessage(uc.getResponseMessage());
+ } catch (Exception e2) {
+ err.setCode( 500 );
+ err.setMessage("Unable to determine response message");
+ }
+ } finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ return responseBody;
+ }
+
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java b/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java new file mode 100644 index 0000000..420c315 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/client/MrProvConnection.java @@ -0,0 +1,187 @@ +/*-
+ * ============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.client;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ConnectException;
+import java.net.ProtocolException;
+import java.net.URL;
+import java.net.UnknownHostException;
+import javax.net.ssl.HttpsURLConnection;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+import org.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);
+
+
+ private String provURL;
+
+ private HttpsURLConnection uc;
+
+
+ private String topicMgrCred;
+
+
+
+ public MrProvConnection() {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ topicMgrCred = p.getProperty("aaf.TopicMgrUser", "noIdSet") + ":" + p.getProperty("aaf.TopicMgrPassword", "noPwdSet" );
+
+ }
+
+ public boolean makeTopicConnection( MR_Cluster cluster ) {
+ logger.info( "connect to cluster: " + cluster.getDcaeLocationName());
+
+
+ provURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/topics/create";
+
+ return makeConnection( provURL );
+ }
+
+ private boolean makeConnection( String pURL ) {
+ logger.info( "makeConnection to " + pURL );
+
+ try {
+ URL u = new URL( pURL );
+ uc = (HttpsURLConnection) u.openConnection();
+ uc.setInstanceFollowRedirects(false);
+ logger.info( "successful connect to " + pURL );
+ return(true);
+ } catch( UnknownHostException uhe ){
+ logger.error( "Caught UnknownHostException for " + pURL);
+ return(false);
+ } catch (Exception e) {
+ logger.error("Unexpected error during openConnection of " + pURL );
+ e.printStackTrace();
+ return(false);
+ }
+
+ }
+
+ static String bodyToString( InputStream is ) {
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader( new InputStreamReader(is));
+ String line;
+ try {
+ while ((line = br.readLine()) != null ) {
+ sb.append( line );
+ }
+ } catch (IOException ex ) {
+ logger.error( "IOexception:" + ex);
+ }
+
+ return sb.toString();
+ }
+
+ public String doPostTopic( Topic postTopic ) {
+ String auth = "Basic " + Base64.encodeBase64String(topicMgrCred.getBytes());
+
+
+ String responsemessage = null;
+ int rc = -1;
+
+
+ try {
+ byte[] postData = postTopic.getBytes();
+ logger.info( "post fields=" + postData.toString() );
+ uc.setRequestProperty("Authorization", auth);
+ logger.info( "Authenticating with " + auth );
+ uc.setRequestMethod("POST");
+ uc.setRequestProperty("Content-Type", "application/json");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ } catch ( UnknownHostException uhe ) {
+ logger.error( "UnknownHostException: " + uhe.getMessage() );
+ return new String( "500: " + uhe.getMessage());
+ }catch ( ConnectException ce ) {
+ logger.error( "ConnectException: " + ce.getMessage() );
+ return new String( "500: " + ce.getMessage());
+ }
+ rc = uc.getResponseCode();
+ logger.info( "http response code:" + rc );
+ responsemessage = uc.getResponseMessage();
+ logger.info( "responsemessage=" + responsemessage );
+
+
+ if (responsemessage == null) {
+ // work around for glitch in Java 1.7.0.21 and likely others
+ // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
+ String h0 = uc.getHeaderField(0);
+ if (h0 != null) {
+ int i = h0.indexOf(' ');
+ int j = h0.indexOf(' ', i + 1);
+ if (i != -1 && j != -1) {
+ responsemessage = h0.substring(j + 1);
+ }
+ }
+ }
+ if (rc >= 200 && rc < 300 ) {
+ String responseBody = null;
+ responseBody = bodyToString( uc.getInputStream() );
+ logger.info( "responseBody=" + responseBody );
+ return responseBody;
+
+ }
+
+ } catch (Exception e) {
+ System.err.println("Unable to read response " );
+ e.printStackTrace();
+ }
+ finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ return new String( rc +": " + responsemessage );
+
+ }
+
+
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java b/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java new file mode 100644 index 0000000..1ab2431 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/client/MrTopicConnection.java @@ -0,0 +1,168 @@ +/*-
+ * ============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.client;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ProtocolException;
+import java.net.URL;
+import javax.net.ssl.HttpsURLConnection;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.MR_Cluster;
+
+public class MrTopicConnection {
+ static final Logger logger = Logger.getLogger(MrTopicConnection.class);
+ private String topicURL;
+
+ private HttpsURLConnection uc;
+
+
+ private String mmProvCred;
+
+
+
+ public MrTopicConnection(String user, String pwd ) {
+ mmProvCred = new String( user + ":" + pwd );
+
+ }
+
+ public boolean makeTopicConnection( MR_Cluster cluster, String topic ) {
+ logger.info( "connect to cluster: " + cluster.getFqdn() + " for topic: " + topic );
+
+
+ topicURL = cluster.getTopicProtocol() + "://" + cluster.getFqdn() + ":" + cluster.getTopicPort() + "/events/" + topic ;
+
+ return makeConnection( topicURL );
+ }
+
+ private boolean makeConnection( String pURL ) {
+ logger.info( "makeConnection to " + pURL );
+
+ try {
+ URL u = new URL( pURL );
+ uc = (HttpsURLConnection) u.openConnection();
+ uc.setInstanceFollowRedirects(false);
+ logger.info( "successful connect to " + pURL );
+ return(true);
+ } catch (Exception e) {
+ logger.error("Unexpected error during openConnection of " + pURL );
+ e.printStackTrace();
+ return(false);
+ }
+
+ }
+
+ static String bodyToString( InputStream is ) {
+ StringBuilder sb = new StringBuilder();
+ BufferedReader br = new BufferedReader( new InputStreamReader(is));
+ String line;
+ try {
+ while ((line = br.readLine()) != null ) {
+ sb.append( line );
+ }
+ } catch (IOException ex ) {
+ logger.error( "IOexception:" + ex);
+ }
+
+ return sb.toString();
+ }
+
+ public ApiError doPostMessage( String postMessage ) {
+ ApiError response = new ApiError();
+ String auth = "Basic " + Base64.encodeBase64String(mmProvCred.getBytes());
+
+
+
+ try {
+ byte[] postData = postMessage.getBytes();
+ logger.info( "post fields=" + postMessage );
+ uc.setRequestProperty("Authorization", auth);
+ logger.info( "Authenticating with " + auth );
+ uc.setRequestMethod("POST");
+ uc.setRequestProperty("Content-Type", "application/json");
+ uc.setRequestProperty( "charset", "utf-8");
+ uc.setRequestProperty( "Content-Length", Integer.toString( postData.length ));
+ uc.setUseCaches(false);
+ uc.setDoOutput(true);
+ OutputStream os = null;
+
+
+ try {
+ uc.connect();
+ os = uc.getOutputStream();
+ os.write( postData );
+
+ } catch (ProtocolException pe) {
+ // Rcvd error instead of 100-Continue
+ try {
+ // work around glitch in Java 1.7.0.21 and likely others
+ // without this, Java will connect multiple times to the server to run the same request
+ uc.setDoOutput(false);
+ } catch (Exception e) {
+ }
+ }
+ response.setCode( uc.getResponseCode());
+ logger.info( "http response code:" + response.getCode());
+ response.setMessage( uc.getResponseMessage() );
+ logger.info( "response message=" + response.getMessage() );
+
+
+ if ( response.getMessage() == null) {
+ // work around for glitch in Java 1.7.0.21 and likely others
+ // When Expect: 100 is set and a non-100 response is received, the response message is not set but the response code is
+ String h0 = uc.getHeaderField(0);
+ if (h0 != null) {
+ int i = h0.indexOf(' ');
+ int j = h0.indexOf(' ', i + 1);
+ if (i != -1 && j != -1) {
+ response.setMessage( h0.substring(j + 1) );
+ }
+ }
+ }
+ if ( response.is2xx() ) {
+ response.setFields( bodyToString( uc.getInputStream() ) );
+ logger.info( "responseBody=" + response.getFields() );
+ return response;
+
+ }
+
+ } catch (Exception e) {
+ response.setCode(500);
+ response.setMessage( "Unable to read response");
+ logger.warn( response.getMessage() );
+ e.printStackTrace();
+ }
+ finally {
+ try {
+ uc.disconnect();
+ } catch ( Exception e ) {}
+ }
+ return response;
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/ConnWrapper.java b/src/main/java/org/openecomp/dmaapbc/database/ConnWrapper.java new file mode 100644 index 0000000..1cbba1d --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/ConnWrapper.java @@ -0,0 +1,63 @@ +/*-
+ * ============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.database;
+
+import java.sql.*;
+
+
+public abstract class ConnWrapper<T, U> {
+ protected Connection c;
+ protected PreparedStatement ps;
+ protected ResultSet rs;
+ protected abstract T run(U u) throws Exception;
+ public T protect(ConnectionFactory cf, U u) throws DBException {
+ try {
+ try {
+ return(attempt(cf, u, false));
+ } catch (SQLException sqle) {
+ return(attempt(cf, u, true));
+ }
+ } catch (RuntimeException rte) {
+ throw rte;
+ } catch (Exception e) {
+ throw new DBException(e);
+ }
+ }
+ private T attempt(ConnectionFactory cf, U u, boolean fresh) throws Exception {
+ c = null;
+ ps = null;
+ rs = null;
+ try {
+ c = cf.get(fresh);
+ T ret = run(u);
+ cf.release(c);
+ c = null;
+ return(ret);
+ } finally {
+ if (rs != null) { try { rs.close(); } catch (Exception e) {}}
+ rs = null;
+ if (ps != null) { try { ps.close(); } catch (Exception e) {}}
+ ps = null;
+ if (c != null) { try { c.close(); } catch (Exception e) {}}
+ c = null;
+ }
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java b/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java new file mode 100644 index 0000000..7dd54ae --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/ConnectionFactory.java @@ -0,0 +1,77 @@ +/*-
+ * ============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.database;
+
+import java.sql.*;
+import java.util.*;
+
+import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+public class ConnectionFactory {
+ static final Logger logger = Logger.getLogger(ConnectionFactory.class);
+ static {
+ try {
+ Class.forName("org.postgresql.Driver");
+ } catch (Exception e) {
+ logger.error("Unable to load postgres driver " + e, e);
+ }
+ }
+ private static ConnectionFactory instance = new ConnectionFactory();
+ private String host;
+ private String dbname;
+ private String dbuser;
+ private String dbcr;
+ public ConnectionFactory() {
+ Properties p = DmaapConfig.getConfig();
+ host = p.getProperty("DB.host", "dcae-pstg-write-ftl.domain.notset.com");
+ dbname = p.getProperty("DB.name", "dmaap");
+ dbuser = p.getProperty("DB.user", "dmaap_admin");
+ dbcr = p.getProperty("DB.cred", "test234-ftl");
+ }
+ public static ConnectionFactory getDefaultInstance() {
+ return(instance);
+ }
+ private Connection[] pool = new Connection[5];
+ private int cur;
+ public Connection get(boolean fresh) throws SQLException {
+ if (!fresh) {
+ synchronized(this) {
+ if (cur > 0) {
+ return(pool[--cur]);
+ }
+ }
+ }
+ Properties p = new Properties();
+ p.put("user", dbuser);
+ p.put("password", dbcr);
+ return(DriverManager.getConnection("jdbc:postgresql://" + host + "/" + dbname, p));
+ }
+ public void release(Connection c) {
+ synchronized(this) {
+ if (cur < pool.length) {
+ pool[cur++] = c;
+ return;
+ }
+ }
+ try { c.close(); } catch (Exception e) {}
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBException.java b/src/main/java/org/openecomp/dmaapbc/database/DBException.java new file mode 100644 index 0000000..91193d8 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/DBException.java @@ -0,0 +1,31 @@ +/*-
+ * ============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.database;
+
+import org.apache.log4j.Logger;
+
+public class DBException extends RuntimeException {
+ static final Logger logger = Logger.getLogger(DBException.class);
+ public DBException(Exception e) {
+ super(e);
+ logger.error("Database access problem " + e, e);
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java b/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java new file mode 100644 index 0000000..46e0fb5 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/DBFieldHandler.java @@ -0,0 +1,194 @@ +/*-
+ * ============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.database;
+
+import java.lang.reflect.*;
+import java.sql.*;
+import java.util.*;
+import org.apache.log4j.Logger;
+
+public class DBFieldHandler {
+ static final Logger logger = Logger.getLogger(DBFieldHandler.class);
+ public static interface SqlOp {
+ public Object get(ResultSet rs, int index) throws Exception;
+ public void set(PreparedStatement ps, int index, Object value) throws Exception;
+ }
+ private static class AofString implements SqlOp {
+ public Object get(ResultSet rs, int index) throws Exception {
+ String val = rs.getString(index);
+ if (val == null) {
+ return(null);
+ }
+ String[] ret = val.split(",");
+ for (int i = 0; i < ret.length; i++) {
+ ret[i] = funesc(ret[i]);
+ }
+ return(ret);
+ }
+ public void set(PreparedStatement ps, int index, Object x) throws Exception {
+ String[] val = (String[])x;
+ if (val == null) {
+ ps.setString(index, null);
+ return;
+ }
+ StringBuffer sb = new StringBuffer();
+ String sep = "";
+ for (String s: val) {
+ sb.append(sep).append(fesc(s));
+ sep = ",";
+ }
+ ps.setString(index, sb.toString());
+ }
+ }
+ private static class EnumSql implements SqlOp {
+ private Class enclass;
+ public EnumSql(Class enclass) {
+ this.enclass = enclass;
+ }
+ @SuppressWarnings("unchecked")
+ public Object get(ResultSet rs, int index) throws Exception {
+ String val = rs.getString(index);
+ if (val == null) {
+ return(null);
+ } else {
+ return(Enum.valueOf(enclass, val));
+ }
+ }
+ public void set(PreparedStatement ps, int index, Object value) throws Exception {
+ if (value == null) {
+ ps.setString(index, null);
+ } else {
+ ps.setString(index, value.toString());
+ }
+ }
+ }
+ private static class SqlDate implements SqlOp {
+ public Object get(ResultSet rs, int index) throws Exception {
+ return(rs.getTimestamp(index));
+ }
+ public void set(PreparedStatement ps, int index, Object val) throws Exception {
+ if (val instanceof java.util.Date && !(val instanceof java.sql.Timestamp)) {
+ val = new java.sql.Timestamp(((java.util.Date)val).getTime());
+ }
+ ps.setTimestamp(index, (java.sql.Timestamp)val);
+ }
+ }
+ private static class SqlType implements SqlOp {
+ private Method sqlget;
+ private Method sqlset;
+ private SqlType(String tag) throws Exception {
+ sqlget = ResultSet.class.getMethod("get" + tag, Integer.TYPE);
+ sqlset = PreparedStatement.class.getMethod("set" + tag, Integer.TYPE, sqlget.getReturnType());
+ sqltypes.put(sqlget.getReturnType().getName(), this);
+ }
+ public Object get(ResultSet rs, int index) throws Exception {
+ return(sqlget.invoke(rs, index));
+ }
+ public void set(PreparedStatement ps, int index, Object val) throws Exception {
+ try {
+ sqlset.invoke(ps, index, val);
+ } catch (Exception e) {
+ logger.error("Problem setting field " + index + " to " + val + " statement is " + ps);
+ throw e;
+ }
+ }
+ }
+ private static Map<String, SqlOp> sqltypes;
+ static {
+ sqltypes = new HashMap<String, SqlOp>();
+ sqltypes.put("[Ljava.lang.String;", new AofString());
+ sqltypes.put("java.util.Date", new SqlDate());
+ try {
+ new SqlType("Boolean");
+ new SqlType("Timestamp");
+ new SqlType("Double");
+ new SqlType("Float");
+ new SqlType("Int");
+ new SqlType("Long");
+ new SqlType("Short");
+ new SqlType("String");
+ } catch (Exception e) {
+ logger.error("Problem initializing sql access methods " + e, e);
+ }
+ }
+ private Method objget;
+ private Method objset;
+ private SqlOp sqlop;
+ private int fieldnum;
+ public void copy(Object from, Object to) throws Exception {
+ objset.invoke(to, objget.invoke(from));
+ }
+ public void setKey(Object o, String key) throws Exception {
+ objset.invoke(o, key);
+ }
+ public String getKey(Object o) throws Exception {
+ return((String)objget.invoke(o));
+ }
+ public void toSQL(Object o, PreparedStatement ps) throws Exception {
+ sqlop.set(ps, fieldnum, objget.invoke(o));
+ }
+ public void fromSQL(ResultSet r, Object o) throws Exception {
+ objset.invoke(o, sqlop.get(r, fieldnum));
+ }
+ public DBFieldHandler(Class<?> c, String fieldname, int fieldnum) throws Exception {
+ this(c, fieldname, fieldnum, null);
+ }
+ public DBFieldHandler(Class<?> c, String fieldname, int fieldnum, SqlOp op) throws Exception {
+ this.fieldnum = fieldnum;
+ StringBuffer sb = new StringBuffer();
+ for (String s: fieldname.split("_")) {
+ sb.append(s.substring(0, 1).toUpperCase()).append(s.substring(1));
+ }
+ String camelcase = sb.toString();
+ try {
+ objget = c.getMethod("is" + camelcase);
+ } catch (Exception e) {
+ objget = c.getMethod("get" + camelcase);
+ }
+ objset = c.getMethod("set" + camelcase, objget.getReturnType());
+ sqlop = op;
+ if (sqlop != null) {
+ return;
+ }
+ Class<?> x = objget.getReturnType();
+ if (x.isEnum()) {
+ sqlop = new EnumSql(x);
+ return;
+ }
+ sqlop = sqltypes.get(x.getName());
+ if (sqlop != null) {
+ return;
+ }
+ logger.error("No field handler for class " + c.getName() + " field " + fieldname + " index " + fieldnum + " type " + x.getName());
+ }
+ public static String fesc(String s) {
+ if (s == null) {
+ return(s);
+ }
+ return(s.replaceAll("@", "@a").replaceAll(";", "@s").replaceAll(",", "@c"));
+ }
+ public static String funesc(String s) {
+ if (s == null) {
+ return(s);
+ }
+ return(s.replaceAll("@c", ",").replaceAll("@s", ";").replaceAll("@a", "@"));
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBMap.java b/src/main/java/org/openecomp/dmaapbc/database/DBMap.java new file mode 100644 index 0000000..c195245 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/DBMap.java @@ -0,0 +1,138 @@ +/*-
+ * ============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.database;
+
+import java.sql.*;
+import java.util.*;
+
+public class DBMap<C> extends TableHandler<C> implements Map<String, C> {
+ public DBMap(Class<C> cls, String tabname, String keyfield) throws Exception {
+ this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyfield);
+ }
+ public DBMap(ConnectionFactory cf, Class<C> cls, String tabname, String keyfield) throws Exception {
+ super(cf, cls, tabname, keyfield);
+ }
+ public void clear() throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+ public boolean containsKey(Object key) throws DBException {
+ return(get(key) != null);
+ }
+ public boolean containsValue(Object value) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+ public boolean isEmpty() {
+ return(false);
+ }
+ public Set<Map.Entry<String, C>> entrySet() throws DBException {
+ return(list());
+ }
+ public Set<String> keySet() throws DBException {
+ Set<String> ret = new HashSet<String>();
+ for (Map.Entry<String, C> x: list()) {
+ ret.add(x.getKey());
+ }
+ return(ret);
+ }
+ public void putAll(Map<? extends String, ? extends C> m) throws UnsupportedOperationException {
+ throw new UnsupportedOperationException();
+ }
+ public int size() {
+ return(2);
+ }
+ public Collection<C> values() throws DBException {
+ Collection<C> ret = new Vector<C>();
+ for (Map.Entry<String, C> x: list()) {
+ ret.add(x.getValue());
+ }
+ return(ret);
+ }
+ public C get(Object key) throws DBException {
+ if (!(key instanceof String)) {
+ return(null);
+ }
+ return((new ConnWrapper<C, String>() {
+ protected C run(String key) throws Exception {
+ ps = c.prepareStatement(getstmt);
+ ps.setString(1, (String)key);
+ rs = ps.executeQuery();
+ if (!rs.next()) {
+ return(null);
+ }
+ C ret = cls.newInstance();
+ for (DBFieldHandler f: fields) {
+ f.fromSQL(rs, ret);
+ }
+ return(ret);
+ }
+ }).protect(cf, (String)key));
+ }
+ public Set<Map.Entry<String, C>> list() throws DBException {
+ return((new ConnWrapper<Set<Map.Entry<String, C>>, Object>() {
+ protected Set<Map.Entry<String, C>> run(Object junk) throws Exception {
+ DBFieldHandler keyfield = fields[fields.length - 1];
+ ps = c.prepareStatement(liststmt);
+ rs = ps.executeQuery();
+ Set<Map.Entry<String, C>> ret = new HashSet<Map.Entry<String, C>>();
+ while (rs.next()) {
+ C val = cls.newInstance();
+ for (DBFieldHandler f: fields) {
+ f.fromSQL(rs, val);
+ }
+ String key = keyfield.getKey(val);
+ ret.add(new AbstractMap.SimpleEntry<String, C>(key, val));
+ }
+ return(ret);
+ }
+ }).protect(cf, null));
+ }
+ public C put(String key, C val) throws DBException {
+ try {
+ fields[fields.length - 1].setKey(val, key);
+ } catch (Exception e) {
+ throw new DBException(e);
+ }
+ PreparedStatement ps = null;
+ return((new ConnWrapper<C, C>() {
+ protected C run(C val) throws Exception {
+ ps = c.prepareStatement(insorreplstmt);
+ for (DBFieldHandler f: fields) {
+ f.toSQL(val, ps);
+ }
+ ps.executeUpdate();
+ return(null);
+ }
+ }).protect(cf, val));
+ }
+ public C remove(Object key) throws DBException {
+ if (!(key instanceof String)) {
+ return(null);
+ }
+ return((new ConnWrapper<C, String>() {
+ protected C run(String key) throws Exception {
+ ps = c.prepareStatement(delstmt);
+ ps.setString(1, key);
+ ps.executeUpdate();
+ return(null);
+ }
+ }).protect(cf, (String)key));
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DBSingleton.java b/src/main/java/org/openecomp/dmaapbc/database/DBSingleton.java new file mode 100644 index 0000000..25ed793 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/DBSingleton.java @@ -0,0 +1,98 @@ +/*-
+ * ============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.database;
+
+import java.sql.*;
+import java.util.*;
+
+import org.openecomp.dmaapbc.util.Singleton;
+
+public class DBSingleton<C> extends TableHandler<C> implements Singleton<C> {
+ private C singleton;
+ public DBSingleton(Class<C> cls, String tabname) throws Exception {
+ this(ConnectionFactory.getDefaultInstance(), cls, tabname);
+ }
+ public DBSingleton(ConnectionFactory cf, Class<C> cls, String tabname) throws Exception {
+ super(cf, cls, tabname, null);
+ singleton = cls.newInstance();
+ }
+ public C get() throws DBException {
+ return((new ConnWrapper<C, Object>() {
+ protected C run(Object junk) throws Exception {
+ ps = c.prepareStatement(getstmt);
+ rs = ps.executeQuery();
+ if (!rs.next()) {
+ return(null);
+ }
+ for (DBFieldHandler f: fields) {
+ f.fromSQL(rs, singleton);
+ }
+ return(singleton);
+ }
+ }).protect(cf, null));
+ }
+ public void init(C val) throws DBException {
+ if (get() != null) {
+ return;
+ }
+ (new ConnWrapper<Void, C>() {
+ protected Void run(C val) throws Exception {
+ ps = c.prepareStatement(initstmt);
+ for (DBFieldHandler f: fields) {
+ f.toSQL(val, ps);
+ }
+ ps.executeUpdate();
+ if (val != singleton) {
+ for (DBFieldHandler f: fields) {
+ f.copy(val, singleton);
+ }
+ }
+ return(null);
+ }
+ }).protect(cf, val);
+ }
+ public void update(C val) throws DBException {
+ (new ConnWrapper<Void, C>() {
+ protected Void run(C val) throws Exception {
+ ps = c.prepareStatement(insorreplstmt);
+ for (DBFieldHandler f: fields) {
+ f.toSQL(val, ps);
+ }
+ ps.executeUpdate();
+ if (val != singleton) {
+ for (DBFieldHandler f: fields) {
+ f.copy(val, singleton);
+ }
+ }
+ return(null);
+ }
+ }).protect(cf, val);
+ }
+ public void remove() throws DBException {
+ (new ConnWrapper<Void, Object>() {
+ protected Void run(Object junk) throws Exception {
+ ps = c.prepareStatement(delstmt);
+ ps.executeUpdate();
+ return(null);
+ }
+ }).protect(cf, null);
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java b/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java new file mode 100644 index 0000000..973d592 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/DatabaseClass.java @@ -0,0 +1,268 @@ +/*-
+ * ============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.database;
+
+import java.util.*;
+import java.sql.*;
+
+import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.model.DR_Node;
+import org.openecomp.dmaapbc.model.DR_Pub;
+import org.openecomp.dmaapbc.model.DR_Sub;
+import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.model.Dmaap;
+import org.openecomp.dmaapbc.model.Feed;
+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.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);
+
+ private static Singleton<Dmaap> dmaap;
+ private static Map<String, DcaeLocation> dcaeLocations;
+ private static Map<String, DR_Node> dr_nodes;
+ private static Map<String, DR_Pub> dr_pubs;
+ private static Map<String, DR_Sub> dr_subs;
+ private static Map<String, MR_Client> mr_clients;
+ private static Map<String, MR_Cluster> mr_clusters;
+ private static Map<String, Feed> feeds;
+ private static Map<String, Topic> topics;
+ private static Map<String, MirrorMaker> mirrors;
+
+ private static long lastTime = 0L;
+
+ private static class MirrorVectorHandler implements DBFieldHandler.SqlOp {
+ public Object get(ResultSet rs, int index) throws Exception {
+ String val = rs.getString(index);
+ if (val == null) {
+ return(null);
+ }
+ Set<ReplicationVector> rv = new HashSet<ReplicationVector>();
+ for (String s: val.split(",")) {
+ String[] f = s.split(";");
+ if (f.length < 3) {
+ continue;
+ }
+ rv.add(new ReplicationVector(DBFieldHandler.funesc(f[0]), DBFieldHandler.funesc(f[1]), DBFieldHandler.funesc(f[2])));
+ }
+ return(rv);
+ }
+ public void set(PreparedStatement ps, int index, Object val) throws Exception {
+ if (val == null) {
+ ps.setString(index, null);
+ return;
+ }
+ Set xv = (Set)val;
+ StringBuffer sb = new StringBuffer();
+ String sep = "";
+ for (Object o: xv) {
+ ReplicationVector rv = (ReplicationVector)o;
+ sb.append(sep).append(DBFieldHandler.fesc(rv.getFqtn())).append(';').append(DBFieldHandler.fesc(rv.getSourceCluster())).append(';').append(DBFieldHandler.fesc(rv.getTargetCluster()));
+ sep = ",";
+ }
+ ps.setString(index, sb.toString());
+ }
+ }
+
+ // modified version of MirrorVectorHandler for Topics
+ private static class MirrorTopicsHandler implements DBFieldHandler.SqlOp {
+ public Object get(ResultSet rs, int index) throws Exception {
+ String val = rs.getString(index);
+ if (val == null) {
+ return(null);
+ }
+ List<String> rv = new ArrayList<String>();
+ for (String s: val.split(",")) {
+ //String[] f = s.split(";");
+ //if (f.length < 3) {
+ // continue;
+ //}
+ rv.add(new String(s));
+ }
+ return(rv);
+ }
+ public void set(PreparedStatement ps, int index, Object val) throws Exception {
+ if (val == null) {
+ ps.setString(index, null);
+ return;
+ }
+ @SuppressWarnings("unchecked")
+ List<String> xv = (List<String>)val;
+ StringBuffer sb = new StringBuffer();
+ String sep = "";
+ for (Object o: xv) {
+ String rv = (String)o;
+ sb.append(sep).append(DBFieldHandler.fesc(rv));
+ sep = ",";
+ }
+ ps.setString(index, sb.toString());
+ }
+ }
+ public static Singleton<Dmaap> getDmaap() {
+ return dmaap;
+ }
+
+
+
+ public static Map<String, DcaeLocation> getDcaeLocations() {
+ return dcaeLocations;
+ }
+
+ public static Map<String, DR_Node> getDr_nodes() {
+ return dr_nodes;
+ }
+
+ public static Map<String, DR_Sub> getDr_subs() {
+ return dr_subs;
+ }
+ public static Map<String, DR_Pub> getDr_pubs() {
+ return dr_pubs;
+ }
+
+ public static Map<String, MR_Client> getMr_clients() {
+ return mr_clients;
+ }
+
+
+ public static Map<String, MR_Cluster> getMr_clusters() {
+ return mr_clusters;
+ }
+
+ public static Map<String, Feed> getFeeds() {
+ return feeds;
+ }
+ public static Map<String, Topic> getTopics() {
+ return topics;
+ }
+ public static Map<String, MirrorMaker> getMirrorMakers() {
+ return mirrors;
+ }
+
+ static {
+ try {
+ logger.info( "begin static initialization");
+ logger.info( "initializing dmaap" );
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ if ("true".equalsIgnoreCase(p.getProperty("UsePGSQL", "false"))) {
+ logger.info("Data from database");
+ try {
+ LoadSchema.upgrade();
+ } catch (Exception e) {
+ logger.warn("Problem updating DB schema", e);
+ }
+ try {
+ dmaap = new DBSingleton<Dmaap>(Dmaap.class, "dmaap");
+ dcaeLocations = new DBMap<DcaeLocation>(DcaeLocation.class, "dcae_location", "dcae_location_name");
+ dr_nodes = new DBMap<DR_Node>(DR_Node.class, "dr_node", "fqdn");
+ dr_pubs = new DBMap<DR_Pub>(DR_Pub.class, "dr_pub", "pub_id");
+ dr_subs = new DBMap<DR_Sub>(DR_Sub.class, "dr_sub", "sub_id");
+ 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");
+ 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);
+ System.exit(1);
+ }
+ } else {
+ logger.info("Data from memory");
+ dmaap = new Singleton<Dmaap>() {
+ private Dmaap dmaap;
+ public void remove() {
+ dmaap = null;
+ }
+ public void init(Dmaap val) {
+ if (dmaap == null) {
+ dmaap = val;
+ }
+ }
+ public Dmaap get() {
+ return(dmaap);
+ }
+ public void update(Dmaap nd) {
+ dmaap.setVersion(nd.getVersion());
+ dmaap.setTopicNsRoot(nd.getTopicNsRoot());
+ dmaap.setDmaapName(nd.getDmaapName());
+ dmaap.setDrProvUrl(nd.getDrProvUrl());
+ dmaap.setBridgeAdminTopic(nd.getBridgeAdminTopic());
+ dmaap.setLoggingUrl(nd.getLoggingUrl());
+ dmaap.setNodeKey(nd.getNodeKey());
+ dmaap.setAccessKeyOwner(nd.getAccessKeyOwner());
+ }
+ };
+ dcaeLocations = new HashMap<String, DcaeLocation>();
+ dr_nodes = new HashMap<String, DR_Node>();
+ dr_pubs = new HashMap<String, DR_Pub>();
+ dr_subs = new HashMap<String, DR_Sub>();
+ mr_clients = new HashMap<String, MR_Client>();
+ mr_clusters = new HashMap<String, MR_Cluster>();
+ feeds = new HashMap<String, Feed>();
+ topics = new HashMap<String, Topic>();
+ mirrors = new HashMap<String, MirrorMaker>();
+ }
+ dmaap.init(new Dmaap("0", "", "", "", "", "", "", ""));
+ // check for, and set up initial data, if it isn't already there
+ Dmaap dmx = dmaap.get();
+ if ("0".equals(dmx.getVersion())) {
+
+ dmx = new Dmaap("0", "", "", "", "", "", "", "");
+ dmx.setDmaapName(p.getProperty("DmaapName"));
+ dmx.setDrProvUrl("https://" + p.getProperty("DR.provhost"));
+ dmx.setVersion("1");
+ dmx.setTopicNsRoot("org.openecomp.dcae.dmaap");
+ dmx.setBridgeAdminTopic("DCAE_MM_AGENT");
+
+ (new DmaapService()).addDmaap(dmx);
+ }
+ } catch (Exception e) {
+ logger.error("Error loading database " + e, e);
+ }
+ }
+
+ public synchronized static String getNextClientId() {
+
+ long id = System.currentTimeMillis();
+ if ( id <= lastTime ) {
+ id = lastTime + 1;
+ }
+ lastTime = id;
+ return Long.toString(id);
+ }
+
+
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java b/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java new file mode 100644 index 0000000..bcf838a --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/LoadSchema.java @@ -0,0 +1,105 @@ +/*-
+ * ============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.database;
+
+import java.io.*;
+import java.sql.*;
+import org.apache.log4j.Logger;
+
+public class LoadSchema {
+ static Logger logger = Logger.getLogger(LoadSchema.class);
+ static int getVer(Statement s) throws SQLException {
+ ResultSet rs = null;
+ try {
+ rs = s.executeQuery("SELECT version FROM dmaapbc_sch_ver");
+ rs.next();
+ return(rs.getInt(1));
+ } finally {
+ if (rs != null) {
+ rs.close();
+ }
+ }
+ }
+ static void upgrade() throws SQLException {
+ ConnectionFactory cf = ConnectionFactory.getDefaultInstance();
+ Connection c = null;
+ Statement stmt = null;
+ InputStream is = null;
+ try {
+ c = cf.get(true);
+ stmt = c.createStatement();
+ int newver = -1;
+ try {
+ newver = getVer(stmt);
+ } catch (Exception e) {}
+ logger.info("Database schema currently at version " + newver++);
+ while ((is = LoadSchema.class.getClassLoader().getResourceAsStream("schema_" + newver + ".sql")) != null) {
+ logger.info("Upgrading database schema to version " + newver);
+ BufferedReader br = new BufferedReader(new InputStreamReader(is));
+ String s;
+ String sofar = null;
+ while ((s = br.readLine()) != null) {
+ logger.info("SCHEMA: " + s);
+ s = s.trim();
+ if (s.length() == 0 || s.startsWith("--")) {
+ continue;
+ }
+ if (sofar == null) {
+ sofar = s;
+ } else {
+ sofar = sofar + " " + s;
+ }
+ if (s.endsWith(";")) {
+ sofar = sofar.substring(0, sofar.length() - 1);
+ boolean ignore = false;
+ if (sofar.startsWith("@")) {
+ ignore = true;
+ sofar = sofar.substring(1).trim();
+ }
+ try {
+ stmt.execute(sofar);
+ } catch (SQLException sqle) {
+ if (!ignore) {
+ throw sqle;
+ }
+ }
+ sofar = null;
+ }
+ }
+ is.close();
+ is = null;
+ if (getVer(stmt) != newver) {
+ throw new SQLException("Schema version not properly updated to " + newver + " by upgrade script");
+ }
+ logger.info("Upgrade to database schema version " + newver + " successful");
+ newver++;
+ }
+ } catch (IOException ioe) {
+ throw new SQLException(ioe);
+ } finally {
+ if (stmt != null) { try { stmt.close(); } catch (Exception e) {}}
+ if (c != null) { try { c.close(); } catch (Exception e) {}}
+ }
+ }
+ public static void main(String[] args) throws Exception {
+ upgrade();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/database/TableHandler.java b/src/main/java/org/openecomp/dmaapbc/database/TableHandler.java new file mode 100644 index 0000000..2104123 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/database/TableHandler.java @@ -0,0 +1,115 @@ +/*-
+ * ============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.database;
+
+import java.util.*;
+import java.lang.reflect.*;
+import java.sql.*;
+
+class TableHandler<C> {
+ protected ConnectionFactory cf;
+ protected boolean haskey;
+ protected String delstmt;
+ protected String insorreplstmt;
+ protected String getstmt;
+ protected String liststmt;
+ protected String initstmt;
+ protected Class<C> cls;
+ protected DBFieldHandler[] fields;
+ private static Map<String, Map<String, DBFieldHandler.SqlOp>> exceptions = new HashMap<String, Map<String, DBFieldHandler.SqlOp>>();
+ public static void setSpecialCase(String dbtabname, String dbfldname, DBFieldHandler.SqlOp handler) {
+ Map<String, DBFieldHandler.SqlOp> m = exceptions.get(dbtabname);
+ if (m == null) {
+ m = new HashMap<String, DBFieldHandler.SqlOp>();
+ exceptions.put(dbtabname, m);
+ }
+ m.put(dbfldname, handler);
+ }
+ public static DBFieldHandler.SqlOp getSpecialCase(String dbtabname, String dbfldname) {
+ Map<String, DBFieldHandler.SqlOp> m = exceptions.get(dbtabname);
+ if (m != null) {
+ return(m.get(dbfldname));
+ }
+ return(null);
+ }
+ protected TableHandler(Class<C> cls, String tabname, String keyname) throws Exception {
+ this(ConnectionFactory.getDefaultInstance(), cls, tabname, keyname);
+ }
+ protected TableHandler(ConnectionFactory cf, Class<C> cls, String tabname, String keyname) throws Exception {
+ this.cf = cf;
+ Connection c = null;
+ try {
+ c = cf.get(false);
+ setup(c.getMetaData(), cls, tabname, keyname);
+ } finally {
+ if (c != null) {
+ cf.release(c);
+ }
+ }
+ }
+ private void setup(DatabaseMetaData dmd, Class<C> cls, String tabname, String keyname) throws Exception {
+ this.cls = cls;
+ Vector<DBFieldHandler> h = new Vector<DBFieldHandler>();
+ ResultSet rs = dmd.getColumns("", "public", tabname, null);
+ StringBuffer sb1 = new StringBuffer();
+ StringBuffer sb2 = new StringBuffer();
+ StringBuffer sb3 = new StringBuffer();
+ int count = 0;
+ while (rs.next()) {
+ if (!rs.getString(3).equals(tabname)) {
+ continue;
+ }
+ String cname = rs.getString(4);
+ if (cname.equals(keyname)) {
+ haskey = true;
+ continue;
+ }
+ sb1.append(", ").append(cname);
+ sb2.append(", ?");
+ sb3.append(", EXCLUDED.").append(cname);
+ count++;
+ h.add(new DBFieldHandler(cls, cname, count, getSpecialCase(tabname, cname)));
+ }
+ if (count == 0) {
+ throw new SQLException("Table " + tabname + " not found");
+ }
+ String clist = sb1.substring(2);
+ String qlist = sb2.substring(2);
+ String elist = sb3.substring(2);
+ if (keyname != null && !haskey) {
+ throw new SQLException("Table " + tabname + " does not have key column " + keyname + " not found");
+ }
+ if (haskey) {
+ count++;
+ h.add(new DBFieldHandler(cls, keyname, count, getSpecialCase(tabname, keyname)));
+ delstmt = "DELETE FROM " + tabname + " WHERE " + keyname + " = ?";
+ insorreplstmt = "INSERT INTO " + tabname + " (" + clist + ", " + keyname + ") VALUES (" + qlist + ", ?) ON CONFLICT(" + keyname + ") DO UPDATE SET (" + clist + ") = (" + elist + ")";
+ getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname + " WHERE " + keyname + " = ?";
+ liststmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname;
+ } else {
+ delstmt = "DELETE FROM " + tabname;
+ initstmt = "INSERT INTO " + tabname + " (" + clist + ") VALUES (" + qlist + ")";
+ insorreplstmt = "UPDATE " + tabname + " SET (" + clist + ") = (" + qlist + ")";
+ getstmt = "SELECT " + clist + ", " + keyname + " FROM " + tabname;
+ }
+ fields = h.toArray(new DBFieldHandler[h.size()]);
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/ApiError.java b/src/main/java/org/openecomp/dmaapbc/model/ApiError.java new file mode 100644 index 0000000..0659f65 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/ApiError.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.model;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public class ApiError {
+ private int code;
+ private String message;
+ private String fields;
+
+ public int getCode() {
+ return code;
+ }
+ public void setCode(int rc) {
+ this.code = rc;
+ }
+ public String getMessage() {
+ return message;
+ }
+ public void setMessage(String message) {
+ this.message = message;
+ }
+ public String getFields() {
+ return fields;
+ }
+ public void setFields(String fields) {
+ this.fields = fields;
+ }
+ public String toString() {
+ return String.format( "code=%d msg=%s fields=%s", this.code, this.message, this.fields );
+ }
+ public boolean is2xx() {
+
+ return code >= 200 && code < 300;
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/BrTopic.java b/src/main/java/org/openecomp/dmaapbc/model/BrTopic.java new file mode 100644 index 0000000..e8a697e --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/BrTopic.java @@ -0,0 +1,65 @@ +/*-
+ * ============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 javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.log4j.Logger;
+
+@XmlRootElement
+public class BrTopic {
+ static final Logger logger = Logger.getLogger(BrTopic.class);
+
+ private String brSource;
+ private String brTarget;
+ private int topicCount;
+
+ // no-op constructor used by framework
+ public BrTopic() {
+ }
+
+ public String getBrSource() {
+ return brSource;
+ }
+
+ public void setBrSource(String brSource) {
+ this.brSource = brSource;
+ }
+
+ public String getBrTarget() {
+ return brTarget;
+ }
+
+ public void setBrTarget(String brTarget) {
+ this.brTarget = brTarget;
+ }
+
+ public int getTopicCount() {
+ return topicCount;
+ }
+
+ public void setTopicCount(int topicCount) {
+ this.topicCount = topicCount;
+ }
+
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DR_Node.java b/src/main/java/org/openecomp/dmaapbc/model/DR_Node.java new file mode 100644 index 0000000..f3ff1fe --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/DR_Node.java @@ -0,0 +1,78 @@ +/*-
+ * ============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 javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public class DR_Node extends DmaapObject {
+ private String fqdn;
+ private String dcaeLocationName;
+ private String hostName;
+ private String version;
+
+ public DR_Node() {
+
+ }
+
+ public DR_Node( String f,
+ String dLN,
+ String hN,
+ String v ) {
+ this.fqdn = f;
+ this.dcaeLocationName = dLN;
+ this.hostName = hN;
+ this.version = v;
+ }
+
+ public String getFqdn() {
+ return fqdn;
+ }
+
+ public void setFqdn(String fqdn) {
+ this.fqdn = fqdn;
+ }
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+ public String getHostName() {
+ return hostName;
+ }
+
+ public void setHostName(String hostName) {
+ this.hostName = hostName;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java b/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java new file mode 100644 index 0000000..2e3e894 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/DR_Pub.java @@ -0,0 +1,136 @@ +/*-
+ * ============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 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;
+ private String feedId;
+ private String pubId;
+
+
+ public DR_Pub() {
+ status = DmaapObject_Status.EMPTY;
+
+ }
+
+ public DR_Pub( String dLN ) {
+ this.dcaeLocationName = dLN;
+ this.status = DmaapObject_Status.STAGED;
+ }
+
+ public DR_Pub( String dLN,
+ String uN,
+ String uP,
+ String fI,
+ String pI ) {
+ this.dcaeLocationName = dLN;
+ this.username = uN;
+ this.userpwd = uP;
+ this.feedId = fI;
+ this.pubId = pI;
+ this.status = DmaapObject_Status.VALID;
+ }
+
+
+ public DR_Pub( String dLN,
+ String uN,
+ String uP,
+ String fI ) {
+ this.dcaeLocationName = dLN;
+ this.username = uN;
+ this.userpwd = uP;
+ this.feedId = fI;
+ this.pubId = fI + "." + DR_Pub.nextKey();
+ this.status = DmaapObject_Status.VALID;
+ }
+
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getUserpwd() {
+ return userpwd;
+ }
+
+ public void setUserpwd(String userpwd) {
+ this.userpwd = userpwd;
+ }
+
+ public String getFeedId() {
+ return feedId;
+ }
+
+ public void setFeedId(String feedId) {
+ this.feedId = feedId;
+ }
+
+ public String getPubId() {
+ return pubId;
+ }
+
+ public void setPubId(String pubId) {
+ this.pubId = pubId;
+ }
+
+ public void setNextPubId() {
+ this.pubId = this.feedId + "." + DR_Pub.nextKey();
+ }
+
+ public DR_Pub setRandomUserName() {
+ RandomString r = new RandomString(15);
+ this.username = "tmp_" + r.nextString();
+ return this;
+ }
+ public DR_Pub setRandomPassword() {
+ RandomString r = new RandomString(15);
+ this.userpwd = r.nextString();
+ return this;
+ }
+
+ public static String nextKey() {
+ RandomString ri = new RandomString(5);
+ return ri.nextString();
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java b/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java new file mode 100644 index 0000000..0184a14 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/DR_Sub.java @@ -0,0 +1,206 @@ +/*-
+ * ============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.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;
+
+@XmlRootElement
+public class DR_Sub extends DmaapObject {
+ static final Logger logger = Logger.getLogger(DR_Sub.class);
+
+ private String dcaeLocationName;
+ private String username;
+ private String userpwd;
+ private String feedId;
+ private String deliveryURL;
+ private String logURL;
+ private String subId;
+ private boolean use100;
+ private boolean suspended;
+ private String owner;
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public boolean isSuspended() {
+ return suspended;
+ }
+
+ public void setSuspended(boolean suspended) {
+ this.suspended = suspended;
+ }
+
+
+
+ public boolean isUse100() {
+ return use100;
+ }
+
+ public void setUse100(boolean use100) {
+ this.use100 = use100;
+ }
+
+ public DR_Sub() {
+
+ }
+
+ public DR_Sub( String dLN,
+ String uN,
+ String uP,
+ String fI,
+ String dU,
+ String lU,
+ boolean u100 ) {
+ this.dcaeLocationName = dLN;
+ this.username = uN;
+ this.userpwd = uP;
+ this.feedId = fI;
+ this.deliveryURL = dU;
+ this.logURL = lU;
+ this.use100 = u100;
+ this.setStatus( DmaapObject_Status.NEW );
+ this.subId = "0";
+ }
+
+ public DR_Sub ( String json ) {
+ logger.info( "DR_Sub:" + json );
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj;
+
+ try {
+ jsonObj = (JSONObject) parser.parse( json );
+ } catch ( ParseException pe ) {
+ logger.error( "Error parsing provisioning data: " + json );
+ this.setStatus( DmaapObject_Status.INVALID );
+ return;
+ }
+
+ this.setOwner( (String) jsonObj.get("subscriber"));
+ this.setSuspended( (boolean) jsonObj.get("suspend"));
+
+ JSONObject links = (JSONObject) jsonObj.get("links");
+ String url = (String) links.get("feed");
+ this.setFeedId( url.substring( url.lastIndexOf('/')+1, url.length() ));
+ url = (String) links.get("self");
+ this.setSubId( url.substring( url.lastIndexOf('/')+1, url.length() ));
+ logger.info( "feedid="+ this.getFeedId() );
+ this.setLogURL( (String) links.get("log") );
+
+ JSONObject del = (JSONObject) jsonObj.get("delivery");
+ this.setDeliveryURL( (String) del.get("url") );
+ this.setUsername( (String) del.get("user"));
+ this.setUserpwd( (String) del.get( "password"));
+ this.setUse100((boolean) del.get( "use100"));
+
+ this.setStatus( DmaapObject_Status.VALID );
+
+ logger.info( "new DR_Sub returning");
+ }
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+
+ public String getUserpwd() {
+ return userpwd;
+ }
+
+ public void setUserpwd(String userpwd) {
+ this.userpwd = userpwd;
+ }
+
+ public String getFeedId() {
+ return feedId;
+ }
+
+ public void setFeedId(String feedId) {
+ this.feedId = feedId;
+ }
+
+ public String getDeliveryURL() {
+ return deliveryURL;
+ }
+
+ public void setDeliveryURL(String deliveryURL) {
+ this.deliveryURL = deliveryURL;
+ }
+
+ public String getLogURL() {
+ return logURL;
+ }
+
+ public void setLogURL(String logURL) {
+ this.logURL = logURL;
+ }
+
+ public String getSubId() {
+ return subId;
+ }
+
+ public void setSubId(String subId) {
+ this.subId = subId;
+ }
+
+
+
+ public byte[] getBytes() {
+ return toProvJSON().getBytes(StandardCharsets.UTF_8);
+ }
+ // returns the DR_Sub object in JSON that conforms to DR Prov Server expectations
+ public String toProvJSON() {
+
+ // 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\"}",
+ this.getDeliveryURL(),
+ this.getUsername(),
+ this.getUserpwd(),
+ this.isUse100() );
+
+ logger.info( postJSON );
+ return postJSON;
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DcaeLocation.java b/src/main/java/org/openecomp/dmaapbc/model/DcaeLocation.java new file mode 100644 index 0000000..f0ef481 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/DcaeLocation.java @@ -0,0 +1,103 @@ +/*-
+ * ============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 javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.log4j.Logger;
+
+@XmlRootElement
+public class DcaeLocation extends DmaapObject {
+ static final Logger logger = Logger.getLogger(MR_Cluster.class);
+ private String clli;
+ private String dcaeLayer;
+ private String dcaeLocationName;
+ private String openStackAvailabilityZone;
+ private String subnet;
+
+
+
+ public DcaeLocation() {
+
+ }
+
+ public DcaeLocation( String c,
+ String dL,
+ String dLN,
+ String oSAZ,
+ String s ) {
+
+ this.clli = c;
+ this.dcaeLayer = dL;
+ this.dcaeLocationName = dLN;
+ this.openStackAvailabilityZone = oSAZ;
+ this.subnet = s;
+ }
+
+ public String getClli() {
+ return clli;
+ }
+
+ public void setClli(String clli) {
+ this.clli = clli;
+ }
+
+ public String getDcaeLayer() {
+ return dcaeLayer;
+ }
+
+ public void setDcaeLayer(String dcaeLayer) {
+ this.dcaeLayer = dcaeLayer;
+ }
+ public boolean isCentral() {
+ return dcaeLayer != null && dcaeLayer.contains("central");
+ }
+ public boolean isLocal() {
+ return dcaeLayer != null && dcaeLayer.contains("local");
+ }
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+
+
+ public String getOpenStackAvailabilityZone() {
+ return openStackAvailabilityZone;
+ }
+
+ public void setOpenStackAvailabilityZone(String openStackAvailabilityZone) {
+ this.openStackAvailabilityZone = openStackAvailabilityZone;
+ }
+
+ public String getSubnet() {
+ return subnet;
+ }
+
+ public void setSubnet(String subnet) {
+ this.subnet = subnet;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java b/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java new file mode 100644 index 0000000..362c184 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/Dmaap.java @@ -0,0 +1,133 @@ +/*-
+ * ============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 javax.xml.bind.annotation.XmlRootElement;
+
+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;
+ private String drProvUrl;
+ private String bridgeAdminTopic;
+ private String loggingUrl;
+ private String nodeKey;
+ private String accessKeyOwner;
+
+
+
+ // no-op constructor used by framework
+ public Dmaap() {
+
+ }
+
+ public Dmaap( String ver,
+ String tnr,
+ String dn,
+ String dpu,
+ String lu,
+ String bat,
+ String nk,
+ String ako ) {
+ this.version = ver;
+ this.topicNsRoot = tnr;
+ this.dmaapName = dn;
+ this.drProvUrl = dpu;
+ this.bridgeAdminTopic = bat;
+ this.loggingUrl = lu;
+ this.nodeKey = nk;
+ this.accessKeyOwner = ako;
+ this.setStatus( DmaapObject_Status.NEW );
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getTopicNsRoot() {
+ return topicNsRoot;
+ }
+
+ public void setTopicNsRoot(String topicNsRoot) {
+ this.topicNsRoot = topicNsRoot;
+ }
+
+ public String getDmaapName() {
+ return dmaapName;
+ }
+
+ public void setDmaapName(String dmaapName) {
+ this.dmaapName = dmaapName;
+ }
+
+ public String getDrProvUrl() {
+ return drProvUrl;
+ }
+
+ public void setDrProvUrl(String drProvUrl) {
+ this.drProvUrl = drProvUrl;
+ }
+
+
+ public String getNodeKey() {
+ return nodeKey;
+ }
+
+ public void setNodeKey(String nodeKey) {
+ this.nodeKey = nodeKey;
+ }
+
+ public String getAccessKeyOwner() {
+ return accessKeyOwner;
+ }
+
+ public void setAccessKeyOwner(String accessKeyOwner) {
+ this.accessKeyOwner = accessKeyOwner;
+ }
+
+
+ public String getBridgeAdminTopic() {
+ return bridgeAdminTopic;
+ }
+
+ public void setBridgeAdminTopic(String bridgeAdminTopic) {
+ this.bridgeAdminTopic = bridgeAdminTopic;
+ }
+
+ public String getLoggingUrl() {
+ return loggingUrl;
+ }
+
+ public void setLoggingUrl(String loggingUrl) {
+ this.loggingUrl = loggingUrl;
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java b/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java new file mode 100644 index 0000000..39d4181 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/DmaapObject.java @@ -0,0 +1,68 @@ +/*-
+ * ============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.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement
+public abstract class DmaapObject {
+ protected Date lastMod;
+ protected DmaapObject_Status status;
+
+ public Date getLastMod() {
+ return lastMod;
+ }
+
+ public void setLastMod(Date lastMod) {
+ this.lastMod = lastMod;
+ }
+
+ public void setLastMod() {
+ this.lastMod = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
+ }
+
+ public enum DmaapObject_Status {
+ EMPTY,
+ NEW,
+ STAGED,
+ VALID,
+ INVALID,
+ DELETED
+ }
+ public DmaapObject_Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(DmaapObject_Status status) {
+ this.status = status;
+ }
+
+ public boolean isStatusValid() {
+ if ( this.status == DmaapObject_Status.VALID ) {
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Feed.java b/src/main/java/org/openecomp/dmaapbc/model/Feed.java new file mode 100644 index 0000000..c445b65 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/Feed.java @@ -0,0 +1,279 @@ +/*-
+ * ============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.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;
+
+ private String feedName;
+ private String feedVersion;
+ private String feedDescription;
+ private String owner;
+ private String asprClassification;
+ private String publishURL;
+ private String subscribeURL;
+ private boolean suspended;
+ private String logURL;
+ private String formatUuid;
+
+ private ArrayList<DR_Pub> pubs;
+ private ArrayList<DR_Sub> subs;
+
+
+
+ public boolean isSuspended() {
+ return suspended;
+ }
+
+ public void setSuspended(boolean suspended) {
+ this.suspended = suspended;
+ }
+
+ public String getSubscribeURL() {
+ return subscribeURL;
+ }
+
+ public void setSubscribeURL(String subscribeURL) {
+ this.subscribeURL = subscribeURL;
+ }
+
+
+
+ public Feed() {
+ this.pubs = new ArrayList<DR_Pub>();
+ this.subs = new ArrayList<DR_Sub>();
+ this.setStatus( DmaapObject_Status.EMPTY );
+
+ }
+
+ public Feed( String name,
+ String version,
+ String description,
+ String owner,
+ String aspr
+ ) {
+ this.feedName = name;
+ this.feedVersion = version;
+ this.feedDescription = description;
+ this.owner = owner;
+ this.asprClassification = aspr;
+ this.pubs = new ArrayList<DR_Pub>();
+ this.subs = new ArrayList<DR_Sub>();
+ this.setStatus( DmaapObject_Status.NEW );
+
+ }
+
+ // expects a String in JSON format, with known fields to populate Feed object
+ public Feed ( String json ) {
+ JSONParser parser = new JSONParser();
+ JSONObject jsonObj;
+
+ try {
+ jsonObj = (JSONObject) parser.parse( json );
+ } catch ( ParseException pe ) {
+ logger.error( "Error parsing provisioning data: " + json );
+ this.setStatus( DmaapObject_Status.INVALID );
+ return;
+ }
+ this.setFeedName( (String) jsonObj.get("name"));
+
+
+ this.setFeedVersion( (String) jsonObj.get("version"));
+ this.setFeedDescription( (String) jsonObj.get("description"));
+ this.setOwner( (String) jsonObj.get("publisher"));
+
+ this.setSuspended( (boolean) jsonObj.get("suspend"));
+ JSONObject links = (JSONObject) jsonObj.get("links");
+ String url = (String) links.get("publish");
+ this.setPublishURL( url );
+ this.setFeedId( url.substring( url.lastIndexOf('/')+1, url.length() ));
+ logger.info( "feedid="+ this.getFeedId() );
+ this.setSubscribeURL( (String) links.get("subscribe") );
+ this.setLogURL( (String) links.get("log") );
+ JSONObject auth = (JSONObject) jsonObj.get("authorization");
+ this.setAsprClassification( (String) auth.get("classification"));
+ JSONArray pubs = (JSONArray) auth.get( "endpoint_ids");
+ int i;
+ ArrayList<DR_Pub> dr_pub = new ArrayList<DR_Pub>();
+ this.subs = new ArrayList<DR_Sub>();
+
+ for( i = 0; i < pubs.size(); i++ ) {
+ JSONObject entry = (JSONObject) pubs.get(i);
+ dr_pub.add( new DR_Pub( "someLocation",
+ (String) entry.get("id"),
+ (String) entry.get("password"),
+ this.getFeedId(),
+ this.getFeedId() + "." + DR_Pub.nextKey() ));
+
+ }
+ this.setPubs( dr_pub );
+
+ this.setStatus( DmaapObject_Status.VALID );
+
+ }
+
+ public String getFeedId() {
+ return feedId;
+ }
+
+ public void setFeedId(String feedId) {
+ this.feedId = feedId;
+ }
+
+ public String getFeedName() {
+ return feedName;
+ }
+
+ public void setFeedName(String feedName) {
+ this.feedName = feedName;
+ }
+
+ public String getFeedVersion() {
+ return feedVersion;
+ }
+
+ public void setFeedVersion(String feedVersion) {
+ this.feedVersion = feedVersion;
+ }
+
+ public String getFeedDescription() {
+ return feedDescription;
+ }
+
+ public void setFeedDescription(String feedDescription) {
+ this.feedDescription = feedDescription;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public String getAsprClassification() {
+ return asprClassification;
+ }
+
+ public void setAsprClassification(String asprClassification) {
+ this.asprClassification = asprClassification;
+ }
+
+ public String getPublishURL() {
+ return publishURL;
+ }
+
+ public void setPublishURL(String publishURL) {
+ this.publishURL = publishURL;
+ }
+
+ public String getLogURL() {
+ return logURL;
+ }
+
+ public void setLogURL(String logURL) {
+ this.logURL = logURL;
+ }
+
+
+
+ public String getFormatUuid() {
+ return formatUuid;
+ }
+
+ public void setFormatUuid(String formatUuid) {
+ this.formatUuid = formatUuid;
+ }
+
+ // returns the Feed object in JSON that conforms to DR Prov Server expectations
+ public String toProvJSON() {
+
+ ArrayList<DR_Pub> pubs = this.getPubs();
+ String postJSON = String.format("{\"name\": \"%s\", \"version\": \"%s\", \"description\": \"%s\", \"suspend\": %s, \"authorization\": { \"classification\": \"%s\", ",
+ this.getFeedName(),
+ this.getFeedVersion(),
+ this.getFeedDescription(),
+ this.isSuspended() ,
+ this.getAsprClassification()
+ );
+ int i;
+ postJSON += "\"endpoint_addrs\": [],\"endpoint_ids\": [";
+ String comma = "";
+ for( i = 0 ; i < pubs.size(); i++) {
+ postJSON += String.format(" %s{\"id\": \"%s\",\"password\": \"%s\"}",
+ comma,
+ pubs.get(i).getUsername(),
+ pubs.get(i).getUserpwd()
+ ) ;
+ comma = ",";
+ }
+ postJSON += "]}}";
+
+ logger.info( "postJSON=" + postJSON);
+ return postJSON;
+ }
+
+ public ArrayList<DR_Pub> getPubs() {
+ return pubs;
+ }
+
+ public void setPubs( ArrayList<DR_Pub> pubs) {
+ this.pubs = pubs;
+ }
+
+ public ArrayList<DR_Sub> getSubs() {
+ return subs;
+ }
+
+ public void setSubs( ArrayList<DR_Sub> subs) {
+ this.subs = subs;
+ }
+
+ public byte[] getBytes() {
+ return toProvJSON().getBytes(StandardCharsets.UTF_8);
+ }
+
+ public static String getSubProvURL( String feedId ) {
+ String ret = new String();
+ ret = new DmaapService().getDmaap().getDrProvUrl() + "/subscribe/" + feedId ;
+ return ret;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java b/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java new file mode 100644 index 0000000..684424a --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/MR_Client.java @@ -0,0 +1,121 @@ +/*-
+ * ============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.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;
+ private String fqtn;
+ private String clientRole;
+ private String[] action;
+ private String mrClientId;
+
+
+ public MR_Client() {
+ this.mrClientId = DatabaseClass.getNextClientId();
+ this.lastMod = new Date();
+ this.setLastMod();
+ logger.debug( "MR_Client constructor " + this.lastMod );
+
+ }
+
+ public MR_Client( String dLN,
+ String f,
+ String cR,
+ String[] a ) {
+ this.dcaeLocationName = dLN;
+ this.fqtn = f;
+ this.clientRole = cR;
+ int i = 0;
+
+ if ( this.action == null ) {
+ this.action = new String[a.length];
+ }
+ for( String aa : a ) {
+ this.action[i++] = new String( aa );
+ }
+ this.setStatus( DmaapObject_Status.NEW );
+ this.mrClientId = DatabaseClass.getNextClientId();
+ this.setLastMod();
+ logger.debug( "MR_Client constructor w initialization " + this.lastMod );
+ }
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+ public String getFqtn() {
+ return fqtn;
+ }
+
+ public void setFqtn(String fqtn) {
+ this.fqtn = fqtn;
+ }
+
+ public String getClientRole() {
+ return clientRole;
+ }
+
+ public void setClientRole(String clientRole) {
+ this.clientRole = clientRole;
+ }
+
+ public String[] getAction() {
+ return action;
+ }
+
+ public void setAction(String[] action) {
+ this.action = action;
+ }
+
+ public String getMrClientId() {
+ return mrClientId;
+ }
+
+ public void setMrClientId(String mrClientId) {
+ this.mrClientId = mrClientId;
+ }
+
+
+
+ public String getTopicURL() {
+ return topicURL;
+ }
+
+ public void setTopicURL(String topicURL) {
+ this.topicURL = topicURL;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java b/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java new file mode 100644 index 0000000..fcaf007 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/MR_Cluster.java @@ -0,0 +1,124 @@ +/*-
+ * ============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.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;
+ //private DmaapTimestamp lastMod;
+ private String topicProtocol;
+ private String topicPort;
+
+
+ // TODO: make this a system property
+ private static String defaultTopicProtocol = "https";
+ private static String defaultTopicPort = "3905";
+
+
+
+
+ public MR_Cluster() {
+ this.topicProtocol = defaultTopicProtocol;
+ this.topicPort = defaultTopicPort;
+ this.lastMod = new Date();
+
+ logger.info( "MR_Cluster constructor " + this.lastMod );
+
+ }
+
+ public MR_Cluster( String dLN,
+ String f,
+ String a,
+ String[] h ) {
+ this.dcaeLocationName = dLN;
+ this.fqdn = f;
+ this.hosts[0] = h[0];
+ this.hosts[1] = h[1];
+ this.hosts[2] = h[2];
+ this.topicProtocol = defaultTopicProtocol;
+ this.topicPort = defaultTopicPort;
+
+ logger.info( "MR_Cluster constructor w initialization complete" + this.lastMod );
+ }
+
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+
+ public String getFqdn() {
+ return fqdn;
+ }
+
+ public void setFqdn(String fqdn) {
+ this.fqdn = fqdn;
+ }
+
+ public String[] getHosts() {
+ return hosts;
+ }
+
+ public void setHosts(String[] hosts) {
+ this.hosts = hosts;
+ }
+
+ public String getTopicProtocol() {
+ return topicProtocol;
+ }
+
+ public void setTopicProtocol(String topicProtocol) {
+ this.topicProtocol = topicProtocol;
+ }
+
+ public String getTopicPort() {
+ return topicPort;
+ }
+
+ public void setTopicPort(String topicPort) {
+ this.topicPort = topicPort;
+ }
+
+ public String genTopicURL( String topic ) {
+ StringBuilder str = new StringBuilder( topicProtocol );
+ str.append("://")
+ .append(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 new file mode 100644 index 0000000..828e9e0 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/MirrorMaker.java @@ -0,0 +1,202 @@ +/*-
+ * ============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.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+import org.openecomp.dmaapbc.service.MirrorMakerService;
+
+public class MirrorMaker extends DmaapObject {
+ static final Logger logger = Logger.getLogger(MirrorMaker.class);
+
+ private String sourceCluster;
+ private String targetCluster;
+ private String mmName;
+ private ArrayList<String> topics; //re-using this var name for backwards DB compatibility
+
+ private Set<ReplicationVector> vectors;
+
+
+ public MirrorMaker(){
+
+ }
+
+ public MirrorMaker(String source, String target) {
+ sourceCluster = source;
+ targetCluster = target;
+ mmName = genKey(source, target);
+ vectors = new HashSet<ReplicationVector>();
+ topics = new ArrayList<String>();
+
+ }
+
+ public String getMmName() {
+ return mmName;
+ }
+
+ public void setMmName(String mmName) {
+ this.mmName = mmName;
+ }
+
+
+ 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 );
+ }
+ vectors.add(new ReplicationVector( fqtn, source, target ));
+ }
+
+ public void delVector( String fqtn, String source, String target ) {
+ vectors.remove(new ReplicationVector( fqtn, source, target));
+ }
+
+
+
+ public String toJSON() {
+ StringBuilder str = new StringBuilder( "{ \"source\": " + sourceCluster + ",\"topics\": [" );
+ int numTargets = 0;
+ for (ReplicationVector rv: vectors) {
+ if ( numTargets > 0 ) {
+ str.append( ",");
+ }
+ str.append( " \"target\": " + rv.getTargetCluster() + ", \"topic\": " + rv.getFqtn());
+ numTargets++;
+ }
+ str.append( "] }" );
+
+ return str.toString();
+ }
+
+
+ // returns the JSON for MM message containing which Topics to replicate
+ /*
+ * example:
+ *
+ {
+ "messageID":"12349",
+ "updateWhiteList":
+ {
+ "name":"Global1ToGlobal3",
+ "whitelist":"org.openecomp.dcae.topic1,org.openecomp.dcae.topic2"
+ }
+ }
+ */
+ public String updateWhiteList() {
+ StringBuilder str = new StringBuilder( "{ \"messageID\": \"" + MirrorMakerService.genTransactionId() + "\", \"updateWhiteList\": {" );
+ str.append( " \"name\": \"" + this.getMmName() + "\", \"whitelist\": \"" );
+ int numTargets = 0;
+
+ //for (ReplicationVector rv: vectors) {
+ for (String rv: topics) {
+ if ( numTargets > 0 ) {
+ str.append( ",");
+ }
+ //str.append( rv.getFqtn() );
+ str.append( rv );
+ numTargets++;
+ }
+ str.append( "\" } }" );
+
+ return str.toString();
+ }
+
+ // returns the JSON for MM message indicating that a MM agent is needed between two clusters
+ // example:
+ /*
+ *
+ {
+ "messageID":"12345"
+ "createMirrorMaker":
+ {
+ "name":"Global1ToGlobal2",
+ "consumer":"192.168.0.1:2181",
+ "producer":"192.168.0.2:9092"
+ }
+ }
+ */
+ public String createMirrorMaker() {
+ StringBuilder str = new StringBuilder( "{ \"messageID\": \"" + MirrorMakerService.genTransactionId() + "\", \"createMirrorMaker\": {" );
+ str.append( " \"name\": \"" + this.getMmName() + "\", " );
+ str.append( " \"consumer\": \"" + this.sourceCluster + ":2181\", " );
+ str.append( " \"producer\": \"" + this.targetCluster + ":9092\" ");
+
+ str.append( " } }" );
+
+ return str.toString();
+ }
+
+
+ public String getSourceCluster() {
+ return sourceCluster;
+ }
+
+ public void setSourceCluster(String sourceCluster) {
+ this.sourceCluster = sourceCluster;
+ }
+
+ public String getTargetCluster() {
+ return targetCluster;
+ }
+
+ public void setTargetCluster(String targetCluster) {
+ this.targetCluster = targetCluster;
+ }
+
+
+ public Set<ReplicationVector> getVectors() {
+ return vectors;
+ }
+
+ public void setVectors(Set<ReplicationVector> vectors) {
+ this.vectors = vectors;
+ }
+ public ArrayList<String> getTopics() {
+ return topics;
+ }
+
+ //public void setVectors(Set<ReplicationVector> vectors) {
+ public void setTopics(ArrayList<String> topics) {
+ this.topics = topics;
+ }
+
+
+ public static String genKey( String s, String t) {
+ StringBuilder str = new StringBuilder();
+ str.append(s);
+ str.append("-To-");
+ str.append(t);
+ return str.toString();
+ }
+
+
+
+ public void addTopic( String topic ) {
+ topics.add(topic);
+ }
+
+ public int getTopicCount() {
+ return topics.size();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java b/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java new file mode 100644 index 0000000..60f25e5 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/ReplicationVector.java @@ -0,0 +1,104 @@ +/*-
+ * ============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 org.apache.log4j.Logger;
+
+public class ReplicationVector {
+
+
+
+ static final Logger logger = Logger.getLogger(ReplicationVector.class);
+ public enum ReplicationVector_Status {
+ EMPTY,
+ NEW,
+ STAGED,
+ VALID,
+ INVALID,
+ INVALID_DUP,
+ DELETED
+ }
+
+ String fqtn;
+ String sourceCluster;
+ String targetCluster;
+ ReplicationVector_Status status;
+
+ public ReplicationVector(){
+
+ }
+
+ public ReplicationVector(String fqtn, String sourceCluster,
+ String targetCluster) {
+ super();
+ this.fqtn = fqtn;
+ this.sourceCluster = sourceCluster;
+ this.targetCluster = targetCluster;
+ }
+
+ public String getFqtn() {
+ return fqtn;
+ }
+
+ public void setFqtn(String fqtn) {
+ this.fqtn = fqtn;
+ }
+
+ public String getSourceCluster() {
+ return sourceCluster;
+ }
+
+ public void setSourceCluster(String sourceCluster) {
+ this.sourceCluster = sourceCluster;
+ }
+
+ public String getTargetCluster() {
+ return targetCluster;
+ }
+
+ public void setTargetCluster(String targetCluster) {
+ this.targetCluster = targetCluster;
+ }
+
+ public int hashCode() {
+ StringBuilder tmp = new StringBuilder( this.fqtn );
+ tmp.append(this.sourceCluster);
+ tmp.append(this.targetCluster);
+
+ return tmp.toString().hashCode();
+ }
+ private static boolean xeq(String s1, String s2) {
+ if (s1 == null) {
+ return(s2 == null);
+ } else {
+ return(s1.equals(s2));
+ }
+ }
+ public boolean equals(Object o) {
+ if (o == this) {
+ return(true);
+ }
+ if (!(o instanceof ReplicationVector)) {
+ return(false);
+ }
+ ReplicationVector x = (ReplicationVector)o;
+ return(xeq(fqtn, x.fqtn) && xeq(sourceCluster, x.sourceCluster) && xeq(targetCluster, x.targetCluster));
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/model/Topic.java b/src/main/java/org/openecomp/dmaapbc/model/Topic.java new file mode 100644 index 0000000..3d9ea6f --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/model/Topic.java @@ -0,0 +1,165 @@ +/*-
+ * ============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.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+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 ArrayList<MR_Client> clients;
+
+
+
+ private static Dmaap dmaap = new DmaapService().getDmaap();
+
+ //
+ // utility function to generate the FQTN of a topic
+ public static String genFqtn( String name ) {
+ String ret = dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + name;
+ return ret;
+ }
+
+
+
+ public Topic() {
+ super();
+ this.clients = new ArrayList<MR_Client>();
+ this.lastMod = new Date();
+ this.setLastMod();
+ logger.info( "Topic constructor " + this.lastMod );
+ }
+ public Topic(String fqtn, String topicName, String topicDescription,
+ String tnxEnabled, String owner) {
+ super();
+ this.fqtn = fqtn;
+ this.topicName = topicName;
+ this.topicDescription = topicDescription;
+ //this.dcaeLocationName = dcaeLocationName;
+ this.tnxEnabled = tnxEnabled;
+ this.owner = owner;
+ this.setLastMod();
+ this.setStatus( DmaapObject_Status.NEW );
+ logger.info( "Topic constructor " + this.getLastMod() );
+ }
+ public String getFqtn() {
+ return fqtn;
+ }
+ public void setFqtn(String fqtn) {
+ this.fqtn = fqtn;
+ }
+ public String getTopicName() {
+ return topicName;
+ }
+ public void setTopicName(String topicName) {
+ this.topicName = topicName;
+ }
+ public String getTopicDescription() {
+ return topicDescription;
+ }
+ public void setTopicDescription(String topicDescription) {
+ this.topicDescription = topicDescription;
+ }
+ /*
+ public String getDcaeLocationName() {
+ return dcaeLocationName;
+ }
+ public void setDcaeLocationName(String dcaeLocationName) {
+ this.dcaeLocationName = dcaeLocationName;
+ }
+ */
+ public String getTnxEnabled() {
+ return tnxEnabled;
+ }
+ public void setTnxEnabled(String tnxEnabled) {
+ this.tnxEnabled = tnxEnabled;
+ }
+ public String getOwner() {
+ return owner;
+ }
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+
+ public void setClients(ArrayList<MR_Client> clients) {
+ this.clients = clients;
+ }
+
+ public ArrayList<MR_Client> getClients() {
+ return clients;
+ }
+
+ public int getNumClients() {
+ if ( this.clients == null ) {
+ return 0;
+ }
+ return this.clients.size();
+ }
+
+
+
+
+ public String getFormatUuid() {
+ return formatUuid;
+ }
+
+
+
+ public void setFormatUuid(String formatUuid) {
+ this.formatUuid = formatUuid;
+ }
+
+
+
+ public String toProvJSON() {
+ StringBuilder str = new StringBuilder();
+ str.append("{ \"topicName\": \"");
+ str.append( this.getFqtn() );
+ str.append( "\", \"topicDescription\": \"");
+ str.append( this.getTopicDescription());
+ str.append( "\", \"partitionCount\": \"2\", \"replicationCount\": \"1\" } ");
+ logger.info( str.toString() );
+ return str.toString();
+ }
+
+ public byte[] getBytes() {
+ return toProvJSON().getBytes(StandardCharsets.UTF_8);
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java b/src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java new file mode 100644 index 0000000..a2a9e71 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/ApiResource.java @@ -0,0 +1,45 @@ +/*-
+ * ============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.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();
+ }
+
+
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java b/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java new file mode 100644 index 0000000..0c5782a --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/BridgeResource.java @@ -0,0 +1,111 @@ +/*-
+ * ============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.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+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.model.BrTopic;
+import org.openecomp.dmaapbc.model.MirrorMaker;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.MirrorMakerService;
+
+@Path("/bridge")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class BridgeResource {
+
+ static final Logger logger = Logger.getLogger(BridgeResource.class);
+
+ private MirrorMakerService mmService = new MirrorMakerService();
+
+ @GET
+ public Response getBridgedTopics(@QueryParam("source") String source,
+ @QueryParam("target") String target,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ 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
+ brTopic.setBrSource(source);
+ brTopic.setBrTarget(target);
+ MirrorMaker mm = mmService.getMirrorMaker(source, target);
+ if ( mm != null ) {
+ brTopic.setTopicCount( mm.getTopicCount() );
+ }
+
+ logger.info( "topicCount [2 locations]: " + brTopic.getTopicCount() );
+ }
+ else if (source == null && target == null ) {
+ List<String> mmList = mmService.getAllMirrorMakers();
+ brTopic.setBrSource("all");
+ brTopic.setBrTarget("all");
+ int totCnt = 0;
+ for( String key: mmList ) {
+ int mCnt = 0;
+ MirrorMaker mm = mmService.getMirrorMaker(key);
+ if ( mm != null ) {
+ mCnt = mm.getTopicCount();
+ }
+ logger.info( "Count for "+ key + ": " + mCnt);
+ totCnt += mCnt;
+ }
+
+ 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();
+ }
+ return Response.ok(brTopic).
+ build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java new file mode 100644 index 0000000..73506f6 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_NodeResource.java @@ -0,0 +1,183 @@ +/*-
+ * ============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.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.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.model.DR_Node;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.DR_NodeService;
+
+@Path("/dr_nodes")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class DR_NodeResource extends ApiResource {
+ static final Logger logger = Logger.getLogger(DR_NodeResource.class);
+ DR_NodeService dr_nodeService = new DR_NodeService();
+
+ @GET
+ public List<DR_Node> getDr_Nodes(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @POST
+ public Response addDr_Node( DR_Node node,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ DR_Node nNode = dr_nodeService.addDr_Node(node, resp.getErr());
+ if ( resp.getErr().is2xx()) {
+ return Response.status(Status.OK.getStatusCode())
+ .entity(nNode)
+ .build();
+ }
+ return Response.status( resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @PUT
+ @Path("/{fqdn}")
+ public Response updateDr_Node( @PathParam("fqdn") String name, DR_Node node,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ 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 Response.status( resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @DELETE
+ @Path("/{fqdn}")
+ public Response deleteDr_Node( @PathParam("fqdn") String name,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+
+ 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();
+ }
+ dr_nodeService.removeDr_Node(name, resp.getErr());
+ if ( resp.getErr().is2xx() ) {
+ return Response.status(Status.NO_CONTENT.getStatusCode())
+ .build();
+ }
+ return Response.status( resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @GET
+ @Path("/{fqdn}")
+ public Response get( @PathParam("fqdn") String name,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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 Response.status( resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java new file mode 100644 index 0000000..108a18b --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_PubResource.java @@ -0,0 +1,270 @@ +/*-
+ * ============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.util.ArrayList;
+import java.util.Iterator;
+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.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.model.ApiError;
+import org.openecomp.dmaapbc.model.DR_Pub;
+import org.openecomp.dmaapbc.model.Feed;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.DR_PubService;
+import org.openecomp.dmaapbc.service.FeedService;
+
+
+@Path("/dr_pubs")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class DR_PubResource extends ApiResource {
+ static final Logger logger = Logger.getLogger(DR_PubResource.class);
+ DR_PubService dr_pubService = new DR_PubService();
+
+ @GET
+ public List<DR_Pub> getDr_Pubs(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @POST
+ public Response addDr_Pub( DR_Pub pub,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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);
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( err.toString() );
+ return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ }
+
+ 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();
+ }
+
+ 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();
+ if ( pub.getUsername() == null ) {
+ pub.setRandomUserName();
+ }
+ if ( pub.getUserpwd() == null ) {
+ pub.setRandomPassword();
+ }
+ pubs.add( pub );
+ fnew.setPubs(pubs);
+ fnew = feeds.updateFeed( fnew, err );
+
+ if ( ! err.is2xx()) {
+ return Response.status(err.getCode())
+ .entity( err )
+ .build();
+ }
+ 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();
+ }
+
+ @PUT
+ @Path("/{pubId}")
+ public Response updateDr_Pub( @PathParam("pubId") String name, DR_Pub pub,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @DELETE
+ @Path("/{pubId}")
+ public Response deleteDr_Pub( @PathParam("pubId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ logger.info( "Entry: DELETE /dr_pubs");
+ 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);
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( err.toString() );
+ return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ }
+
+ DR_Pub pub = dr_pubService.getDr_Pub( id, err );
+ if ( ! err.is2xx()) {
+ return Response.status(err.getCode())
+ .entity( err )
+ .build();
+ }
+ 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();
+ }
+ 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();
+ }
+ Iterator<DR_Pub> i = pubs.iterator();
+ while( 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();
+ }
+
+ dr_pubService.removeDr_Pub(id, err);
+ if ( ! err.is2xx()) {
+ return Response.status(err.getCode())
+ .entity( err )
+ .build();
+ }
+ return Response.status(Status.NO_CONTENT.getStatusCode())
+ .build();
+ }
+
+ @GET
+ @Path("/{pubId}")
+ public Response get( @PathParam("pubId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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);
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( err.toString() );
+ return Response.status(Status.BAD_REQUEST).entity( err ).build();
+ }
+ 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();
+ }
+ return Response.status(Status.OK.getStatusCode())
+ .entity(pub)
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java new file mode 100644 index 0000000..e0b42ce --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/DR_SubResource.java @@ -0,0 +1,253 @@ +/*-
+ * ============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.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.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.model.DR_Sub;
+import org.openecomp.dmaapbc.model.Feed;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.DR_SubService;
+import org.openecomp.dmaapbc.service.FeedService;
+
+
+@Path("/dr_subs")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class DR_SubResource extends ApiResource {
+ static final Logger logger = Logger.getLogger(DR_SubResource.class);
+
+
+ @GET
+ public List<DR_Sub> getDr_Subs(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.info( "Entry: GET /dr_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();
+ }
+
+ @POST
+ public Response addDr_Sub( DR_Sub sub,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.info( "Entry: POST /dr_subs");
+ 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(), "");
+ resp.required( "dcaeLocationName", sub.getDcaeLocationName(), "");
+
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( resp.toString() );
+ return Response.status(Status.BAD_REQUEST)
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ 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();
+ }
+
+ DR_SubService dr_subService = new DR_SubService( fnew.getSubscribeURL());
+ ArrayList<DR_Sub> subs = fnew.getSubs();
+ 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();
+ }
+ subs.add( snew );
+ logger.info( "num existing subs after = " + subs.size() );
+
+ fnew.setSubs(subs);
+ logger.info( "update feed");
+ //feeds.updateFeed( fnew, err );
+
+ return Response.status(Status.CREATED)
+ .entity(snew)
+ .build();
+
+ }
+
+ @PUT
+ @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");
+ 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, "");
+ resp.required( "feedId", sub.getFeedId(), "");
+ resp.required( "dcaeLocationName", sub.getDcaeLocationName(), "");
+
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( resp.toString() );
+ return Response.status(Status.BAD_REQUEST)
+ .entity( resp.getErr() )
+ .build();
+ }
+ 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 Response.status(resp.getErr().getCode())
+ .entity(resp.getErr())
+ .build();
+ }
+
+ @DELETE
+ @Path("/{subId}")
+ public Response deleteDr_Sub( @PathParam("subId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ logger.info( "Entry: DELETE /dr_subs");
+ 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();
+ }
+ 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 Response.status(Status.NO_CONTENT.getStatusCode())
+ .build();
+ }
+
+ @GET
+ @Path("/{subId}")
+ public Response get( @PathParam("subId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.info( "Entry: GET /dr_subs");
+ 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();
+ }
+ 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 Response.status(resp.getErr().getCode())
+ .entity(resp.getErr())
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java new file mode 100644 index 0000000..9d158fa --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/DcaeLocationResource.java @@ -0,0 +1,185 @@ +/*-
+ * ============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.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.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.model.ApiError;
+import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.DcaeLocationService;
+
+
+@Path("/dcaeLocations")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class DcaeLocationResource {
+ static final Logger logger = Logger.getLogger(DcaeLocationResource.class);
+ DcaeLocationService locationService = new DcaeLocationService();
+
+ @GET
+ public List<DcaeLocation> getDcaeLocations( @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @POST
+ public Response addDcaeLocation( DcaeLocation location,
+ @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();
+ }
+ if ( locationService.getDcaeLocation(location.getDcaeLocationName()) != null ) {
+ ApiError err = new ApiError();
+
+ err.setCode(Status.CONFLICT.getStatusCode());
+ err.setMessage("dcaeLocation already exists");
+ err.setFields("dcaeLocation");
+
+ logger.warn( err );
+ return Response.status(Status.CONFLICT).entity( err ).build();
+
+
+ }
+ DcaeLocation loc = locationService.addDcaeLocation(location);
+ return Response.status(Status.CREATED)
+ .entity(loc)
+ .build();
+ }
+
+ @PUT
+ @Path("/{locationName}")
+ public Response updateDcaeLocation( @PathParam("locationName") String name, DcaeLocation location,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setMessage("dcaeLocation does not exist");
+ err.setFields("dcaeLocation");
+
+ logger.warn( err );
+ return Response.status(Status.NOT_FOUND).entity( err ).build();
+
+
+ }
+ DcaeLocation loc = locationService.updateDcaeLocation(location);
+ return Response.status(Status.CREATED)
+ .entity(loc)
+ .build();
+ }
+
+ @DELETE
+ @Path("/{locationName}")
+ public Response deleteDcaeLocation( @PathParam("locationName") String name,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ 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();
+ }
+
+ @GET
+ @Path("/{locationName}")
+ public Response getDcaeLocation( @PathParam("locationName") String name,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setMessage("dcaeLocation does not exist");
+ err.setFields("dcaeLocation");
+
+ logger.warn( err );
+ return Response.status(Status.NOT_FOUND).entity( err ).build();
+
+
+ }
+
+ return Response.status(Status.OK)
+ .entity(loc)
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java b/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java new file mode 100644 index 0000000..03c731f --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/DmaapResource.java @@ -0,0 +1,140 @@ +/*-
+ * ============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=========================================================
+ */
+
+//
+// $Id$
+
+package org.openecomp.dmaapbc.resources;
+
+
+
+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;
+import javax.ws.rs.Produces;
+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.model.Dmaap;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.DmaapService;
+
+
+
+@Path("/dmaap")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class DmaapResource {
+ static final Logger logger = Logger.getLogger(DmaapResource.class);
+
+ DmaapService dmaapService = new DmaapService();
+
+ @GET
+ public Response getDmaap(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ logger.debug( "Entry: GET " + uriInfo.getPath() );
+ 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();
+ }
+
+ @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();
+ }
+ 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();
+ }
+
+ Dmaap d = dmaapService.addDmaap(obj);
+ if ( d == null ) {
+ return Response.status(Status.NOT_FOUND)
+ .build();
+
+ }
+
+ return Response.ok(d)
+ .build();
+ }
+
+ @PUT
+ public Response updateDmaap( Dmaap obj, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ 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();
+ }
+ Dmaap d = dmaapService.updateDmaap(obj);
+ if ( d != null ) {
+ return Response.ok(d)
+ .build();
+ } else {
+ return Response.status(Status.NOT_FOUND)
+ .build();
+ }
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java b/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java new file mode 100644 index 0000000..b1dcd57 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/FeedResource.java @@ -0,0 +1,227 @@ +/*-
+ * ============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.util.List;
+
+import javax.jws.WebParam;
+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.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.log4j.Logger;
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+import org.openecomp.dmaapbc.authentication.AuthenticationErrorException;
+import org.openecomp.dmaapbc.model.Feed;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.FeedService;
+
+
+@Path("/feeds")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class FeedResource extends ApiResource {
+ static final Logger logger = Logger.getLogger(FeedResource.class);
+
+
+ @GET
+ public List<Feed> getFeeds(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.debug( "Entry: GET " + uriInfo.getPath() );
+ 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;
+ }
+
+
+
+ @POST
+ public Response addFeed( @WebParam(name = "feed") Feed feed , @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ logger.debug( "Entry: POST " + uriInfo.getPath());
+
+ 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(), "");
+ resp.required( "owner", feed.getOwner(), "" );
+ resp.required( "asprClassification", feed.getAsprClassification(), "" );
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( resp.toString() );
+ return Response.status(Status.BAD_REQUEST).entity( resp ).build();
+ }
+
+ FeedService feedService = new FeedService();
+ Feed nfeed = feedService.addFeed( feed, resp.getErr() );
+ if ( nfeed != null ) {
+ return Response.status(Status.OK)
+ .entity(nfeed)
+ .build();
+ } else {
+ logger.error( "Unable to create: " + feed.getFeedName() + ":" + feed.getFeedVersion());
+
+ return Response.status(resp.getErr().getCode())
+ .entity( resp )
+ .build();
+ }
+ }
+
+ @PUT
+ @Path("/{id}")
+ public Response updateFeed( @PathParam("id") String id, Feed feed, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.debug( "Entry: PUT " + uriInfo.getPath());
+
+ 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();
+ }
+
+ Feed nfeed = feedService.getFeed( id, resp.getErr() );
+ if ( nfeed == null ) {
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ // we assume there is no updates allowed for pubs and subs objects via this api...
+ // need to update any fields supported by PUT but preserve original field values.
+ nfeed.setSuspended(feed.isSuspended());
+ nfeed.setFeedDescription(feed.getFeedDescription());
+ nfeed.setFormatUuid(feed.getFormatUuid());
+
+ nfeed = feedService.updateFeed(nfeed, resp.getErr());
+ if ( nfeed != null ) {
+ return Response.status(Status.OK)
+ .entity(nfeed)
+ .build();
+ } else {
+ logger.info( "Unable to update: " + feed.getFeedName() + ":" + feed.getFeedVersion());
+
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+ }
+
+ @DELETE
+ @Path("/{id}")
+ public Response deleteFeed( @PathParam("id") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ){
+ 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());
+ FeedService feedService = new FeedService();
+ feedService.removeFeed(id);
+ return Response.status(Status.NO_CONTENT)
+ .build();
+ }
+
+ @GET
+ @Path("/{id}")
+ public Response getFeed( @PathParam("id") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ logger.debug( "Entry: GET " + uriInfo.getPath());
+ 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();
+ }
+ return Response.status(Status.OK)
+ .entity(nfeed)
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java new file mode 100644 index 0000000..7acc0a4 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClientResource.java @@ -0,0 +1,267 @@ +/*-
+ * ============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.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.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.model.ApiError;
+import org.openecomp.dmaapbc.model.MR_Client;
+import org.openecomp.dmaapbc.model.MR_Cluster;
+import org.openecomp.dmaapbc.model.Topic;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.MR_ClientService;
+import org.openecomp.dmaapbc.service.MR_ClusterService;
+import org.openecomp.dmaapbc.service.TopicService;
+
+
+@Path("/mr_clients")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class MR_ClientResource extends ApiResource {
+ static final Logger logger = Logger.getLogger(MR_ClientResource.class);
+ private MR_ClientService mr_clientService = new MR_ClientService();
+
+ @GET
+ public List<MR_Client> getMr_Clients(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @POST
+ public Response addMr_Client( MR_Client client,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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(), "");
+ resp.required( "clientRole", client.getClientRole(), "" );
+ resp.required( "action", client.getAction(), "");
+
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( resp.toString() );
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+ 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();
+ }
+ 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();
+ }
+ TopicService topics = new TopicService();
+ ApiError err = resp.getErr();
+ Topic t = topics.getTopic(client.getFqtn(), err);
+ if ( t == null ) {
+ return Response.status(err.getCode()).entity( err ).build();
+ }
+ 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();
+ }
+ else {
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+ }
+
+ @PUT
+ @Path("/{clientId}")
+ public Response updateMr_Client( @PathParam("clientId") String clientId, MR_Client client,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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(), "");
+ resp.required( "clientRole", client.getClientRole(), "" );
+ resp.required( "action", client.getAction(), "");
+
+ } catch ( RequiredFieldException rfe ) {
+ logger.debug( resp.toString() );
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+ client.setMrClientId(clientId);
+ MR_Client nClient = mr_clientService.updateMr_Client(client, resp.getErr() );
+ if ( resp.getErr().is2xx()) {
+ return Response.ok(nClient)
+ .build();
+ }
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @DELETE
+ @Path("/{subId}")
+ public Response deleteMr_Client( @PathParam("subId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ 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();
+ }
+ MR_Client client = mr_clientService.removeMr_Client(id, 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 Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @GET
+ @Path("/{subId}")
+ public Response test( @PathParam("subId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ MR_Client nClient = mr_clientService.getMr_Client( id, resp.getErr() );
+ if ( resp.getErr().is2xx()) {
+ return Response.ok(nClient)
+ .build();
+ }
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java new file mode 100644 index 0000000..a7b8f37 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/MR_ClusterResource.java @@ -0,0 +1,195 @@ +/*-
+ * ============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.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.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.model.MR_Cluster;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.MR_ClusterService;
+
+
+@Path("/mr_clusters")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class MR_ClusterResource {
+ static final Logger logger = Logger.getLogger(MR_ClusterResource.class);
+
+ MR_ClusterService mr_clusterService = new MR_ClusterService();
+
+ @GET
+ public List<MR_Cluster> getMr_Clusters(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+
+ @POST
+ public Response addMr_Cluster( MR_Cluster cluster,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.info("Entry: /POST" );
+ 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();
+ }
+ MR_Cluster mrc = mr_clusterService.addMr_Cluster(cluster, resp.getErr() );
+ if ( mrc != null && mrc.isStatusValid() ) {
+ return Response.status(Status.CREATED)
+ .entity(mrc)
+ .build();
+ }
+ return Response.status(resp.getErr().getCode())
+ .entity(resp.getErr())
+ .build();
+
+ }
+
+ @PUT
+ @Path("/{clusterId}")
+ public Response updateMr_Cluster( @PathParam("clusterId") String clusterId, MR_Cluster cluster,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ 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 Response.status(resp.getErr().getCode())
+ .entity(resp.getErr())
+ .build();
+ }
+
+ @DELETE
+ @Path("/{clusterId}")
+ public Response deleteMr_Cluster( @PathParam("clusterId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth){
+ 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();
+ }
+ mr_clusterService.removeMr_Cluster(id, resp.getErr() );
+ if ( resp.getErr().is2xx()) {
+ return Response.status(Status.NO_CONTENT.getStatusCode())
+ .build();
+ }
+ return Response.status(resp.getErr().getCode())
+ .entity( resp.getErr() )
+ .build();
+ }
+
+ @GET
+ @Path("/{clusterId}")
+ public Response getMR_Cluster( @PathParam("clusterId") String id,
+ @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ MR_Cluster mrc = mr_clusterService.getMr_Cluster( id, resp.getErr() );
+ if ( mrc != null && mrc.isStatusValid() ) {
+ return Response.status(Status.CREATED)
+ .entity(mrc)
+ .build();
+ }
+ return Response.status(resp.getErr().getCode())
+ .entity(resp.getErr())
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/RequiredFieldException.java b/src/main/java/org/openecomp/dmaapbc/resources/RequiredFieldException.java new file mode 100644 index 0000000..081e086 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/RequiredFieldException.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.resources;
+
+public class RequiredFieldException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java b/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java new file mode 100644 index 0000000..5d4b9a7 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/resources/TopicResource.java @@ -0,0 +1,184 @@ +/*-
+ * ============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.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.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.model.ApiError;
+import org.openecomp.dmaapbc.model.Topic;
+import org.openecomp.dmaapbc.service.ApiService;
+import org.openecomp.dmaapbc.service.TopicService;
+
+@Path("/topics")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class TopicResource {
+
+ static final Logger logger = Logger.getLogger(TopicResource.class);
+
+ TopicService mr_topicService = new TopicService();
+
+ @GET
+ public List<Topic> getTopics(@Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ logger.info("Entry: /GET" );
+ 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();
+ }
+
+ @POST
+ public Response addTopic( Topic topic, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ) {
+ logger.info("Entry: /POST" );
+ 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();
+ }
+ //String fqtn = Topic.genFqtn(topic.getTopicName());
+ ApiError err = check.getErr();
+
+ topic.setLastMod();
+
+ Topic mrc = mr_topicService.addTopic(topic, err);
+ if ( mrc != null && mrc.isStatusValid() ) {
+ return Response.status(Status.CREATED)
+ .entity(mrc)
+ .build();
+ }
+ return Response.status(err.getCode())
+ .entity(err)
+ .build();
+
+ }
+
+ @PUT
+ @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");
+
+ return Response.status(err.getCode())
+ .entity( err )
+ .build();
+ //return mr_topicService.updateTopic(topic);
+ }
+
+ @DELETE
+ @Path("/{topicId}")
+ public Response deleteTopic( @PathParam("topicId") String id, @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth ){
+ logger.info("Entry: /DELETE " + 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();
+ }
+
+ Topic topic = mr_topicService.removeTopic(id, check.getErr());
+ if ( check.getErr().is2xx()) {
+ return Response.status(Status.NO_CONTENT.getStatusCode())
+ .build();
+ }
+ return Response.status(check.getErr().getCode())
+ .entity( check.getErr() )
+ .build();
+ }
+
+
+ @GET
+ @Path("/{topicId}")
+ public Response getTopic( @PathParam("topicId") String id , @Context UriInfo uriInfo, @HeaderParam("Authorization") String basicAuth) {
+ 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();
+ }
+ Topic mrc = mr_topicService.getTopic( id, check.getErr() );
+ if ( mrc == null ) {
+ return Response.status(check.getErr().getCode())
+ .entity(check.getErr())
+ .build();
+ }
+ return Response.ok(mrc)
+ .build();
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java b/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java new file mode 100644 index 0000000..cef19a8 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/server/JettyServer.java @@ -0,0 +1,144 @@ +/*-
+ * ============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 java.util.Properties;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.log4j.Logger;
+import org.eclipse.jetty.security.SecurityHandler;
+import org.eclipse.jetty.server.Connector;
+import org.eclipse.jetty.server.HttpConfiguration;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.SecureRequestCustomizer;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.server.SslConnectionFactory;
+import org.eclipse.jetty.servlet.DefaultServlet;
+import org.eclipse.jetty.servlet.ServletContextHandler;
+import org.eclipse.jetty.servlet.ServletHolder;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * 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 JettyServer( Properties params ) throws Exception {
+
+ Server server = new Server();
+ 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 );
+
+ // HTTP Server
+
+ HttpConfiguration http_config = new HttpConfiguration();
+ http_config.setSecureScheme("https");
+ http_config.setSecurePort(sslPort);
+ http_config.setOutputBufferSize(32768);
+
+
+
+ ServerConnector httpConnector = new ServerConnector(server, new HttpConnectionFactory(http_config));
+ httpConnector.setPort(httpPort);
+ httpConnector.setIdleTimeout(30000);
+
+
+ // HTTPS Server
+
+ HttpConfiguration https_config = new HttpConfiguration(http_config);
+ https_config.addCustomizer(new SecureRequestCustomizer());
+ SslContextFactory sslContextFactory = new SslContextFactory();
+ String keystore = params.getProperty("KeyStoreFile", "etc/keystore");
+ logger.info( "https Server using keystore at " + keystore );
+ String keystorePwd = params.getProperty( "KeyStorePassword", "changeit");
+ String keyPwd = params.getProperty("KeyPassword", "changeit");
+
+
+ sslContextFactory.setKeyStorePath(keystore);
+ sslContextFactory.setKeyStorePassword(keystorePwd);
+ sslContextFactory.setKeyManagerPassword(keyPwd);
+
+
+ ServerConnector sslConnector = null;
+ if ( sslPort != 0 ) {
+ sslConnector = new ServerConnector(server,
+ new SslConnectionFactory(sslContextFactory, "http/1.1"),
+ new HttpConnectionFactory(https_config));
+ sslConnector.setPort(sslPort);
+ if ( allowHttp ) {
+ logger.info("Starting httpConnector on port " + httpPort );
+ logger.info("Starting sslConnector on port " + sslPort + " for https");
+ server.setConnectors( new Connector[] { httpConnector, sslConnector });
+ } else {
+ logger.info("NOT starting httpConnector because HttpAllowed param is " + allowHttp );
+ logger.info("Starting sslConnector on port " + sslPort + " for https");
+ server.setConnectors( new Connector[] { sslConnector });
+ }
+ }
+ else {
+ logger.info("NOT starting sslConnector on port " + sslPort + " for https");
+ if ( allowHttp ) {
+ logger.info("Starting httpConnector on port " + httpPort );
+ server.setConnectors( new Connector[] { httpConnector });
+ }
+ }
+
+ // Set context for servlet. This is shared for http and https
+ ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
+ context.setContextPath("/");
+ server.setHandler( context );
+
+ 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" );
+
+ // also serve up some static pages...
+ ServletHolder staticServlet = context.addServlet(DefaultServlet.class,"/*");
+ staticServlet.setInitParameter("resourceBase","www");
+ staticServlet.setInitParameter("pathInfoOnly","true");
+
+ try {
+
+ logger.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 );
+ //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 new file mode 100644 index 0000000..2143670 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/server/Main.java @@ -0,0 +1,70 @@ +/*-
+ * ============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 java.io.FileInputStream;
+import java.util.Properties;
+
+import org.apache.log4j.Logger;
+import org.apache.log4j.PropertyConfigurator;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+public class Main {
+
+ private Properties parameters;
+ private static String provFQDN;
+
+ public static String getProvFQDN() {
+ return provFQDN;
+ }
+ public void setProvFQDN(String provFQDN) {
+ Main.provFQDN = provFQDN;
+ }
+ private Main() {
+ }
+ public static void main(String[] args) throws Exception {
+ (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.");
+ parameters = DmaapConfig.getConfig();
+ setProvFQDN( parameters.getProperty("ProvFQDN", "ProvFQDN.notset.com"));
+
+
+ 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);
+ 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 new file mode 100644 index 0000000..8690bb0 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/ApiService.java @@ -0,0 +1,176 @@ +/*-
+ * ============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.service;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+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.AuthenticationErrorException;
+import org.openecomp.dmaapbc.authentication.DecisionPolicy;
+import org.openecomp.dmaapbc.model.ApiError;
+import org.openecomp.dmaapbc.model.Dmaap;
+import org.openecomp.dmaapbc.resources.RequiredFieldException;
+import org.openecomp.dmaapbc.util.DmaapConfig;
+
+public class ApiService {
+ static final Logger logger = Logger.getLogger(ApiService.class);
+ static private String apiNamespace;
+ static private boolean usePE;
+
+ private ApiError err;
+
+ public ApiService() {
+ err = new ApiError();
+
+ if (apiNamespace == null) {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ usePE = "true".equalsIgnoreCase(p.getProperty("UsePE", "false"));
+ apiNamespace = p.getProperty("ApiNamespace", "org.openecomp.dmaapBC.api");
+ }
+
+ }
+
+
+ public ApiError getErr() {
+ return err;
+ }
+
+
+ public void setErr(ApiError err) {
+ this.err = err;
+ }
+
+
+ // test for presence of a required field
+ public void required( String name, Object val, String expr ) throws RequiredFieldException {
+ if ( val == null ) {
+ err.setCode(Status.BAD_REQUEST.getStatusCode());
+ err.setMessage("missing required field");
+ err.setFields( name );
+ throw new RequiredFieldException();
+ }
+ if ( expr != null && ! expr.isEmpty() ) {
+ Pattern pattern = Pattern.compile(expr);
+ Matcher matcher = pattern.matcher((CharSequence) val);
+ if ( ! matcher.find() ) {
+ err.setCode(Status.BAD_REQUEST.getStatusCode());
+ err.setMessage( "value '" + val + "' violates regexp check '" + expr + "'");
+ err.setFields( name );
+ throw new RequiredFieldException();
+ }
+ }
+ }
+
+ // utility to serialize ApiErr object
+ public String toString() {
+ return String.format( "code=%d msg=%s fields=%s", err.getCode(), err.getMessage(), err.getFields() );
+ }
+
+
+ public void setCode(int statusCode) {
+ err.setCode(statusCode);
+ }
+
+
+ public void setMessage(String string) {
+ err.setMessage(string);
+ }
+
+
+ public void setFields(String string) {
+ err.setFields(string);
+ }
+
+ private Response buildResponse() {
+ return Response.status( err.getCode())
+ .entity(getErr())
+ .build();
+ }
+ public Response response(int statusCode) {
+ err.setCode(statusCode);
+ return buildResponse();
+ }
+ 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();
+ }
+ public Response unavailable() {
+ err.setCode(Status.SERVICE_UNAVAILABLE.getStatusCode());
+ err.setMessage( "Request is unavailable due to unexpected condition");
+ return buildResponse();
+ }
+
+ 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()) {
+ String errmsg = "No URI value provided ";
+ logger.info( errmsg );
+ throw new AuthenticationErrorException( );
+ }
+ if ( method == null || method.isEmpty()) {
+ String errmsg = "No method value provided ";
+ logger.info( errmsg );
+ throw new AuthenticationErrorException( );
+ }
+ DmaapService dmaapService = new DmaapService();
+ Dmaap dmaap = dmaapService.getDmaap();
+ String env = dmaap.getDmaapName();
+
+ // special case during bootstrap of app when DMaaP environment may not be set.
+ // this allows us to authorize certain APIs used for initialization during this window.
+ if ( env.isEmpty() ) {
+ env = "boot";
+ }
+
+ 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...
+ try {
+ DecisionPolicy d = new DecisionPolicy();
+ DmaapPerm p = new DmaapPerm( apiNamespace + "." + uriPath, env, method );
+ d.check( ID, Password, p);
+ } catch ( AuthenticationErrorException ae ) {
+ logger.info( "User " + ID + " failed authentication/authorization");
+ throw ae;
+
+ }
+*/
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java b/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java new file mode 100644 index 0000000..c1e36aa --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/DR_NodeService.java @@ -0,0 +1,118 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.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);
+ private Map<String, DR_Node> dr_nodes = DatabaseClass.getDr_nodes();
+
+ public Map<String, DR_Node> getDr_Nodes() {
+ return dr_nodes;
+ }
+
+ public List<DR_Node> getAllDr_Nodes() {
+ return new ArrayList<DR_Node>(dr_nodes.values());
+ }
+
+ public DR_Node getDr_Node( String fqdn, ApiError apiError ) {
+ DR_Node old = dr_nodes.get( fqdn );
+ if ( old == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "fqdn");
+ apiError.setMessage( "Node " + fqdn + " does not exist");
+ return null;
+ }
+ apiError.setCode(200);
+ return old;
+ }
+
+ public DR_Node addDr_Node( DR_Node node, ApiError apiError ) {
+ String fqdn = node.getFqdn();
+ DR_Node old = dr_nodes.get( fqdn );
+ if ( old != null ) {
+ apiError.setCode(Status.CONFLICT.getStatusCode());
+ apiError.setFields( "fqdn");
+ apiError.setMessage( "Node " + fqdn + " already exists");
+ return null;
+ }
+ node.setLastMod();
+ node.setStatus(DmaapObject_Status.VALID);
+ dr_nodes.put( node.getFqdn(), node );
+ apiError.setCode(200);
+ return node;
+ }
+
+ public DR_Node updateDr_Node( DR_Node node, ApiError apiError ) {
+ DR_Node old = dr_nodes.get( node );
+ if ( old == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "fqdn");
+ apiError.setMessage( "Node " + node + " does not exist");
+ return null;
+ }
+ node.setLastMod();
+ dr_nodes.put( node.getFqdn(), node );
+ apiError.setCode(200);
+ return node;
+ }
+
+ public DR_Node removeDr_Node( String nodeName, ApiError apiError ) {
+ DR_Node old = dr_nodes.get( nodeName );
+ if ( old == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "fqdn");
+ apiError.setMessage( "Node " + nodeName + " does not exist");
+ return null;
+ }
+ apiError.setCode(200);
+ return dr_nodes.remove(nodeName);
+ }
+
+ public String getNodePatternAtLocation( String loc ) {
+ logger.info( "loc=" + loc );
+ if ( loc == null ) {
+ return null;
+ }
+ StringBuilder str = new StringBuilder();
+ for( DR_Node node : dr_nodes.values() ) {
+ if ( loc.equals( node.getDcaeLocationName()) ) {
+ if ( str.length() > 0 ) {
+ str.append( ",");
+ }
+ str.append( node.getFqdn());
+ }
+ }
+ logger.info( "returning " + str.toString() );
+ return 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 new file mode 100644 index 0000000..8479e55 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/DR_PubService.java @@ -0,0 +1,144 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.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);
+ private Map<String, DR_Pub> dr_pubs = DatabaseClass.getDr_pubs();
+ private DR_NodeService nodeService = new DR_NodeService();
+ private static DrProvConnection prov;
+
+ public DR_PubService() {
+ super();
+ prov = new DrProvConnection();
+ }
+
+ public Map<String, DR_Pub> getDr_Pubs() {
+ return dr_pubs;
+ }
+
+ public List<DR_Pub> getAllDr_Pubs() {
+ return new ArrayList<DR_Pub>(dr_pubs.values());
+ }
+
+ public ArrayList<DR_Pub> getDr_PubsByFeedId( String feedId ) {
+ ArrayList<DR_Pub> somePubs = new ArrayList<DR_Pub>();
+ for( DR_Pub pub : dr_pubs.values() ) {
+ if ( feedId.equals( pub.getFeedId() )) {
+ somePubs.add( pub );
+ }
+ }
+
+ return somePubs;
+ }
+
+ public DR_Pub getDr_Pub( String key, ApiError err ) {
+ DR_Pub pub = dr_pubs.get( key );
+ if ( pub == null ) {
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setFields( "pubId");
+ err.setMessage("DR_Pub with pubId = " + key + " not found");
+ } else {
+ err.setCode(Status.OK.getStatusCode());
+ }
+ return pub;
+ }
+
+ private void addIngressRoute( DR_Pub pub, ApiError err ) {
+
+ String nodePattern = nodeService.getNodePatternAtLocation( pub.getDcaeLocationName());
+ 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);
+ logger.info( "rc=" + rc + " error code=" + err.getCode() );
+
+ if ( rc != 200 ) {
+ switch( rc ) {
+ case 403:
+ logger.error( "Not authorized for DR ingress API");
+ err.setCode(500);
+ err.setMessage("API deployment/configuration error - contact support");
+ err.setFields( "PROV_AUTH_ADDRESSES");
+ break;
+
+ default:
+ logger.warn( "unable to create ingress rule for " + pub.getPubId() + " on feed " + pub.getFeedId() + " to " + nodePattern);
+ }
+ }
+
+ }
+ }
+
+ public DR_Pub addDr_Pub( DR_Pub pub ) {
+ ApiError err = new ApiError();
+ if ( pub.getPubId() != null && ! pub.getPubId().isEmpty() ) {
+ addIngressRoute( pub, err);
+ if ( err.getCode() > 0 ) {
+ pub.setStatus(DmaapObject_Status.INVALID);
+ }
+ pub.setLastMod();
+ dr_pubs.put( pub.getPubId(), pub );
+ return pub;
+ }
+ else {
+ return null;
+ }
+ }
+
+ public DR_Pub updateDr_Pub( DR_Pub pub ) {
+ if ( pub.getPubId().isEmpty()) {
+ return null;
+ }
+ pub.setLastMod();
+ dr_pubs.put( pub.getPubId(), pub );
+ return pub;
+ }
+
+ public DR_Pub removeDr_Pub( String pubId, ApiError err ) {
+
+ DR_Pub pub = dr_pubs.get( pubId );
+ if ( pub == null ) {
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setFields( "pubId");
+ err.setMessage( "pubId " + pubId + " not found");
+ } else {
+ dr_pubs.remove(pubId);
+ err.setCode(Status.OK.getStatusCode());
+ }
+ return pub;
+
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java b/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java new file mode 100644 index 0000000..a360cff --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/DR_SubService.java @@ -0,0 +1,141 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.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);
+ private Map<String, DR_Sub> dr_subs = DatabaseClass.getDr_subs();
+ private String provURL;
+ //private DrProvConnection prov;
+
+ public DR_SubService( ) {
+ logger.info( "Entry: DR_SubService (with no args)" );
+// prov = new DrProvConnection();
+
+ }
+ public DR_SubService( String subURL ) {
+ logger.info( "Entry: DR_SubService " + subURL );
+ provURL = subURL;
+// prov = new DrProvConnection();
+// prov.makeSubConnection( subURL );
+ }
+ public Map<String, DR_Sub> getDR_Subs() {
+ logger.info( "enter getDR_Subs()");
+ return dr_subs;
+ }
+
+ public List<DR_Sub> getAllDr_Subs() {
+ logger.info( "enter getAllDR_Subs()");
+ return new ArrayList<DR_Sub>(dr_subs.values());
+ }
+
+ public ArrayList<DR_Sub> getDr_SubsByFeedId( String pubId ) {
+ ArrayList<DR_Sub> someSubs = new ArrayList<DR_Sub>();
+ for( DR_Sub sub : dr_subs.values() ) {
+ if ( pubId.equals( sub.getFeedId() )) {
+ someSubs.add( sub );
+ }
+ }
+
+ return someSubs;
+ }
+ public DR_Sub getDr_Sub( String key, ApiError apiError ) {
+ logger.info( "enter getDR_Sub()");
+ DR_Sub sub = dr_subs.get( key );
+ if ( sub == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "subId");
+ apiError.setMessage("subId " + key + " not found");
+ } else {
+ apiError.setCode(200);
+ }
+ return sub;
+ }
+
+ 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 );
+
+ DR_Sub snew = null;
+
+ if ( resp != null ) {
+ snew = new DR_Sub( resp );
+ snew.setDcaeLocationName(sub.getDcaeLocationName());
+ snew.setLastMod();
+ dr_subs.put( snew.getSubId(), snew );
+ apiError.setCode(200);
+ } else {
+ apiError.setCode(400);
+ }
+
+ return snew;
+ }
+
+
+ public DR_Sub updateDr_Sub( DR_Sub obj, ApiError apiError ) {
+ logger.info( "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;
+ }
+
+ public void removeDr_Sub( String key, ApiError apiError ) {
+ logger.info( "enter removeDR_Subs()");
+ DR_Sub sub = dr_subs.get( key );
+ if ( sub == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "subId");
+ apiError.setMessage("subId " + key + " not found");
+ } else {
+ dr_subs.remove(key);
+ apiError.setCode(200);
+ }
+
+ return;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java b/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java new file mode 100644 index 0000000..f88852a --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/DcaeLocationService.java @@ -0,0 +1,86 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+
+
+
+
+
+
+
+import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.model.DmaapObject.DmaapObject_Status;
+
+public class DcaeLocationService {
+
+ private Map<String, DcaeLocation> dcaeLocations = DatabaseClass.getDcaeLocations();
+
+ public Map<String, DcaeLocation> getDcaeLocations() {
+ return dcaeLocations;
+ }
+
+ public List<DcaeLocation> getAllDcaeLocations() {
+ return new ArrayList<DcaeLocation>(dcaeLocations.values());
+ }
+
+ public DcaeLocation getDcaeLocation( String name ) {
+ return dcaeLocations.get(name);
+ }
+
+ public DcaeLocation addDcaeLocation( DcaeLocation location ) {
+ location.setLastMod();
+ location.setStatus(DmaapObject_Status.VALID);
+ dcaeLocations.put( location.getDcaeLocationName(), location );
+ return location;
+ }
+
+ public DcaeLocation updateDcaeLocation( DcaeLocation location ) {
+ if ( location.getDcaeLocationName().isEmpty()) {
+ return null;
+ }
+ location.setLastMod();
+ dcaeLocations.put( location.getDcaeLocationName(), location );
+ return location;
+ }
+
+ public DcaeLocation removeDcaeLocation( String locationName ) {
+ return dcaeLocations.remove(locationName);
+ }
+
+ public String getCentralLocation() {
+ for( Map.Entry<String, DcaeLocation> entry: dcaeLocations.entrySet() ) {
+ DcaeLocation loc = entry.getValue();
+ if ( loc.isCentral() ) {
+ // use the name of the first central location we hit
+ return loc.getDcaeLocationName();
+ }
+
+ }
+ return "aCentralLocation"; // default value that is obvious to see is wrong
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java b/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java new file mode 100644 index 0000000..47cc271 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/DmaapService.java @@ -0,0 +1,233 @@ +/*-
+ * ============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.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.database.DatabaseClass;
+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;
+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);
+
+ private Singleton<Dmaap> dmaapholder = DatabaseClass.getDmaap();
+
+ // TODO put these in properties file
+ String topicFactory = "org.openecomp.dcae.dmaap.topicFactory";
+ String topicMgrRole = "org.openecomp.dmaapBC.TopicMgr";
+
+ // TODO confirm this is equivalent to dmaap.getTopicNsRoot() so we can retire it
+ String dcaeTopicNs = "org.openecomp.dcae.dmaap";
+
+
+ public DmaapService() {
+
+ }
+
+ public Dmaap getDmaap() {
+ logger.info( "entering getDmaap()" );
+ return(dmaapholder.get());
+ }
+
+ public Dmaap addDmaap( Dmaap nd ) {
+
+ logger.info( "entering addDmaap()" );
+ Dmaap dmaap = dmaapholder.get();
+ if ( dmaap.getVersion().equals( "0")) {
+
+ nd.setLastMod();
+ dmaapholder.update(nd);
+
+ AafService aaf = new AafService( ServiceType.AAF_Admin);
+
+ boolean anythingWrong = setTopicMgtPerms( nd, aaf ) || createMmaTopic();
+
+ if ( anythingWrong ) {
+ dmaap.setStatus(DmaapObject_Status.INVALID);
+ }
+ else {
+ dmaap.setStatus(DmaapObject_Status.VALID);
+ }
+
+
+ return dmaap;
+
+ }
+ else {
+ return dmaap;
+ }
+ }
+
+ public Dmaap updateDmaap( Dmaap nd ) {
+ 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:
+ // - if the DMaaP Name changes
+ // - if the version is 0 (this is a handy test to force this processing by updating the DB)
+ // - if the object is invalid, reprocessing might fix it.
+ 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.
+ anythingWrong = setTopicMgtPerms( nd, aaf ) || createMmaTopic();
+ }
+
+ if ( anythingWrong ) {
+ nd.setStatus(DmaapObject_Status.INVALID);
+ }
+ else {
+ nd.setStatus(DmaapObject_Status.VALID);
+ }
+ nd.setLastMod();
+ dmaapholder.update(nd); // may need to update status...
+ return(dmaapholder.get());
+
+ }
+
+ public String getTopicPerm(){
+ Dmaap dmaap = dmaapholder.get();
+ return getTopicPerm( dmaap.getDmaapName() );
+ }
+ public String getTopicPerm( String val ) {
+ Dmaap dmaap = dmaapholder.get();
+ return dmaap.getTopicNsRoot() + "." + val + ".mr.topic";
+ }
+
+ public String getBridgeAdminFqtn(){
+ Dmaap dmaap = dmaapholder.get();
+ return(dmaap.getTopicNsRoot() + "." + dmaap.getDmaapName() + "." + dmaap.getBridgeAdminTopic());
+ }
+
+ private boolean setTopicMgtPerms( Dmaap nd, AafService aaf ){
+ String[] actions = { "create", "destroy" };
+ String instance = ":" + dcaeTopicNs + "." + nd.getDmaapName() + ".mr.topic:" + dcaeTopicNs + "." + nd.getDmaapName();
+
+ for( String action : actions ) {
+
+ DmaapPerm perm = new DmaapPerm( topicFactory, instance, action );
+
+ int rc = aaf.addPerm( perm );
+ if ( rc != 201 && rc != 409 ) {
+ logger.error( "unable to add perm for "+ topicFactory + "|" + 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 );
+ return true;
+ }
+ }
+
+ String t = dcaeTopicNs +"." + nd.getDmaapName() + ".mr.topic";
+ String[] s = { "view", "pub", "sub" };
+ actions = s;
+ instance = "*";
+
+ for( String action : actions ) {
+
+ DmaapPerm perm = new DmaapPerm( t, instance, action );
+
+ int rc = aaf.addPerm( perm );
+ if ( rc != 201 && rc != 409 ) {
+ logger.error( "unable to add perm for "+ 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 );
+ return true;
+ }
+
+ }
+ return false;
+ }
+
+ // create the special topic for MMA provisioning.
+ // return true indicating a problem in topic creation,
+ // else false means it was ok (created or previously existed)
+ private boolean createMmaTopic() {
+ boolean rc = true;
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ Dmaap dmaap = dmaapholder.get();
+
+ ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
+ String[] actions = { "pub", "sub", "view" };
+ String centralMR = new DcaeLocationService().getCentralLocation();
+ if ( centralMR == null ) {
+ return rc;
+ }
+ logger.info( "Location for " + dmaap.getBridgeAdminTopic() + " is " + centralMR );
+
+ // first client is the Role used by Bus Controller to send messages to MMA
+ String provRole = p.getProperty("MM.ProvRole");
+ MR_Client nClient = new MR_Client();
+ nClient.setAction(actions);
+ nClient.setClientRole(provRole);
+ nClient.setDcaeLocationName(centralMR);
+ clients.add( nClient );
+
+ // second client is the Role used by MMA to listen to messages from Bus Controller
+ String agentRole = p.getProperty("MM.AgentRole");
+ nClient = new MR_Client();
+ nClient.setAction(actions);
+ nClient.setClientRole(agentRole);
+ nClient.setDcaeLocationName(centralMR);
+ clients.add( nClient );
+
+ // initialize Topic
+ Topic mmaTopic = new Topic();
+ mmaTopic.setTopicName(dmaap.getBridgeAdminTopic());
+ mmaTopic.setClients(clients);
+ mmaTopic.setOwner("BusController");
+ mmaTopic.setTopicDescription("topic reserved for MirrorMaker Administration");
+ mmaTopic.setTnxEnabled("false");
+
+ ApiError err = new ApiError();
+ TopicService svc = new TopicService();
+ Topic nTopic = svc.addTopic(mmaTopic, err);
+ if ( err.is2xx() || err.getCode() == 409 ) {
+ return false;
+ }
+ logger.error( "Unable to create topic for " + dmaap.getBridgeAdminTopic() + " err=" + err.getFields() + " fields=" + err.getFields() + " msg=" + 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 new file mode 100644 index 0000000..a9af116 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/FeedService.java @@ -0,0 +1,314 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.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);
+ private Map<String, Feed> feeds = DatabaseClass.getFeeds();
+ private DR_PubService pubService = new DR_PubService();
+ private DR_SubService subService = new DR_SubService();
+ private DcaeLocationService dcaeLocations = new DcaeLocationService();
+ public FeedService() {
+ logger.info( "new FeedService");
+
+ }
+
+ public Map<String, Feed> getFeeds() {
+ return feeds;
+ }
+
+ private void getSubObjects( Feed f ) {
+ ArrayList<DR_Pub> pubs = pubService.getDr_PubsByFeedId( f.getFeedId() );
+ f.setPubs(pubs);
+ ArrayList<DR_Sub> subs = subService.getDr_SubsByFeedId( f.getFeedId() );
+ f.setSubs(subs);
+ }
+
+ public List<Feed> getAllFeeds() {
+ ArrayList<Feed> fatFeeds = new ArrayList<Feed>();
+ for( Feed f: feeds.values() ) {
+ getSubObjects(f);
+ fatFeeds.add(f);
+ }
+ return fatFeeds;
+ }
+
+ public Feed getFeed( String key, ApiError err ) {
+ Feed f = feeds.get( key );
+ if ( f != null ) {
+ getSubObjects( f );
+ } else {
+ err.setCode(Status.NOT_FOUND.getStatusCode());
+ err.setMessage("feed not found");
+ err.setFields("feedId=" + key );
+ }
+ err.setCode(200);
+ return f;
+ }
+ //TODO: clean this up after testing proves it is no longer needed
+ /*
+ private void saveChildren( Feed fnew, Feed req ) {
+ // save any pubs
+ DR_PubService pubSvc = new DR_PubService();
+ ArrayList<DR_Pub> reqPubs = req.getPubs();
+ ArrayList<DR_Pub> newPubs = fnew.getPubs();
+ logger.info( "reqPubs size=" + reqPubs.size() + " newPubs size=" + newPubs.size() );
+
+ // NOTE: when i > 1 newPubs are in reverse order from reqPubs
+ int nSize = newPubs.size();
+ int rSize = reqPubs.size();
+ if ( nSize != rSize ) {
+ logger.error( "Resulting set of publishers do not match requested set of publishers " + nSize + " vs " + rSize );
+ fnew.setStatus( DmaapObject_Status.INVALID);
+ return;
+ }
+ for( int i = 0; i < reqPubs.size(); i++ ) {
+ DR_Pub reqPub = reqPubs.get(i);
+ DR_Pub newPub = newPubs.get(nSize - i - 1);
+
+
+ // make sure to re-use original pubId if it exists
+ String origPubId = reqPub.getPubId();
+ if ( origPubId != null && ! origPubId.isEmpty()) {
+ newPub.setPubId( origPubId );
+ }
+ newPub.setDcaeLocationName(reqPub.getDcaeLocationName());
+
+
+ newPubs.set( nSize - i - 1 , pubSvc.addDr_Pub( newPub ));
+ }
+
+ // save any subs
+ ArrayList<DR_Sub> subs = req.getSubs();
+ if ( subs.size() == 0 ) {
+ logger.info( "No subs specified");
+ } else {
+ DR_SubService subSvc = new DR_SubService( fnew.getSubscribeURL() );
+ ApiError err = new ApiError();
+ for( int i = 0; i < subs.size(); i++ ) {
+ subs.set( i, subSvc.addDr_Sub(subs.get(i), err));
+ }
+ fnew.setSubs(subs);
+ }
+
+
+ fnew.setStatus(DmaapObject_Status.VALID);
+
+ }
+ */
+
+ private boolean savePubs( Feed f ) {
+ return savePubs( f, f );
+ }
+ // need to save the Pub objects independently and copy pubId from original request
+ private boolean savePubs( Feed fnew, Feed req ) {
+ // save any pubs
+ DR_PubService pubSvc = new DR_PubService();
+ ArrayList<DR_Pub> reqPubs = req.getPubs();
+ ArrayList<DR_Pub> newPubs = fnew.getPubs();
+
+
+
+ int nSize = newPubs.size();
+ 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 );
+ fnew.setStatus( DmaapObject_Status.INVALID);
+ return false;
+ }
+ // NOTE: when i > 1 newPubs are in reverse order from reqPubs
+ for( int i = 0; i < reqPubs.size(); i++ ) {
+ DR_Pub reqPub = reqPubs.get(i);
+ ApiError err = new ApiError();
+ if ( pubSvc.getDr_Pub( reqPub.getPubId(), err ) == null ) {
+ DR_Pub newPub = newPubs.get(nSize - i - 1);
+ reqPub.setPubId(newPub.getPubId());
+ reqPub.setFeedId(newPub.getFeedId());
+ reqPub.setStatus(DmaapObject_Status.VALID);
+ if ( reqPub.getDcaeLocationName() == null ) {
+ reqPub.setDcaeLocationName("dcaeLocationNotSpecified");
+ }
+ pubSvc.addDr_Pub( reqPub );
+ }
+
+ }
+
+ fnew.setPubs(reqPubs);
+ fnew.setStatus(DmaapObject_Status.VALID);
+ return true;
+
+ }
+
+ private boolean saveSubs( Feed f ) {
+ return saveSubs( f, f );
+ }
+ // need to save the Sub objects independently
+ private boolean saveSubs( Feed fnew, Feed req ) {
+ ArrayList<DR_Sub> subs = req.getSubs();
+ if ( subs.size() == 0 ) {
+ logger.info( "No subs specified");
+ } else {
+ DR_SubService subSvc = new DR_SubService( fnew.getSubscribeURL() );
+ ApiError err = new ApiError();
+ for( int i = 0; i < subs.size(); i++ ) {
+ DR_Sub sub = subs.get(i);
+ if ( subSvc.getDr_Sub( sub.getSubId(), err) == null ) {
+ subs.set( i, subSvc.addDr_Sub(sub, err));
+ if ( ! err.is2xx()) {
+ logger.error( "i=" + i + " url=" + sub.getDeliveryURL() + " err=" + err.getCode() );
+ return false;
+ }
+ }
+
+ }
+ fnew.setSubs(subs);
+ }
+
+
+ fnew.setStatus(DmaapObject_Status.VALID);
+ return true;
+
+ }
+
+ public Feed addFeed( Feed req, ApiError err ) {
+
+ // at least 1 pub is required by DR, so create a default pub if none is specified
+ if ( req.getPubs().size() == 0 ) {
+ logger.info( "No pubs specified - creating tmp pub");
+ ArrayList<DR_Pub> pubs = new ArrayList<DR_Pub>();
+ pubs.add( new DR_Pub( dcaeLocations.getCentralLocation())
+ .setRandomUserName()
+ .setRandomPassword());
+ req.setPubs(pubs);
+ }
+
+ DrProvConnection prov = new DrProvConnection();
+ prov.makeFeedConnection();
+ String resp = prov.doPostFeed( req, err );
+ logger.info( "resp=" + resp );
+ if ( resp == null ) {
+ switch( err.getCode() ) {
+ case 400:
+ err.setFields( "feedName=" + req.getFeedName() + " + feedVersion=" + req.getFeedVersion() );
+ break;
+ case 403:
+ err.setCode(500);
+ err.setMessage("API deployment/configuration error - contact support");
+ err.setFields( "PROV_AUTH_ADDRESSES");
+ logger.error( "Prov response: 403. " + err.getMessage() + " regarding " + err.getFields() );
+ break;
+ default:
+ err.setCode(500);
+ err.setMessage( "Unexpected response from DR backend" );
+ err.setFields("response");
+ }
+ return null;
+ }
+
+
+ Feed fnew = new Feed( resp );
+ logger.info( "fnew status is:" + fnew.getStatus() );
+ if ( ! fnew.isStatusValid()) {
+ err.setCode(500);
+ err.setMessage( "Unexpected response from DR backend" );
+ err.setFields("response");
+ return null;
+ }
+
+ //saveChildren( fnew, req );
+ if ( ! savePubs( fnew, req ) || ! saveSubs( fnew, req ) ) {
+ err.setCode(Status.BAD_REQUEST.getStatusCode());
+ err.setMessage("Unable to save Pub or Sub objects");
+ return null;
+ }
+ fnew.setFormatUuid(req.getFormatUuid());
+ fnew.setLastMod();
+ feeds.put( fnew.getFeedId(), fnew );
+ return fnew;
+ }
+
+ public Feed updateFeed( Feed req, ApiError err ) {
+
+
+ DrProvConnection prov = new DrProvConnection();
+ prov.makeFeedConnection( req.getFeedId() );
+ String resp = prov.doPutFeed( req, err );
+ logger.info( "resp=" + resp );
+ if ( resp == null ) {
+ switch( err.getCode() ) {
+ case 400:
+ err.setFields( "feedName=" + req.getFeedName() + " + feedVersion=" + req.getFeedVersion() );
+ break;
+ case 403:
+ err.setCode(500);
+ err.setMessage("API deployment/configuration error - contact support");
+ err.setFields( "PROV_AUTH_ADDRESSES");
+ break;
+ default:
+ err.setCode(500);
+ err.setMessage( "Unexpected response from DR backend" );
+ err.setFields("response");
+ }
+ return null;
+ }
+
+
+ Feed fnew = new Feed( resp );
+ logger.info( "fnew status is:" + fnew.getStatus() );
+ if ( ! fnew.isStatusValid()) {
+ err.setCode(500);
+ err.setMessage( "Unexpected response from DR backend" );
+ err.setFields("response");
+ return null;
+ }
+
+ if ( ! savePubs( fnew, req ) || ! saveSubs( fnew, req ) ) {
+ err.setCode(Status.BAD_REQUEST.getStatusCode());
+ err.setMessage("Unable to save Pub or Sub objects");
+ return null;
+ }
+ fnew.setFormatUuid(req.getFormatUuid());
+ fnew.setLastMod();
+ feeds.put( fnew.getFeedId(), fnew );
+ return fnew;
+ }
+
+ public Feed removeFeed( String pubId ) {
+ return feeds.remove(pubId);
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java b/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java new file mode 100644 index 0000000..ac4b5c8 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/MR_ClientService.java @@ -0,0 +1,181 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.model.ApiError;
+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;
+
+public class MR_ClientService {
+ static final Logger logger = Logger.getLogger(MR_ClientService.class);
+
+ 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 DmaapService dmaap = new DmaapService();
+
+ public Map<String, MR_Client> getMR_Clients() {
+ return mr_clients;
+ }
+
+ public List<MR_Client> getAllMr_Clients() {
+ return new ArrayList<MR_Client>(mr_clients.values());
+ }
+
+ public ArrayList<MR_Client> getAllMrClients(String fqtn) {
+ ArrayList<MR_Client> results = new ArrayList<MR_Client>();
+ for (Map.Entry<String, MR_Client> entry : mr_clients.entrySet())
+ {
+ MR_Client client = entry.getValue();
+ if ( fqtn.equals(client.getFqtn() ) ) {
+ results.add( client );
+ }
+ }
+ return results;
+ }
+
+
+ public MR_Client getMr_Client( String key, ApiError apiError ) {
+ MR_Client c = mr_clients.get( key );
+ if ( c == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "mrClientId");
+ apiError.setMessage("mrClientId " + key + " not found" );
+ } else {
+ apiError.setCode(200);
+ }
+ return c;
+ }
+
+ 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" );
+ return null;
+ }
+ 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());
+ 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 {
+ logger.info( "Client references a dcaeLocation that doesn't exist:" + client.getDcaeLocationName());
+ client.setStatus( DmaapObject_Status.STAGED);
+ //return null;
+ }
+
+ 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;
+ }
+
+ public MR_Client updateMr_Client( MR_Client client, ApiError apiError ) {
+ MR_Client c = mr_clients.get( client.getMrClientId());
+ if ( c == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "mrClientId");
+ apiError.setMessage("mrClientId " + client.getMrClientId() + " not found" );
+ } else {
+ apiError.setCode(200);
+ }
+ mr_clients.put( client.getMrClientId(), client );
+ return client;
+ }
+
+ public MR_Client removeMr_Client( String key, ApiError apiError ) {
+ MR_Client c = mr_clients.get( key );
+ if ( c == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "mrClientId");
+ apiError.setMessage("mrClientId " + key + " not found" );
+ } else {
+ apiError.setCode(200);
+ }
+
+ return mr_clients.remove(key);
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java b/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java new file mode 100644 index 0000000..d5cb402 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/MR_ClusterService.java @@ -0,0 +1,133 @@ +/*-
+ * ============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.service;
+
+import java.util.ArrayList;
+import java.util.List;
+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.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);
+
+ private Map<String, MR_Cluster> mr_clusters = DatabaseClass.getMr_clusters();
+
+ public Map<String, MR_Cluster> getMR_Clusters() {
+ return mr_clusters;
+ }
+
+ public List<MR_Cluster> getAllMr_Clusters() {
+ return new ArrayList<MR_Cluster>(mr_clusters.values());
+ }
+
+ public MR_Cluster getMr_Cluster( String key, ApiError apiError ) {
+ MR_Cluster mrc = mr_clusters.get( key );
+ if ( mrc == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "dcaeLocationName");
+ apiError.setMessage( "Cluster with dcaeLocationName " + key + " not found");
+ }
+ apiError.setCode(200);
+ return mrc;
+ }
+ public MR_Cluster getMr_ClusterByFQDN( String key ) {
+ for( MR_Cluster cluster: mr_clusters.values() ) {
+ if ( key.equals( cluster.getFqdn() ) ) {
+ return cluster;
+ }
+ }
+ return null;
+ }
+
+ public MR_Cluster addMr_Cluster( MR_Cluster cluster, ApiError apiError ) {
+ logger.info( "Entry: addMr_Cluster");
+ MR_Cluster mrc = mr_clusters.get( cluster.getDcaeLocationName() );
+ if ( mrc != null ) {
+ apiError.setCode(Status.CONFLICT.getStatusCode());
+ apiError.setFields( "dcaeLocationName");
+ apiError.setMessage( "Cluster with dcaeLocationName " + cluster.getDcaeLocationName() + " already exists");
+ return null;
+ }
+ cluster.setLastMod();
+ cluster.setStatus(DmaapObject_Status.VALID);
+ mr_clusters.put( cluster.getDcaeLocationName(), cluster );
+ DcaeLocationService svc = new DcaeLocationService();
+ DcaeLocation loc = svc.getDcaeLocation( cluster.getDcaeLocationName() );
+ if ( loc != null && loc.isCentral() ) {
+ ApiError resp = TopicService.setBridgeClientPerms( cluster );
+ if ( ! resp.is2xx() ) {
+ logger.error( "Unable to provision Bridge to " + cluster.getDcaeLocationName() );
+ cluster.setLastMod();
+ cluster.setStatus(DmaapObject_Status.INVALID);
+ mr_clusters.put( cluster.getDcaeLocationName(), cluster );
+ }
+ }
+ apiError.setCode(200);
+ return cluster;
+ }
+
+ public MR_Cluster updateMr_Cluster( MR_Cluster cluster, ApiError apiError ) {
+ MR_Cluster mrc = mr_clusters.get( cluster.getDcaeLocationName() );
+ if ( mrc == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "dcaeLocationName");
+ apiError.setMessage( "Cluster with dcaeLocationName " + cluster.getDcaeLocationName() + " not found");
+ return null;
+ }
+ cluster.setLastMod();
+ mr_clusters.put( cluster.getDcaeLocationName(), cluster );
+ DcaeLocationService svc = new DcaeLocationService();
+ DcaeLocation loc = svc.getDcaeLocation( cluster.getDcaeLocationName() );
+ if ( loc.isCentral() ) {
+ ApiError resp = TopicService.setBridgeClientPerms( cluster );
+ if ( ! resp.is2xx() ) {
+ logger.error( "Unable to provision Bridge to " + cluster.getDcaeLocationName() );
+ cluster.setLastMod();
+ cluster.setStatus(DmaapObject_Status.INVALID);
+ mr_clusters.put( cluster.getDcaeLocationName(), cluster );
+ }
+ }
+ apiError.setCode(200);
+ return cluster;
+ }
+
+ public MR_Cluster removeMr_Cluster( String key, ApiError apiError ) {
+ MR_Cluster mrc = mr_clusters.get( key );
+ if ( mrc == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "dcaeLocationName");
+ apiError.setMessage( "Cluster with dcaeLocationName " + key + " not found");
+ return null;
+ }
+ apiError.setCode(200);
+ return mr_clusters.remove(key);
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java b/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java new file mode 100644 index 0000000..5d633b0 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/MirrorMakerService.java @@ -0,0 +1,137 @@ +/*-
+ * ============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.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.client.MrTopicConnection;
+import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.model.ApiError;
+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);
+
+ private Map<String, MirrorMaker> mirrors = DatabaseClass.getMirrorMakers();
+ private static MrTopicConnection prov;
+
+ public MirrorMakerService() {
+ super();
+ // TODO Auto-generated constructor stub
+ }
+
+ // will create a MM on MMagent if needed
+ // will update the MMagent whitelist with all topics for this MM
+ public MirrorMaker updateMirrorMaker( MirrorMaker mm ) {
+ logger.info( "updateMirrorMaker");
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ String provUser = p.getProperty("MM.ProvUserMechId");
+ String provUserPwd = AndrewDecryptor.valueOf(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!!!!
+
+ MR_Cluster central = clusters.getMr_ClusterByFQDN(mm.getTargetCluster());
+ if ( central != null ) {
+ prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn() );
+ 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());
+ mm.setStatus(DmaapObject_Status.INVALID);
+ } else {
+ prov.makeTopicConnection(central, dmaap.getBridgeAdminFqtn() );
+ resp = prov.doPostMessage(mm.updateWhiteList());
+ if ( ! resp.is2xx()) {
+ logger.error( "Unable to publish MR Bridge provisioning message. rc=" + resp.getCode() + " msg=" + resp.getMessage());
+ mm.setStatus(DmaapObject_Status.INVALID);
+ } else {
+ mm.setStatus(DmaapObject_Status.VALID);
+ }
+ }
+
+ } else {
+ logger.warn( "target cluster " + mm.getTargetCluster() + " not found!");
+ }
+
+ mm.setLastMod();
+ return mirrors.put( mm.getMmName(), mm);
+ }
+ public MirrorMaker getMirrorMaker( String part1, String part2 ) {
+ logger.info( "getMirrorMaker using " + part1 + " and " + part2 );
+ return mirrors.get(MirrorMaker.genKey(part1, part2));
+ }
+ public MirrorMaker getMirrorMaker( String key ) {
+ logger.info( "getMirrorMaker using " + key);
+ return mirrors.get(key);
+ }
+
+ /*public MirrorMaker updateMirrorMaker( MirrorMaker mm ) {
+ logger.info( "updateMirrorMaker");
+ return mirrors.put( mm.getMmName(), mm);
+ }
+ */
+
+ public void delMirrorMaker( MirrorMaker mm ) {
+ logger.info( "delMirrorMaker");
+ mirrors.remove(mm.getMmName());
+ }
+
+ // TODO: this should probably return sequential values or get replaced by the MM client API
+ // but it should be sufficient for initial 1610 development
+ public static String genTransactionId() {
+ RandomInteger ri = new RandomInteger(100000);
+ int randomInt = ri.next();
+ return Integer.toString(randomInt);
+ }
+ public List<String> getAllMirrorMakers() {
+ List<String> ret = new ArrayList<String>();
+ for( String key: mirrors.keySet()) {
+ ret.add( key );
+ }
+
+ return ret;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/service/TopicService.java b/src/main/java/org/openecomp/dmaapbc/service/TopicService.java new file mode 100644 index 0000000..0240fab --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/service/TopicService.java @@ -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=========================================================
+ */
+
+package org.openecomp.dmaapbc.service;
+
+import java.util.ArrayList;
+import java.util.Collection;
+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.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.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);
+
+ // TODO put these in properties file
+ String topicFactory = "org.openecomp.dcae.dmaap.topicFactory";
+
+ private Map<String, Topic> mr_topics = DatabaseClass.getTopics();
+ private Map<String, MR_Cluster> clusters = DatabaseClass.getMr_clusters();
+
+ private Dmaap dmaap = new DmaapService().getDmaap();
+ private MR_ClientService clientService = new MR_ClientService();
+ private MirrorMakerService bridge = new MirrorMakerService();
+
+
+ public Map<String, Topic> getTopics() {
+ return mr_topics;
+ }
+
+ public List<Topic> getAllTopics() {
+ ArrayList<Topic> topics = new ArrayList<Topic>(mr_topics.values());
+ for( Topic topic: topics ) {
+ topic.setClients( clientService.getAllMrClients(topic.getFqtn()));
+ }
+ return topics;
+ }
+
+
+ public Topic getTopic( String key, ApiError apiError ) {
+ logger.info( "getTopic: key=" + key);
+ Topic t = mr_topics.get( key );
+ if ( t == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setFields( "fqtn");
+ apiError.setMessage("topic with fqtn " + key + " not found");
+ return null;
+ }
+ t.setClients( clientService.getAllMrClients( key ));
+ apiError.setCode(Status.OK.getStatusCode());
+ return t;
+ }
+
+ public Topic addTopic( Topic topic, ApiError err ) {
+ logger.info( "Entry: addTopic");
+ String nFqtn = Topic.genFqtn( topic.getTopicName() );
+ if ( getTopic( nFqtn, err ) != null ) {
+ String t = "topic already exists: " + nFqtn;
+ logger.info( t );
+ err.setMessage( t );
+ err.setFields( "fqtn");
+ err.setCode(Status.CONFLICT.getStatusCode());
+ return null;
+ }
+ 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();
+
+ String[] actions = { "pub", "sub", "view" };
+ for ( String action : actions ){
+ DmaapPerm perm = new DmaapPerm( t, instance, action );
+ int rc = aaf.addPerm( perm );
+ if ( rc != 201 && rc != 409 ) {
+ err.setCode(500);
+ err.setMessage("Unexpected response from AAF:" + rc );
+ err.setFields("t="+t + " instance="+ instance + " action="+ action);
+ return null;
+ }
+ }
+
+
+ if ( topic.getNumClients() > 0 ) {
+ ArrayList<MR_Client> clients = new ArrayList<MR_Client>(topic.getClients());
+
+
+ ArrayList<MR_Client> clients2 = new ArrayList<MR_Client>();
+ for ( Iterator<MR_Client> it = clients.iterator(); it.hasNext(); ) {
+ MR_Client c = it.next();
+
+ logger.info( "c fqtn=" + c.getFqtn() + " ID=" + c.getMrClientId() + " url=" + c.getTopicURL());
+ MR_Client nc = new MR_Client( c.getDcaeLocationName(), topic.getFqtn(), c.getClientRole(), c.getAction());
+ nc.setFqtn(topic.getFqtn());
+ logger.info( "nc fqtn=" + nc.getFqtn() + " ID=" + nc.getMrClientId() + " url=" + nc.getTopicURL());
+ clients2.add( clientService.addMr_Client(nc, topic, err));
+ if ( ! err.is2xx()) {
+ return null;
+ }
+ }
+
+ 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 ( anythingWrong ) {
+ 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);
+ err.setCode(Status.OK.getStatusCode());
+ return topic;
+ }
+
+
+ public Topic updateTopic( Topic topic ) {
+ if ( topic.getFqtn().isEmpty()) {
+ return null;
+ }
+ mr_topics.put( topic.getFqtn(), topic );
+ return topic;
+ }
+
+ public Topic removeTopic( String pubId, ApiError apiError ) {
+ if ( mr_topics.get(pubId) == null ) {
+ apiError.setCode(Status.NOT_FOUND.getStatusCode());
+ apiError.setMessage("Topic " + pubId + " does not exist");
+ apiError.setFields("fqtn");
+ return null;
+ }
+ apiError.setCode(Status.OK.getStatusCode());
+ return mr_topics.remove(pubId);
+ }
+ public static ApiError setBridgeClientPerms( MR_Cluster node ) {
+ DmaapConfig p = (DmaapConfig)DmaapConfig.getConfig();
+ String mmProvRole = p.getProperty("MM.ProvRole");
+ String mmAgentRole = p.getProperty("MM.AgentRole");
+ String[] Roles = { mmProvRole, mmAgentRole };
+ String[] actions = { "view", "pub", "sub" };
+ Topic bridgeAdminTopic = new Topic();
+ bridgeAdminTopic.setTopicName( DatabaseClass.getDmaap().get().getBridgeAdminTopic());
+ bridgeAdminTopic.setTopicDescription( "RESERVED topic for MirroMaker Provisioning");
+ bridgeAdminTopic.setOwner( "DBC" );
+ ArrayList<MR_Client> clients = new ArrayList<MR_Client>();
+ for( String role: Roles ) {
+ MR_Client client = new MR_Client();
+ client.setAction(actions);
+ client.setClientRole(role);
+ client.setDcaeLocationName( node.getDcaeLocationName());
+ clients.add( client );
+ }
+ bridgeAdminTopic.setClients(clients);
+
+ TopicService ts = new TopicService();
+ ApiError err = new ApiError();
+ ts.addTopic(bridgeAdminTopic, err);
+
+ if ( err.is2xx() || err.getCode() == 409 ){
+ err.setCode(200);
+ return err;
+ }
+
+ logger.error( "Unable to create MM provisioning topic " + bridgeAdminTopic.getFqtn());
+ return err;
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/util/DmaapConfig.java b/src/main/java/org/openecomp/dmaapbc/util/DmaapConfig.java new file mode 100644 index 0000000..31c01b0 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/DmaapConfig.java @@ -0,0 +1,50 @@ +/*-
+ * ============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.util;
+
+import java.io.*;
+import java.util.*;
+
+public class DmaapConfig extends Properties {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private static String configfname = System.getProperty("ConfigFile", "etc/dmaapbc.properties");
+ private static Properties config = new DmaapConfig();
+ public static Properties getConfig() {
+ return(config);
+ }
+ public static String getConfigFileName() {
+ return(configfname);
+ }
+ private DmaapConfig() {
+ try {
+ InputStream is = new FileInputStream(configfname);
+ load(is);
+ is.close();
+ } catch (Exception e) {
+ System.err.println("Unable to load configuration file " + configfname);
+ org.apache.log4j.Logger.getLogger(getClass()).fatal("Unable to load configuration file " + configfname, e);
+ System.exit(1);
+ }
+ }
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/util/DmaapTimestamp.java b/src/main/java/org/openecomp/dmaapbc/util/DmaapTimestamp.java new file mode 100644 index 0000000..080773f --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/DmaapTimestamp.java @@ -0,0 +1,51 @@ +/*-
+ * ============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.util;
+
+import java.util.Calendar;
+import java.util.Date;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.log4j.Logger;
+
+@XmlRootElement
+public class DmaapTimestamp {
+ static final Logger logger = Logger.getLogger(DmaapTimestamp.class);
+ private static Calendar cal = Calendar.getInstance();
+ private Date stamp;
+
+ public DmaapTimestamp() {
+
+ stamp = cal.getTime();
+ logger.info("constructor: set val to " + stamp);
+ }
+
+ public void mark() {
+ stamp = cal.getTime();
+ logger.info("mark: set val to " + stamp);
+ }
+
+ public Date getVal() {
+ return stamp;
+ }
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/util/Graph.java b/src/main/java/org/openecomp/dmaapbc/util/Graph.java new file mode 100644 index 0000000..bdb1f6e --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/Graph.java @@ -0,0 +1,111 @@ +/*-
+ * ============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.util;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.openecomp.dmaapbc.database.DatabaseClass;
+import org.openecomp.dmaapbc.model.DcaeLocation;
+import org.openecomp.dmaapbc.model.MR_Client;
+
+
+public class Graph {
+ private HashMap<String, String> graph;
+ private boolean hasCentral;
+
+ private Map<String, DcaeLocation> locations = DatabaseClass.getDcaeLocations();
+
+ //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 ) {
+ if ( clients == null )
+ return;
+ this.graph = new HashMap<String, String>();
+ this.hasCentral = false;
+ for( MR_Client client: clients ) {
+ if ( client.isStatusValid()) {
+ String loc = client.getDcaeLocationName();
+ for( String action : client.getAction() ){
+ DcaeLocation dcaeLoc = locations.get(loc);
+ if ( ! action.equals("view") && dcaeLoc != null ) {
+ graph.put(loc, dcaeLoc.getDcaeLayer());
+ }
+ }
+ String layer = graph.get(loc);
+ if ( layer != null && layer.contains(centralDcaeLayerName) ) {
+ this.hasCentral = true;
+ }
+
+ }
+ }
+ }
+
+ public HashMap<String, String> getGraph() {
+ return graph;
+ }
+
+ public void setGraph(HashMap<String, String> graph) {
+ this.graph = graph;
+ }
+
+ public String put( String key, String val ) {
+ return graph.put(key, val);
+ }
+
+ public String get( String key ) {
+ return graph.get(key);
+ }
+
+ public Collection<String> getKeys() {
+ return graph.keySet();
+ }
+ public boolean isHasCentral() {
+ return hasCentral;
+ }
+ public void setHasCentral(boolean hasCentral) {
+ this.hasCentral = hasCentral;
+ }
+
+ public String getCentralLoc() {
+ if ( ! hasCentral ) {
+ return null;
+ }
+ for( String loc : graph.keySet()) {
+ if ( graph.get(loc).contains(centralDcaeLayerName)) {
+ return loc;
+ }
+ }
+ return null;
+ }
+
+
+}
diff --git a/src/main/java/org/openecomp/dmaapbc/util/RandomInteger.java b/src/main/java/org/openecomp/dmaapbc/util/RandomInteger.java new file mode 100644 index 0000000..e8086ce --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/RandomInteger.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.util;
+
+import java.util.Date;
+// source: http://www.javapractices.com/topic/TopicAction.do?Id=62
+// with some modifications
+import java.util.Random;
+
+
+public final class RandomInteger {
+ private static Random randomGenerator;
+ private int range;
+
+ public RandomInteger( int r ) {
+ randomGenerator = new Random();
+ randomGenerator.setSeed((new Date()).getTime());
+ range = r;
+ }
+
+ public int next(){
+ return randomGenerator.nextInt(range);
+ }
+
+ /** Generate 10 random integers in the range 0..99. */
+ public static final void main(String... aArgs){
+ log("Generating 10 random integers in range 0..99.");
+ RandomInteger ri = new RandomInteger(100);
+ //note a single Random object is reused here
+
+ for (int idx = 1; idx <= 10; ++idx){
+ int randomInt = ri.next();
+ log("Generated : " + randomInt);
+ }
+
+ log("Done.");
+ }
+
+ private static void log(String aMessage){
+ System.out.println(aMessage);
+ }
+}
+
diff --git a/src/main/java/org/openecomp/dmaapbc/util/RandomString.java b/src/main/java/org/openecomp/dmaapbc/util/RandomString.java new file mode 100644 index 0000000..259ed32 --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/RandomString.java @@ -0,0 +1,55 @@ +/*-
+ * ============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.util;
+
+import java.util.Random;
+
+// source: http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string
+
+public class RandomString {
+
+ private static final char[] symbols;
+
+ static {
+ StringBuilder tmp = new StringBuilder();
+ for (char ch = '0'; ch <= '9'; ++ch)
+ tmp.append(ch);
+ for (char ch = 'a'; ch <= 'z'; ++ch)
+ tmp.append(ch);
+ symbols = tmp.toString().toCharArray();
+ }
+
+ private final Random random = new Random();
+
+ private final char[] buf;
+
+ public RandomString(int length) {
+ if (length < 1)
+ throw new IllegalArgumentException("length < 1: " + length);
+ buf = new char[length];
+ }
+
+ public String nextString() {
+ for (int idx = 0; idx < buf.length; ++idx)
+ buf[idx] = symbols[random.nextInt(symbols.length)];
+ return new String(buf);
+ }
+ }
diff --git a/src/main/java/org/openecomp/dmaapbc/util/Singleton.java b/src/main/java/org/openecomp/dmaapbc/util/Singleton.java new file mode 100644 index 0000000..b60509f --- /dev/null +++ b/src/main/java/org/openecomp/dmaapbc/util/Singleton.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.util;
+
+public interface Singleton<T> {
+ public T get();
+ public void init(T val);
+ public void update(T val);
+ public void remove();
+}
diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 0000000..bfaeaf2 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -0,0 +1,29 @@ +### +# ============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========================================================= +### + +log4j.debug=FALSE +log4j.rootLogger=INFO,Root + +log4j.appender.Root=org.apache.log4j.DailyRollingFileAppender +log4j.appender.Root.file=logs/dmaapBC-api.log +log4j.appender.Root.datePattern='.'yyyyMMdd +log4j.appender.Root.append=true +log4j.appender.Root.layout=org.apache.log4j.PatternLayout +log4j.appender.Root.layout.ConversionPattern=%d %p %F %L %t %m%n diff --git a/src/main/resources/schema_0.sql b/src/main/resources/schema_0.sql new file mode 100644 index 0000000..3b59800 --- /dev/null +++ b/src/main/resources/schema_0.sql @@ -0,0 +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 +-- limitations under the License. +-- ============LICENSE_END========================================================= +--- + +@drop table dcae_location; +@drop table dmaap; +@drop table dr_node; +@drop table dr_pub; +@drop table dr_sub; +@drop table mr_client; +@drop table mr_cluster; +@drop table feed; +@drop table topic; +@drop table mirror_maker; +@drop table dmaapbc_sch_ver; +CREATE TABLE dmaapbc_sch_ver ( + version INTEGER +); +INSERT INTO dmaapbc_sch_ver (version) VALUES (0); diff --git a/src/main/resources/schema_1.sql b/src/main/resources/schema_1.sql new file mode 100644 index 0000000..27ae13f --- /dev/null +++ b/src/main/resources/schema_1.sql @@ -0,0 +1,136 @@ +--- +-- ============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========================================================= +--- + +@drop table dcae_location; +create table dcae_location ( + dcae_location_name VARCHAR(100), + clli VARCHAR(100), + dcae_layer VARCHAR(100), + open_stack_availability_zone VARCHAR(100), + last_mod TIMESTAMP, + PRIMARY KEY(dcae_location_name) +); +@drop table dmaap; +create table dmaap ( + version VARCHAR(100), + topic_ns_root VARCHAR(100), + dmaap_name VARCHAR(100), + dr_prov_url VARCHAR(200), + node_key VARCHAR(100), + access_key_owner VARCHAR(100), + last_mod TIMESTAMP, + status VARCHAR(100), + bridge_admin_topic VARCHAR(100), + logging_url VARCHAR(200) +); +@drop table dr_node; +create table dr_node ( + fqdn VARCHAR(100), + dcae_location_name VARCHAR(100), + host_name VARCHAR(100), + version VARCHAR(100), + PRIMARY KEY(fqdn) +); +@drop table dr_pub; +create table dr_pub ( + dcae_location_name VARCHAR(100), + username VARCHAR(100), + userpwd VARCHAR(100), + feed_id VARCHAR(100), + pub_id VARCHAR(100), + status VARCHAR(100), + PRIMARY KEY(pub_id) +); +@drop table dr_sub; +create table dr_sub ( + owner VARCHAR(100), + suspended BOOLEAN, + status VARCHAR(100), + use100 BOOLEAN, + dcae_location_name VARCHAR(100), + username VARCHAR(100), + userpwd VARCHAR(100), + feed_id VARCHAR(100), + delivery_u_r_l VARCHAR(200), + log_u_r_l VARCHAR(200), + sub_id VARCHAR(100), + PRIMARY KEY(sub_id) +); +@drop table mr_client; +create table mr_client ( + dcae_location_name VARCHAR(100), + fqtn VARCHAR(100), + client_role VARCHAR(100), + action VARCHAR(300), + mr_client_id VARCHAR(100), + status VARCHAR(100), + topic_u_r_l VARCHAR(200), + last_mod TIMESTAMP, + PRIMARY KEY(mr_client_id) +); +@drop table mr_cluster; +create table mr_cluster ( + last_mod TIMESTAMP, + dcae_location_name VARCHAR(100), + fqdn VARCHAR(100), + hosts VARCHAR(300), + topic_protocol VARCHAR(100), + topic_port VARCHAR(100), + PRIMARY KEY(dcae_location_name) +); +@drop table feed; +create table feed ( + suspended BOOLEAN, + subscribe_u_r_l VARCHAR(200), + feed_id VARCHAR(100), + feed_name VARCHAR(100), + feed_version VARCHAR(100), + feed_description VARCHAR(1000), + owner VARCHAR(100), + aspr_classification VARCHAR(100), + publish_u_r_l VARCHAR(200), + log_u_r_l VARCHAR(200), + status VARCHAR(100), + -- pubs not stored here + -- subs not stored here + PRIMARY KEY(feed_id) +); +@drop table topic; +create table topic ( + last_mod TIMESTAMP, + fqtn VARCHAR(100), + topic_name VARCHAR(100), + topic_description VARCHAR(1000), + tnx_enabled VARCHAR(100), + owner VARCHAR(100), + status VARCHAR(100), + -- clients not stored here + PRIMARY KEY(fqtn) +); +@drop table mirror_maker; +create table mirror_maker ( + mm_name VARCHAR(100), + source_cluster VARCHAR(100), + target_cluster VARCHAR(100), + last_mod TIMESTAMP, + vectors TEXT, + PRIMARY KEY(source_cluster) +); +update dmaapbc_sch_ver set version = 1 where version = 0; diff --git a/src/main/resources/schema_2.sql b/src/main/resources/schema_2.sql new file mode 100644 index 0000000..c9e5c02 --- /dev/null +++ b/src/main/resources/schema_2.sql @@ -0,0 +1,51 @@ +--- +-- ============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========================================================= +--- + +@alter table dcae_location + add column subnet VARCHAR(100), + add column status VARCHAR(100) +; + +@alter table dr_node + add column last_mod TIMESTAMP, + add column status VARCHAR(100) +; +@alter table dr_pub + add column last_mod TIMESTAMP +; +@alter table dr_sub + add column last_mod TIMESTAMP +; + +@alter table mr_cluster + add column status VARCHAR(100) +; +@alter table feed + add column last_mod TIMESTAMP, + add column format_uuid VARCHAR(100) +; +@alter table topic + add column format_uuid VARCHAR(100) +; + +@alter table mirror_maker + add column status VARCHAR(100) +; +update dmaapbc_sch_ver set version = 2 where version = 1; diff --git a/src/main/resources/schema_3.sql b/src/main/resources/schema_3.sql new file mode 100644 index 0000000..0f28988 --- /dev/null +++ b/src/main/resources/schema_3.sql @@ -0,0 +1,29 @@ +--- +-- ============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========================================================= +--- + + +@alter table mirror_maker + add column topics TEXT +; +@alter table mirror_maker + drop column vectors +; +@delete from mirror_maker; +update dmaapbc_sch_ver set version = 3 where version = 2; diff --git a/src/main/resources/schema_4.sql b/src/main/resources/schema_4.sql new file mode 100644 index 0000000..727c4bd --- /dev/null +++ b/src/main/resources/schema_4.sql @@ -0,0 +1,33 @@ +--- +-- ============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========================================================= +--- + + +@drop table mirror_maker; +create table mirror_maker ( + mm_name VARCHAR(512), + source_cluster VARCHAR(256), + target_cluster VARCHAR(256), + last_mod TIMESTAMP, + topics TEXT, + PRIMARY KEY(source_cluster) +); + + +update dmaapbc_sch_ver set version = 4 where version = 3; diff --git a/src/main/resources/schema_5.sql b/src/main/resources/schema_5.sql new file mode 100644 index 0000000..cd7130b --- /dev/null +++ b/src/main/resources/schema_5.sql @@ -0,0 +1,25 @@ +--- +-- ============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========================================================= +--- + + +@delete from mirror_maker; + + +update dmaapbc_sch_ver set version = 5 where version = 4; diff --git a/src/main/resources/schema_6.sql b/src/main/resources/schema_6.sql new file mode 100644 index 0000000..7c2bbd7 --- /dev/null +++ b/src/main/resources/schema_6.sql @@ -0,0 +1,33 @@ +--- +-- ============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========================================================= +--- + + +@drop table mirror_maker; +create table mirror_maker ( + mm_name VARCHAR(512), + source_cluster VARCHAR(256), + target_cluster VARCHAR(256), + last_mod TIMESTAMP, + topics TEXT, + PRIMARY KEY(mm_name) +); + + +update dmaapbc_sch_ver set version = 6 where version = 5; diff --git a/src/main/webapp/HelloJetty.html b/src/main/webapp/HelloJetty.html new file mode 100644 index 0000000..4d61636 --- /dev/null +++ b/src/main/webapp/HelloJetty.html @@ -0,0 +1,30 @@ +<!DOCTYPE html> +<!-- + ============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========================================================= + --> + +<html> +<head> +<meta charset="ISO-8859-1"> +<title>Index</title> +</head> +<body> +Hello Jetty! +</body> +</html> diff --git a/src/main/webapp/WEB-INF/log4j.xml b/src/main/webapp/WEB-INF/log4j.xml new file mode 100644 index 0000000..4e4d5e9 --- /dev/null +++ b/src/main/webapp/WEB-INF/log4j.xml @@ -0,0 +1,45 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= + --> + +<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > +<log4j:configuration> + <appender name="dmaapBC" class="org.apache.log4j.RollingFileAppender"> + <param name="File" value="dmaapBC.log"/> + <param name="MaxFileSize" value="1000KB"/> + <param name="MaxBackupIndex" value="3"/> + <layout class="org.apache.log4j.PatternLayout"> + <param name="ConversionPattern" value="[%d{HH:mm:ss:SSS}] - %-6p - %c.%M() - %m%n"/> + </layout> + </appender> + <appender name="media" class="org.apache.log4j.ConsoleAppender"> + <param name="Threshold" value="FATAL"/> + <layout class="org.apache.log4j.PatternLayout"> + <param name="ConversionPattern" value="%d %-5r %-5p [%c] (%t:%x) %m%n"/> + </layout> + </appender> + <category name="org.openecomp.dcae.dmaapBC"> + <appender-ref ref="dmaapBC"/> + </category> + <root> + <priority value="all"/> + <appender-ref ref="media"/> + </root> +</log4j:configuration> diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..055fbf0 --- /dev/null +++ b/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= + --> + +<!-- This web.xml file is not required when using Servlet 3.0 container, + see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html --> +<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> + <servlet> + <servlet-name>Jersey Web Application</servlet-name> + <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> + <init-param> + <param-name>jersey.config.server.provider.packages</param-name> + <param-value>org.openecomp.dmaapBC</param-value> + </init-param> + <load-on-startup>1</load-on-startup> + </servlet> + <servlet-mapping> + <servlet-name>Jersey Web Application</servlet-name> + <url-pattern>/webapi/*</url-pattern> + </servlet-mapping> +</web-app> diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp new file mode 100644 index 0000000..45aa9e8 --- /dev/null +++ b/src/main/webapp/index.jsp @@ -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========================================================= + --%> + +<html> +<body> + <h2>Jersey RESTful Web Application!</h2> + <p><a href="webapi/dmaap">Jersey resource</a> + <p>Visit <a href="http://jersey.java.net">Project Jersey website</a> + for more information on Jersey! +</body> +</html> |