diff options
author | Seshu Kumar M <seshu.kumar.m@huawei.com> | 2018-03-14 09:22:15 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2018-03-14 09:22:15 +0000 |
commit | 09f3630ea990197e9d7b669aa2d6a63ec397bf3e (patch) | |
tree | 6625d3e9ac31600d86bf54a50e75dba61cc2c82a /bpmn/MSOCommonBPMN/src/main/java/org/openecomp | |
parent | a56de0e221751debd038aca5b6d20d8f9325d294 (diff) | |
parent | 38f720752af4d4aad8c4e467a288d9048659f688 (diff) |
Merge "AT&T 1712 and 1802 release code"
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/main/java/org/openecomp')
100 files changed, 4652 insertions, 3356 deletions
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/PayloadClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/PayloadClient.java new file mode 100644 index 0000000000..5a0de6f5e9 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/PayloadClient.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload; + +import org.openecomp.mso.bpmn.appc.payload.beans.*; + +import java.util.Optional; + +import com.fasterxml.jackson.core.JsonProcessingException; +import org.openecomp.mso.bpmn.core.json.JsonUtils; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PayloadClient { + + protected static ObjectMapper mapper = new ObjectMapper(); + + + public static Optional<String> upgradeFormat(Optional<String> payload, String vnfName) throws JsonProcessingException{ + UpgradeAction payloadResult = new UpgradeAction(); + ConfigurationParametersUpgrade configParams = new ConfigurationParametersUpgrade(); + String payloadString = payload.get(); + String existingSoftware = JsonUtils.getJsonValue(payloadString, "existing-software-version"); + String newSoftware = JsonUtils.getJsonValue(payloadString, "new-software-version"); + configParams.setExistingSoftwareVersion(existingSoftware); + configParams.setNewSoftwareVersion(newSoftware); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> resumeTrafficFormat(String vnfName) throws JsonProcessingException{ + ResumeTrafficAction payloadResult = new ResumeTrafficAction(); + ConfigurationParametersResumeTraffic configParams = new ConfigurationParametersResumeTraffic(); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> quiesceTrafficFormat(Optional<String> payload, String vnfName) throws JsonProcessingException{ + QuiesceTrafficAction payloadResult = new QuiesceTrafficAction(); + ConfigurationParametersQuiesce configParams = new ConfigurationParametersQuiesce(); + String payloadString = payload.get(); + String operationsTimeout = JsonUtils.getJsonValue(payloadString, "operations-timeout"); + configParams.setOperationsTimeout(operationsTimeout); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> startStopFormat(String aicIdentity) throws JsonProcessingException{ + StartStopAction payloadResult = new StartStopAction(); + payloadResult.setAICIdentity(aicIdentity); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> healthCheckFormat(String vnfName, String vnfHostIpAddress) throws JsonProcessingException{ + HealthCheckAction payloadResult = new HealthCheckAction(); + RequestParametersHealthCheck requestParams = new RequestParametersHealthCheck(); + ConfigurationParametersHealthCheck configParams = new ConfigurationParametersHealthCheck(); + requestParams.setVnfName(vnfName); + configParams.setVnfName(vnfName); + payloadResult.setConfigurationParameters(configParams); + payloadResult.setRequestParameters(requestParams); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + public static Optional<String> snapshotFormat(String vmId, String identityUrl)throws JsonProcessingException{ + SnapshotAction payloadResult = new SnapshotAction(); + payloadResult.setVmId(vmId); + payloadResult.setIdentityUrl(identityUrl); + return Optional.of(mapper.writeValueAsString(payloadResult)); + } + + /*public Optional<String> verifySnapshotFormat(Optional<String> payload) throws Exception, JsonProcessingException, JsonMappingException{ + final Snapshot check = mapper.readValue(payload.get(), Snapshot.class); + return Optional.of(mapper.writeValueAsString(check)); + } + + public Optional<String> verifyUpgradeFormat(Optional<String> payload) throws Exception, JsonProcessingException, JsonMappingException{ + final UpdateCheck check = mapper.readValue(payload.get(), UpdateCheck.class); + return Optional.of(mapper.writeValueAsString(check)); + } + + public Optional<String> verifyQuiesceTrafficFormat(Optional<String> payload)throws Exception, JsonProcessingException, JsonMappingException{ + final QuiesceTraffic check = mapper.readValue(payload.get(), QuiesceTraffic.class); + return Optional.of(mapper.writeValueAsString(check)); + } + */ + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigModifyAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigModifyAction.java new file mode 100644 index 0000000000..09ad2bf439 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigModifyAction.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"request-parameters",
+"configuration-parameters"
+})
+public class ConfigModifyAction {
+
+@JsonProperty("request-parameters")
+private RequestParametersConfigModify requestParameters;
+@JsonProperty("configuration-parameters")
+private ConfigurationParametersConfigModify configurationParameters;
+
+@JsonProperty("request-parameters")
+public RequestParametersConfigModify getRequestParameters() {
+return requestParameters;
+}
+
+@JsonProperty("request-parameters")
+public void setRequestParameters(RequestParametersConfigModify requestParameters) {
+this.requestParameters = requestParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public ConfigurationParametersConfigModify getConfigurationParameters() {
+return configurationParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public void setConfigurationParameters(ConfigurationParametersConfigModify configurationParameters) {
+this.configurationParameters = configurationParameters;
+}
+
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java new file mode 100644 index 0000000000..dda7856168 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersConfigModify.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"node0_hostname",
+"node0_backup_router_address"
+})
+public class ConfigurationParametersConfigModify {
+
+@JsonProperty("node0_hostname")
+private String node0Hostname;
+@JsonProperty("node0_backup_router_address")
+private String node0BackupRouterAddress;
+
+@JsonProperty("node0_hostname")
+public String getNode0Hostname() {
+return node0Hostname;
+}
+
+@JsonProperty("node0_hostname")
+public void setNode0Hostname(String node0Hostname) {
+this.node0Hostname = node0Hostname;
+}
+
+@JsonProperty("node0_backup_router_address")
+public String getNode0BackupRouterAddress() {
+return node0BackupRouterAddress;
+}
+
+@JsonProperty("node0_backup_router_address")
+public void setNode0BackupRouterAddress(String node0BackupRouterAddress) {
+this.node0BackupRouterAddress = node0BackupRouterAddress;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyDecision.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java index 98c7e1558d..000b1bdbf7 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyDecision.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersHealthCheck.java @@ -18,40 +18,28 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.policy; - - +package org.openecomp.mso.bpmn.appc.payload.beans; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "decision", "details" }) -public class PolicyDecision { - - @JsonProperty("decision") - private String decision; - @JsonProperty("details") - private String details; +@JsonPropertyOrder({ +"vnf_name" +}) +public class ConfigurationParametersHealthCheck { - @JsonProperty("decision") - public String getDecision() { - return decision; - } +@JsonProperty("vnf_name") +private String vnfName; - @JsonProperty("decision") - public void setDecision(String decision) { - this.decision = decision; - } - - @JsonProperty("details") - public String getDetails() { - return details; - } +@JsonProperty("vnf_name") +public String getVnfName() { +return vnfName; +} - @JsonProperty("details") - public void setDetails(String details) { - this.details = details; - } +@JsonProperty("vnf_name") +public void setVnfName(String vnfName) { +this.vnfName = vnfName; } +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyDecisionRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java index c83fb19e34..e354d9ca2e 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyDecisionRequest.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersQuiesce.java @@ -18,40 +18,42 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.policy; - - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "decisionAttributes", "ecompcomponentName" }) -public class PolicyDecisionRequest { - - @JsonProperty("decisionAttributes") - private DecisionAttributes decisionAttributes; - @JsonProperty("ecompcomponentName") - private String ecompcomponentName; - - @JsonProperty("decisionAttributes") - public DecisionAttributes getDecisionAttributes() { - return decisionAttributes; - } - - @JsonProperty("decisionAttributes") - public void setDecisionAttributes(DecisionAttributes decisionAttributes) { - this.decisionAttributes = decisionAttributes; - } - - @JsonProperty("ecompcomponentName") - public String getEcompcomponentName() { - return ecompcomponentName; - } - - @JsonProperty("ecompcomponentName") - public void setEcompcomponentName(String ecompcomponentName) { - this.ecompcomponentName = ecompcomponentName; - } - -} +package org.openecomp.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"vnf_name",
+"operations_timeout"
+})
+public class ConfigurationParametersQuiesce {
+
+@JsonProperty("vnf_name")
+private String vnfName;
+@JsonProperty("operations_timeout")
+private String operationsTimeout;
+
+@JsonProperty("vnf_name")
+public String getVnfName() {
+return vnfName;
+}
+
+@JsonProperty("vnf_name")
+public void setVnfName(String vnfName) {
+this.vnfName = vnfName;
+}
+
+@JsonProperty("operations_timeout")
+public String getOperationsTimeout() {
+return operationsTimeout;
+}
+
+@JsonProperty("operations_timeout")
+public void setOperationsTimeout(String operationsTimeout) {
+this.operationsTimeout = operationsTimeout;
+}
+
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java new file mode 100644 index 0000000000..820618e828 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersResumeTraffic.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"vnf_name"
+})
+public class ConfigurationParametersResumeTraffic {
+
+@JsonProperty("vnf_name")
+private String vnfName;
+
+@JsonProperty("vnf_name")
+public String getVnfName() {
+return vnfName;
+}
+
+@JsonProperty("vnf_name")
+public void setVnfName(String vnfName) {
+this.vnfName = vnfName;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java new file mode 100644 index 0000000000..0845e7c37d --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ConfigurationParametersUpgrade.java @@ -0,0 +1,71 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"vnf_name",
+"existing-software-version",
+"new-software-version"
+})
+public class ConfigurationParametersUpgrade {
+@JsonProperty("vnf_name")
+private String vnfName;
+@JsonProperty("existing-software-version")
+private String existingSoftwareVersion;
+@JsonProperty("new-software-version")
+private String newSoftwareVersion;
+
+@JsonProperty("vnf_name")
+public String getVnfName() {
+return vnfName;
+}
+
+@JsonProperty("vnf_name")
+public void setVnfName(String vnfName) {
+this.vnfName = vnfName;
+}
+
+@JsonProperty("existing-software-version")
+public String getExistingSoftwareVersion() {
+return existingSoftwareVersion;
+}
+
+@JsonProperty("existing-software-version")
+public void setExistingSoftwareVersion(String existingSoftwareVersion) {
+this.existingSoftwareVersion = existingSoftwareVersion;
+}
+
+@JsonProperty("new-software-version")
+public String getNewSoftwareVersion() {
+return newSoftwareVersion;
+}
+
+@JsonProperty("new-software-version")
+public void setNewSoftwareVersion(String newSoftwareVersion) {
+this.newSoftwareVersion = newSoftwareVersion;
+}
+
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/ServiceException.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/HealthCheckAction.java index 5ae1d5242b..53408f1ead 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/ServiceException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/HealthCheckAction.java @@ -18,56 +18,42 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai.entities; - -import java.util.List; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "messageId", - "text", - "variables" -}) -public class ServiceException { - - @JsonProperty("messageId") - private String messageId; - @JsonProperty("text") - private String text; - @JsonProperty("variables") - private List<String> variables = null; - - @JsonProperty("messageId") - public String getMessageId() { - return messageId; - } - - @JsonProperty("messageId") - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - @JsonProperty("text") - public String getText() { - return text; - } - - @JsonProperty("text") - public void setText(String text) { - this.text = text; - } - - @JsonProperty("variables") - public List<String> getVariables() { - return variables; - } - - @JsonProperty("variables") - public void setVariables(List<String> variables) { - this.variables = variables; - } - -} +
+package org.openecomp.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"request-parameters",
+"configuration-parameters"
+})
+public class HealthCheckAction {
+
+@JsonProperty("request-parameters")
+private RequestParametersHealthCheck requestParameters;
+@JsonProperty("configuration-parameters")
+private ConfigurationParametersHealthCheck configurationParameters;
+
+@JsonProperty("request-parameters")
+public RequestParametersHealthCheck getRequestParameters() {
+return requestParameters;
+}
+
+@JsonProperty("request-parameters")
+public void setRequestParameters(RequestParametersHealthCheck requestParameters) {
+this.requestParameters = requestParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public ConfigurationParametersHealthCheck getConfigurationParameters() {
+return configurationParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public void setConfigurationParameters(ConfigurationParametersHealthCheck configurationParameters) {
+this.configurationParameters = configurationParameters;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/QuiesceTrafficAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/QuiesceTrafficAction.java new file mode 100644 index 0000000000..cbe8ee0b91 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/QuiesceTrafficAction.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"configuration-parameters"
+})
+public class QuiesceTrafficAction {
+
+@JsonProperty("configuration-parameters")
+private ConfigurationParametersQuiesce configurationParameters;
+
+@JsonProperty("configuration-parameters")
+public ConfigurationParametersQuiesce getConfigurationParameters() {
+return configurationParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public void setConfigurationParameters(ConfigurationParametersQuiesce configurationParameters) {
+this.configurationParameters = configurationParameters;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/RequestError.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/RequestParametersConfigModify.java index 2fd3572401..41b3314e7c 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/RequestError.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/RequestParametersConfigModify.java @@ -18,29 +18,29 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai.entities; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "serviceException" -}) -public class RequestError { - - @JsonProperty("serviceException") - private ServiceException serviceException; - - @JsonProperty("serviceException") - public ServiceException getServiceException() { - return serviceException; - } - - @JsonProperty("serviceException") - public void setServiceException(ServiceException serviceException) { - this.serviceException = serviceException; - } - -} +package org.openecomp.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"vnf-host-ip-address"
+})
+public class RequestParametersConfigModify {
+
+@JsonProperty("vnf-host-ip-address")
+private String vnfHostIpAddress;
+
+@JsonProperty("vnf-host-ip-address")
+public String getVnfHostIpAddress() {
+return vnfHostIpAddress;
+}
+
+@JsonProperty("vnf-host-ip-address")
+public void setVnfHostIpAddress(String vnfHostIpAddress) {
+this.vnfHostIpAddress = vnfHostIpAddress;
+}
+
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/AAIError.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/RequestParametersHealthCheck.java index 5f895ef862..dcdb4fb71e 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/AAIError.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/RequestParametersHealthCheck.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai.entities; +package org.openecomp.mso.bpmn.appc.payload.beans; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -26,21 +26,22 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ - "requestError" +"vnf-name" }) -public class AAIError { +public class RequestParametersHealthCheck { - @JsonProperty("requestError") - private RequestError requestError; +@JsonProperty("vnf-name") +private String vnfName; - @JsonProperty("requestError") - public RequestError getRequestError() { - return requestError; - } - @JsonProperty("requestError") - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } +@JsonProperty("vnf-name") +public String getVnfName() { +return vnfName; +} +@JsonProperty("vnf-name") +public void setVnfName(String vnfName) { +this.vnfName = vnfName; } + +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ResumeTrafficAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ResumeTrafficAction.java new file mode 100644 index 0000000000..de4fe25cd7 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/ResumeTrafficAction.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"configuration-parameters"
+})
+public class ResumeTrafficAction {
+
+@JsonProperty("configuration-parameters")
+private ConfigurationParametersResumeTraffic configurationParameters;
+
+@JsonProperty("configuration-parameters")
+public ConfigurationParametersResumeTraffic getConfigurationParameters() {
+return configurationParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public void setConfigurationParameters(ConfigurationParametersResumeTraffic configurationParameters) {
+this.configurationParameters = configurationParameters;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/SnapshotAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/SnapshotAction.java new file mode 100644 index 0000000000..bb74798300 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/SnapshotAction.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"vm-id",
+"identity-url"
+})
+public class SnapshotAction {
+
+@JsonProperty("vm-id")
+private String vmId;
+@JsonProperty("identity-url")
+private String identityUrl;
+
+@JsonProperty("vm-id")
+public String getVmId() {
+return vmId;
+}
+
+@JsonProperty("vm-id")
+public void setVmId(String vmId) {
+this.vmId = vmId;
+}
+
+@JsonProperty("identity-url")
+public String getIdentityUrl() {
+return identityUrl;
+}
+
+@JsonProperty("identity-url")
+public void setIdentityUrl(String identityUrl) {
+this.identityUrl = identityUrl;
+}
+
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/StartStopAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/StartStopAction.java new file mode 100644 index 0000000000..6ef822fbe1 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/StartStopAction.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+" AICIdentity "
+})
+public class StartStopAction {
+
+@JsonProperty(" AICIdentity ")
+private String aICIdentity;
+
+@JsonProperty(" AICIdentity ")
+public String getAICIdentity() {
+return aICIdentity;
+}
+
+@JsonProperty(" AICIdentity ")
+public void setAICIdentity(String aICIdentity) {
+this.aICIdentity = aICIdentity;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/UpgradeAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/UpgradeAction.java new file mode 100644 index 0000000000..3486fa73ba --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/appc/payload/beans/UpgradeAction.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.bpmn.appc.payload.beans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"configuration-parameters"
+})
+public class UpgradeAction {
+
+@JsonProperty("configuration-parameters")
+private ConfigurationParametersUpgrade configurationParameters;
+
+@JsonProperty("configuration-parameters")
+public ConfigurationParametersUpgrade getConfigurationParameters() {
+return configurationParameters;
+}
+
+@JsonProperty("configuration-parameters")
+public void setConfigurationParameters(ConfigurationParametersUpgrade configurationParameters) {
+this.configurationParameters = configurationParameters;
+}
+}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java index daca9fcf3f..f61c692775 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/AbstractCallbackService.java @@ -25,7 +25,9 @@ import java.util.HashMap; import java.util.List;
import java.util.Map;
+import org.camunda.bpm.BpmPlatform;
import org.camunda.bpm.engine.MismatchingMessageCorrelationException;
+import org.camunda.bpm.engine.OptimisticLockingException;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.runtime.Execution;
import org.camunda.bpm.engine.runtime.MessageCorrelationResult;
@@ -241,12 +243,64 @@ public abstract class AbstractCallbackService extends ProcessEngineAwareService .setVariables(variables)
.processInstanceVariableEquals(correlationVariable, correlationValue)
.correlateWithResult();
-
+
} catch (MismatchingMessageCorrelationException e) {
// A correlation exception occurred even after we identified
// one waiting process. Throw it back to the client.
throw e;
- } catch (Exception e) {
+ } catch (OptimisticLockingException ole) {
+
+ String msg = "Caught " + ole.getClass().getSimpleName() + " after receiving " + messageEventName
+ + " with " + correlationVariable + " = '" + correlationValue
+ + "': " + ole;
+ LOGGER.debug(msg);
+ LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN CORRELATION ERROR -", MsoLogger.getServiceName(),
+ MsoLogger.ErrorCode.UnknownError, msg, ole);
+
+ //Retry for OptimisticLocking Exceptions
+ int retryCount = 0;
+ String retryStr = properties.get("mso.bpmn.optimisticlockingexception.retrycount");
+ if (retryStr != null) {
+ try {
+ retryCount = Integer.parseInt(retryStr);
+ } catch (NumberFormatException e) {
+ // Ignore
+ }
+ }
+
+ LOGGER.debug("Retry correlate for OptimisticLockingException, retryCount:" + retryCount);
+
+ for (; retryCount >0 ; retryCount--) {
+
+ try{
+ Thread.sleep(SLOW_POLL_INT_MS);
+
+ @SuppressWarnings("unused")
+ MessageCorrelationResult result = runtimeService
+ .createMessageCorrelation(messageEventName)
+ .setVariables(variables)
+ .processInstanceVariableEquals(correlationVariable, correlationValue)
+ .correlateWithResult();
+ retryCount = 0;
+ LOGGER.debug("OptimisticLockingException retry was successful, seting retryCount: " + retryCount);
+ } catch (OptimisticLockingException olex) {
+ //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
+ String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + olex;
+ LOGGER.debug(strMsg);
+ LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
+ MsoLogger.ErrorCode.UnknownError, strMsg, olex);
+ } catch (Exception excep) {
+ retryCount = 0;
+ //oleFlag = ex instanceof org.camunda.bpm.engine.OptimisticLockingException;
+ String strMsg = "Received exception, OptimisticLockingException retry failed, retryCount:" + retryCount + " | exception returned: " + excep;
+ LOGGER.debug(strMsg);
+ LOGGER.error(MessageEnum.BPMN_GENERAL_EXCEPTION, "BPMN", MsoLogger.getServiceName(),
+ MsoLogger.ErrorCode.UnknownError, strMsg, excep);
+ }
+
+ }
+
+ }catch (Exception e) {
// This must be an exception from the flow itself. Log it, but don't
// report it back to the client.
String msg = "Caught " + e.getClass().getSimpleName() + " running "
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapProperties.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java index 7bdd7dfe40..cd98860efe 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapProperties.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncCommonResource.java @@ -7,9 +7,9 @@ * 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. @@ -18,15 +18,16 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.dmaap; +package org.openecomp.mso.bpmn.common.workflow.service; -import java.util.Map; +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.ProcessEngines; -public interface DmaapProperties { - /** - * A map of strings which contains the properties for a dmaap client - * @return - */ - public Map<String, String> getProperties(); +public class WorkflowAsyncCommonResource extends WorkflowAsyncResource { + + @Override + public String getProcessEngineName() { + return "default"; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java index 608adcf756..db11db59f7 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/bpmn/common/workflow/service/WorkflowAsyncResource.java @@ -273,7 +273,6 @@ public class WorkflowAsyncResource extends ProcessEngineAwareService { return pes.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult() == null;
}
-
private static Map<String, Object> getInputVariables(VariableMapImpl variableMap) {
Map<String, Object> inputVariables = new HashMap<>();
@SuppressWarnings("unchecked")
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/ResponseExceptionMapper.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/ResponseExceptionMapper.java deleted file mode 100644 index e0e3e936be..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/ResponseExceptionMapper.java +++ /dev/null @@ -1,98 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Optional; - -import javax.annotation.Priority; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAcceptableException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.NotSupportedException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -@Provider -@Priority(value = 1) -public abstract class ResponseExceptionMapper implements ClientResponseFilter { - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - if (responseContext.getStatus() >= 300) { - String message = "empty message"; - if (responseContext.hasEntity()) { - Optional<String> result = this.extractMessage(responseContext.getEntityStream()); - if (result.isPresent()) { - message = result.get(); - } - } - Response.Status status = Response.Status.fromStatusCode(responseContext.getStatus()); - WebApplicationException webAppException; - switch (status) { - case BAD_REQUEST: - webAppException = new BadRequestException(message); - break; - case UNAUTHORIZED: - webAppException = new NotAuthorizedException(message); - break; - case FORBIDDEN: - webAppException = new ForbiddenException(message); - break; - case NOT_FOUND: - webAppException = new NotFoundException(message); - break; - case METHOD_NOT_ALLOWED: - webAppException = new NotAllowedException(message); - break; - case NOT_ACCEPTABLE: - webAppException = new NotAcceptableException(message); - break; - case PRECONDITION_FAILED: - webAppException = new PreconditionFailedException(message); - break; - case UNSUPPORTED_MEDIA_TYPE: - webAppException = new NotSupportedException(message); - break; - case INTERNAL_SERVER_ERROR: - webAppException = new InternalServerErrorException(message); - break; - case SERVICE_UNAVAILABLE: - webAppException = new WebApplicationException(message); - break; - default: - webAppException = new WebApplicationException(message); - } - throw webAppException; - } - } - - public abstract Optional<String> extractMessage(InputStream stream) throws IOException; -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/RestPropertiesLoader.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/RestPropertiesLoader.java deleted file mode 100644 index 6d49d9800f..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/RestPropertiesLoader.java +++ /dev/null @@ -1,55 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client; - -import java.util.Iterator; -import java.util.ServiceLoader; - -public class RestPropertiesLoader { - - private final ServiceLoader<RestProperties> services; - private RestPropertiesLoader() { - services = ServiceLoader.load(RestProperties.class); - } - - private static class Helper { - private static final RestPropertiesLoader INSTANCE = new RestPropertiesLoader(); - } - - public static RestPropertiesLoader getInstance() { - return Helper.INSTANCE; - } - - public <T> T getImpl(Class<? extends RestProperties> clazz) { - T result = null; - Iterator<RestProperties> propertyImpls = services.iterator(); - RestProperties item; - while (propertyImpls.hasNext()) { - item = propertyImpls.next(); - if (clazz.isAssignableFrom(item.getClass())) { - result = (T)item; - break; - } - } - - return result; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIClientResponseExceptionMapper.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIClientResponseExceptionMapper.java deleted file mode 100644 index 4d97c4df71..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIClientResponseExceptionMapper.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import java.io.IOException; - -import javax.annotation.Priority; -import javax.ws.rs.BadRequestException; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.InternalServerErrorException; -import javax.ws.rs.NotAcceptableException; -import javax.ws.rs.NotAllowedException; -import javax.ws.rs.NotAuthorizedException; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.NotSupportedException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.Provider; - -import org.openecomp.mso.client.aai.entities.AAIError; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Provider -@Priority(value = 1) -public class AAIClientResponseExceptionMapper implements ClientResponseFilter { - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - if (responseContext.getStatus() != Response.Status.OK.getStatusCode() && responseContext.hasEntity()) { - AAIError error = new ObjectMapper().readValue(responseContext.getEntityStream(), AAIError.class); - String message = error.getRequestError().getServiceException().getText(); - - Response.Status status = Response.Status.fromStatusCode(responseContext.getStatus()); - WebApplicationException webAppException; - switch (status) { - case BAD_REQUEST: - webAppException = new BadRequestException(message); - break; - case UNAUTHORIZED: - webAppException = new NotAuthorizedException(message); - break; - case FORBIDDEN: - webAppException = new ForbiddenException(message); - break; - case NOT_FOUND: - webAppException = new NotFoundException(message); - break; - case METHOD_NOT_ALLOWED: - webAppException = new NotAllowedException(message); - break; - case NOT_ACCEPTABLE: - webAppException = new NotAcceptableException(message); - break; - case UNSUPPORTED_MEDIA_TYPE: - webAppException = new NotSupportedException(message); - break; - case INTERNAL_SERVER_ERROR: - webAppException = new InternalServerErrorException(message); - break; - case SERVICE_UNAVAILABLE: - webAppException = new WebApplicationException(message); - break; - default: - webAppException = new WebApplicationException(message); - } - throw webAppException; - } - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAICommonObjectMapperProvider.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAICommonObjectMapperProvider.java deleted file mode 100644 index b15059e87b..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAICommonObjectMapperProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.MapperFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -@Provider -public class AAICommonObjectMapperProvider implements ContextResolver<ObjectMapper> { - - final ObjectMapper mapper; - - public AAICommonObjectMapperProvider() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - mapper.enable(MapperFeature.USE_ANNOTATIONS); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - } - - @Override - public ObjectMapper getContext(Class<?> type) { - return mapper; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIQueryObjectMapperProvider.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIQueryObjectMapperProvider.java deleted file mode 100644 index f261408c83..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIQueryObjectMapperProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.databind.AnnotationIntrospector; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector; -import com.fasterxml.jackson.databind.type.TypeFactory; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; - -@Provider -public class AAIQueryObjectMapperProvider extends AAICommonObjectMapperProvider { - - public AAIQueryObjectMapperProvider() { - super(); - AnnotationIntrospector aiJaxb = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); - AnnotationIntrospector aiJackson = new JacksonAnnotationIntrospector(); - // first Jaxb, second Jackson annotations - mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(aiJaxb, aiJackson)); - - } - - @Override - public ObjectMapper getContext(Class<?> type) { - return mapper; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java deleted file mode 100644 index 214be060e3..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.List; - -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Pserver; -import org.onap.aai.domain.yang.Pservers; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - -public interface AAIRestClient { - -Pservers getPhysicalServers(String hostName, String uuid); -List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException; -void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException; -void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; -GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java deleted file mode 100644 index af1eddf491..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import java.io.File; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import javax.net.ssl.SSLContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MediaType; - -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.GenericVnfs; -import org.onap.aai.domain.yang.Pserver; -import org.onap.aai.domain.yang.Pservers; -import org.openecomp.mso.bpmn.core.PropertyConfiguration; -import org.openecomp.mso.client.aai.entities.CustomQuery; -import org.openecomp.mso.client.aai.entities.Results; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -public class AAIRestClientImpl implements AAIRestClient { - - private final WebTarget webTarget; - - private static final String ENDPOINT_VERSION = "v10"; - private static final String ENDPOINT_GET_ALL = ENDPOINT_VERSION + "/cloud-infrastructure/pservers"; - private static final String ENDPOINT_GET_ALL_VNFS = ENDPOINT_VERSION + "/network/generic-vnfs"; - private static final String ENDPOINT_CUSTOM_QUERY = ENDPOINT_VERSION + "/query"; - private static final String PSERVER_VNF_QUERY = "pservers-fromVnf"; - private static final String GENERIC_VNF_PATH = ENDPOINT_VERSION + "/network/generic-vnfs/generic-vnf"; - private static final String SERVICE_TOPOLOGY_BY_SERVICE_INSTANCE_ID = "store(‘x’).union(__.in(‘subscribesTo’).has(‘aai-node-type’,’customer’).store(‘x’),__.out(‘uses’).has(‘aai-node-type’,’allotted-resource’).store(‘x’),__.in(‘hasInstance’).has(‘aai-node-type’,’generic-vnf’).store(‘x’).union(" - + ".out(‘has’).has(‘aai-node-type’,’vf-module’).store(‘x’),out(‘uses’).has(‘aai-node-type’,’volume-group’).store(‘x’)," - + ".out(‘hasLInterface’).has(‘aai-node-type’,’l-interface’).union(" - + ".out(‘hasIpAddress’).has(‘aai-node-type’,’l3-interface-ipv4-address’).store(‘x’).out(‘isMemberOf’).has(‘aai-node-type’,’l3-network’).store(‘x’)," - + ".out(‘hasIpAddress’).has(‘aai-node-type’,’l3-interface-ipv6-address’).store(‘x’).out(‘isMemberOf’).has(‘aai-node-type’,’l3-network’).store(‘x’)" - + ")," + ".out(‘runsOnVserver’).has(‘aai-node-type’,’vserver’).store(‘x’).union(" - + ".in(‘owns’).has(‘aai-node-type’,’tenant’).store(‘x’).in(‘has’).has(‘aai-node-type’,’cloud-region’).store(‘x’)," - + ".out(‘runsOnPserver’).has(‘aai-node-type’,’pserver’).store(‘x’)," - + ".out(‘hasLInterface’).has(‘aai-node-type’,’l-interface’).union(" - + ".out(‘hasIpAddress’).has(‘aai-node-type’,’l3-interface-ipv4-address’).store(‘x’).out(‘isMemberOf’).has(‘aai-node-type’,’l3-network’).store(‘x’)," - + ".out(‘hasIpAddress’).has(‘aai-node-type’,’l3-interface-ipv6-address’).store(‘x’).out(‘isMemberOf’).has(‘aai-node-type’,’l3-network’).store(‘x’)" - + ")" + ")" + ")" + ").cap(‘x’).unfold().dedup()"; - - public AAIRestClientImpl() throws NoSuchAlgorithmException { - - Logger logger = Logger.getLogger(getClass().getName()); - Map<String, String> properties = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); - Client client = this.getSSLClient(); - webTarget = client.register(logger).register(new AAIClientResponseExceptionMapper()) - .target(properties.get("aai.endpoint") + "/aai"); - } - - public AAIRestClientImpl(final String host) throws NoSuchAlgorithmException { - Logger logger = Logger.getLogger(getClass().getName()); - Client client = this.getSSLClient(); - webTarget = client.register(logger).register(new AAIClientResponseExceptionMapper()).target(host + "/aai"); - } - - @Override - public Pservers getPhysicalServers(String hostName, String uuid) { - return webTarget.register(AAIResourcesObjectMapperProvider.class).path(ENDPOINT_GET_ALL).request() - .header("X-FromAppId", "MSO").header("X-TransactionId", uuid) - .header("Content-Type", MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).get() - .readEntity(Pservers.class); - } - - @Override - public List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) - throws JsonParseException, JsonMappingException, IOException { - List<String> startNodes = new ArrayList<>(); - startNodes.add("network/generic-vnfs/generic-vnf/" + vnfId); - String jsonInput = webTarget.register(AAIQueryObjectMapperProvider.class).path(ENDPOINT_CUSTOM_QUERY) - .queryParam("format", "resource").request().header("X-FromAppId", "MSO") - .header("X-TransactionId", transactionLoggingUuid) - .header("Content-Type", MediaType.APPLICATION_JSON_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) - .put(Entity.entity(new CustomQuery(startNodes, PSERVER_VNF_QUERY), MediaType.APPLICATION_JSON)) - .readEntity(String.class); - - - return this.getListOfPservers(jsonInput); - } - - protected List<Pserver> getListOfPservers(String jsonInput) throws JsonParseException, JsonMappingException, IOException - { - ObjectMapper mapper = new AAIQueryObjectMapperProvider().getContext(Object.class); - Results<Map<String, Pserver>> resultsFromJson = mapper.readValue(jsonInput, - new TypeReference<Results<Map<String, Pserver>>>() { - }); - List<Pserver> results = new ArrayList<>(); - for (Map<String, Pserver> m : resultsFromJson.getResult()) { - results.add(m.get("pserver")); - } - return results; - } - - protected List<Pserver> getListOfPservers(File jsonInput) throws JsonParseException, JsonMappingException, IOException - { - ObjectMapper mapper = new AAIQueryObjectMapperProvider().getContext(Object.class); - Results<Map<String, Pserver>> resultsFromJson = mapper.readValue(jsonInput, - new TypeReference<Results<Map<String, Pserver>>>() { - }); - List<Pserver> results = new ArrayList<>(); - for (Map<String, Pserver> m : resultsFromJson.getResult()) { - results.add(m.get("pserver")); - } - return results; - } - - @Override - public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { - GenericVnfs genericVnfs = webTarget.register(AAIResourcesObjectMapperProvider.class).path(ENDPOINT_GET_ALL_VNFS) - .queryParam("vnf-name", vnfName).request().header("X-FromAppId", "MSO") - .header("X-TransactionId", transactionLoggingUuid).header("Content-Type", "application/json") - .accept(MediaType.APPLICATION_JSON_TYPE).get().readEntity(GenericVnfs.class); - - if (genericVnfs.getGenericVnf().size() > 1) - throw new IndexOutOfBoundsException ("Multiple Generic Vnfs Returned"); - - GenericVnf genericVnf = genericVnfs.getGenericVnf().get(0); - updateMaintenceFlagVnfId(genericVnf.getVnfId(), inMaint, transactionLoggingUuid); - } - - @Override - public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) - throws JsonParseException, JsonMappingException, IOException { - GenericVnf genericVnf = new GenericVnf(); - genericVnf.setInMaint(inMaint); - webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() - .header("X-FromAppId", "MSO").header("X-TransactionId", transactionLoggingUuid) - .header("Content-Type", "application/merge-patch+json") - .header("Accept", MediaType.APPLICATION_JSON_TYPE).header("X-HTTP-Method-Override", "PATCH") - .put(Entity.entity(genericVnf, MediaType.valueOf("application/merge-patch+json"))); - } - - @Override - public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { - return webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() - .header("X-FromAppId", "MSO").header("X-TransactionId", transactionLoggingUuid) - .header("Content-Type", "application/json").accept(MediaType.APPLICATION_JSON_TYPE).get() - .readEntity(GenericVnf.class); - } - - protected Client getSSLClient() throws NoSuchAlgorithmException { - return ClientBuilder.newBuilder().sslContext(SSLContext.getDefault()).build(); - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIUpdator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIUpdator.java deleted file mode 100644 index 3bdcdc56a3..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIUpdator.java +++ /dev/null @@ -1,31 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import java.io.IOException; - -public interface AAIUpdator { - - void updateVnfToLocked(String vnfName, String uuid) throws IOException, Exception; - - void updateVnfToUnLocked(String vnfName, String uuid) throws IOException, Exception; - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidator.java deleted file mode 100644 index 117ec42a36..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidator.java +++ /dev/null @@ -1,32 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import java.io.IOException; - -public interface AAIValidator { - - boolean isPhysicalServerLocked(String hostName, String transactionLoggingUuid) throws IOException; - - boolean isVNFLocked(String vnfId, String transactionLoggingUuid) throws IOException, Exception; - - -}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidatorImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidatorImpl.java deleted file mode 100644 index ce248f010c..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIValidatorImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai; - -import java.io.IOException; -import java.util.List; - -import org.onap.aai.domain.yang.GenericVnf; -import org.onap.aai.domain.yang.Pserver; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - - - -@Service -public class AAIValidatorImpl implements AAIValidator { - - - @Autowired - protected AAIRestClient client; - - public AAIRestClient getClient() { - return client; - } - - - public void setClient(AAIRestClient client) { - this.client = client; - } - - @Override - public boolean isPhysicalServerLocked(String vnfId, String transactionLoggingUuid) throws IOException { - List<Pserver> pservers; - boolean isLocked = false; - pservers = client.getPhysicalServerByVnfId(vnfId, transactionLoggingUuid); - for (Pserver pserver : pservers) - if (pserver.isInMaint()) - isLocked = true; - - return isLocked; - } - - @Override - public boolean isVNFLocked(String vnfId, String transactionLoggingUuid) throws Exception { - boolean isLocked = false; - GenericVnf genericVnf = client.getVnfByName(vnfId, transactionLoggingUuid); - if (genericVnf.isInMaint()) - isLocked = true; - - return isLocked; - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/CustomQuery.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/CustomQuery.java deleted file mode 100644 index fab8d64e09..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/CustomQuery.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.aai.entities; - -import java.io.UnsupportedEncodingException; -import java.util.List; - -import com.fasterxml.jackson.annotation.JsonInclude; - - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class CustomQuery { - - List<String> start; - - public String getGremlin() { - return gremlin; - } - - public void setGremlin(String gremlin) { - this.gremlin = gremlin; - } - String query; - String gremlin; - - public CustomQuery(List<String>start, String query){ - this.start=start; - this.query= "query/" + query; - } - - public CustomQuery(String gremlin) throws UnsupportedEncodingException{ - this.gremlin=gremlin; - } - - public List<String> getStart() { - return start; - } - - public void setStart(List<String> start) { - this.start = start; - } - - public String getQuery() { - return query; - } - - public void setQuery(String query) { - this.query = query; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClient.java new file mode 100644 index 0000000000..5e3aca5613 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClient.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.network;
+
+import org.openecomp.mso.adapters.nwrest.CreateNetworkRequest;
+import org.openecomp.mso.adapters.nwrest.CreateNetworkResponse;
+import org.openecomp.mso.adapters.nwrest.DeleteNetworkRequest;
+import org.openecomp.mso.adapters.nwrest.DeleteNetworkResponse;
+import org.openecomp.mso.adapters.nwrest.QueryNetworkResponse;
+import org.openecomp.mso.adapters.nwrest.RollbackNetworkRequest;
+import org.openecomp.mso.adapters.nwrest.RollbackNetworkResponse;
+import org.openecomp.mso.adapters.nwrest.UpdateNetworkRequest;
+import org.openecomp.mso.adapters.nwrest.UpdateNetworkResponse;
+
+public interface NetworkAdapterClient {
+
+ CreateNetworkResponse createNetwork(CreateNetworkRequest req);
+
+ DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req);
+
+ RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req);
+
+ QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId, String networkStackId, boolean skipAAI, String requestId, String serviceInstanceId);
+
+ UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req);
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClientImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClientImpl.java new file mode 100644 index 0000000000..6a1c862a66 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterClientImpl.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.network; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; + +import org.openecomp.mso.adapters.nwrest.CreateNetworkRequest; +import org.openecomp.mso.adapters.nwrest.CreateNetworkResponse; +import org.openecomp.mso.adapters.nwrest.DeleteNetworkRequest; +import org.openecomp.mso.adapters.nwrest.DeleteNetworkResponse; +import org.openecomp.mso.adapters.nwrest.QueryNetworkResponse; +import org.openecomp.mso.adapters.nwrest.RollbackNetworkRequest; +import org.openecomp.mso.adapters.nwrest.RollbackNetworkResponse; +import org.openecomp.mso.adapters.nwrest.UpdateNetworkRequest; +import org.openecomp.mso.adapters.nwrest.UpdateNetworkResponse; +import org.openecomp.mso.client.adapter.vnf.AdapterRestClient; + +public class NetworkAdapterClientImpl implements NetworkAdapterClient { + + private final NetworkAdapterRestProperties props; + public NetworkAdapterClientImpl() { + this.props = new NetworkAdapterRestProperties(); + } + @Override + public CreateNetworkResponse createNetwork(CreateNetworkRequest req) { + return new AdapterRestClient(this.props, this.getUri("").build()).post(req, + CreateNetworkResponse.class); + } + + @Override + public DeleteNetworkResponse deleteNetwork(String aaiNetworkId, DeleteNetworkRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req, + DeleteNetworkResponse.class); + } + + @Override + public RollbackNetworkResponse rollbackNetwork(String aaiNetworkId, RollbackNetworkRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).delete(req, + RollbackNetworkResponse.class); + } + + @Override + public QueryNetworkResponse queryNetwork(String aaiNetworkId, String cloudSiteId, String tenantId, + String networkStackId, boolean skipAAI, String requestId, String serviceInstanceId) { + UriBuilder builder = this.getUri("/" + aaiNetworkId); + if (cloudSiteId != null) { + builder.queryParam("cloudSiteId", cloudSiteId); + } + if (tenantId != null) { + builder.queryParam("tenantId", tenantId); + } + if (networkStackId != null) { + builder.queryParam("networkStackId", networkStackId); + } + + builder.queryParam("skipAAI", skipAAI); + + if (requestId != null) { + builder.queryParam("msoRequest.requestId", requestId); + } + if (serviceInstanceId != null) { + builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId); + } + return new AdapterRestClient(this.props, builder.build(), MediaType.TEXT_XML, MediaType.TEXT_XML) + .get(QueryNetworkResponse.class); + } + + @Override + public UpdateNetworkResponse updateNetwork(String aaiNetworkId, UpdateNetworkRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiNetworkId).build()).put(req, + UpdateNetworkResponse.class); + } + + protected UriBuilder getUri(String path) { + return UriBuilder.fromPath(path); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterRestProperties.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterRestProperties.java new file mode 100644 index 0000000000..62d78d423c --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/network/NetworkAdapterRestProperties.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.network; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; + +import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.client.adapter.vnf.AdapterRestProperties; + +public class NetworkAdapterRestProperties implements AdapterRestProperties { + + private final Map<String, String> props; + + public NetworkAdapterRestProperties() { + this.props = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); + } + + @Override + public String getAuth() { + return props.get("mso.adapters.po.auth"); + } + @Override + public String getKey() { + return props.get("mso.msoKey"); + } + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(props.get("mso.adapters.network.rest.endpoint")); + } + + @Override + public String getSystemName() { + return "MSO"; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/exceptions/SDNOException.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/MsoRequestsDbAdapter.java index ca6a943af5..c3ba8e16ea 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/exceptions/SDNOException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/MsoRequestsDbAdapter.java @@ -18,22 +18,18 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.exceptions; +package org.openecomp.mso.client.adapter.requests.db; +import org.openecomp.mso.client.adapter.requests.db.entities.MsoRequestsDbException; +import org.openecomp.mso.client.adapter.requests.db.entities.UpdateInfraRequest; +import org.openecomp.mso.requestsdb.InfraActiveRequests; -public class SDNOException extends Exception { +public interface MsoRequestsDbAdapter { - private static final long serialVersionUID = 6189163383568887383L; + public void updateInfraRequest(UpdateInfraRequest request) throws MsoRequestsDbException; - public SDNOException() { - super(); - } - - public SDNOException(String string) { - super(string); - } + public InfraActiveRequests getInfraRequest(String requestId) throws MsoRequestsDbException; + + public boolean getSiteStatus(String siteName); - public SDNOException(Exception e) { - super(e); - } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/MsoRequestsDbAdapterClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/MsoRequestsDbAdapterClient.java new file mode 100644 index 0000000000..109da17ea2 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/MsoRequestsDbAdapterClient.java @@ -0,0 +1,300 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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.mso.client.adapter.requests.db;
+
+import java.sql.Timestamp;
+
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.openecomp.mso.client.adapter.requests.db.entities.MsoRequestsDbException;
+import org.openecomp.mso.client.adapter.requests.db.entities.RequestStatusType;
+import org.openecomp.mso.client.adapter.requests.db.entities.UpdateInfraRequest;
+import org.openecomp.mso.db.AbstractSessionFactoryManager;
+import org.openecomp.mso.logger.MessageEnum;
+import org.openecomp.mso.logger.MsoLogger;
+import org.openecomp.mso.requestsdb.InfraActiveRequests;
+import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager;
+import org.openecomp.mso.requestsdb.SiteStatus;
+import org.openecomp.mso.utils.UUIDChecker;
+
+public class MsoRequestsDbAdapterClient implements MsoRequestsDbAdapter {
+
+ protected AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager();
+
+ private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
+
+ @Override
+ public void updateInfraRequest(UpdateInfraRequest request) throws MsoRequestsDbException {
+ Session session = requestsDbSessionFactoryManager.getSessionFactory().openSession();
+ int result = 0;
+ long startTime = System.currentTimeMillis();
+ if (request.getRequestId() != null && request.getLastModifiedBy() != null) {
+ MsoLogger.setLogContext(request.getRequestId(), null);
+ try {
+ session.beginTransaction();
+ String queryString = "update InfraActiveRequests set ";
+ String statusMessage = null;
+ String responseBody = null;
+ RequestStatusType requestStatus = null;
+ String progress = null;
+ String vnfOutputs = null;
+ String serviceInstanceId = null;
+ String networkId = null;
+ String vnfId = null;
+ String vfModuleId = null;
+ String volumeGroupId = null;
+ String serviceInstanceName = null;
+ String vfModuleName = null;
+ String configurationId = null;
+ String configurationName = null;
+ if (request.getStatusMessage() != null) {
+ queryString += "statusMessage = :statusMessage, ";
+ statusMessage = request.getStatusMessage();
+ }
+ if (request.getResponseBody() != null) {
+ queryString += "responseBody = :responseBody, ";
+ responseBody = request.getResponseBody();
+ }
+ if (request.getRequestStatus() != null) {
+ queryString += "requestStatus = :requestStatus, ";
+ requestStatus = request.getRequestStatus();
+ }
+ if (request.getProgress() != null) {
+ queryString += "progress = :progress, ";
+ progress = request.getProgress();
+ }
+ if (request.getVnfOutputs() != null) {
+ queryString += "vnfOutputs = :vnfOutputs, ";
+ vnfOutputs = request.getVnfOutputs();
+ }
+ if (request.getServiceInstanceId() != null) {
+ queryString += "serviceInstanceId = :serviceInstanceId, ";
+ serviceInstanceId = request.getServiceInstanceId();
+ }
+ if (request.getNetworkId() != null) {
+ queryString += "networkId = :networkId, ";
+ networkId = request.getNetworkId();
+ }
+ if (request.getVnfId() != null) {
+ queryString += "vnfId = :vnfId, ";
+ vnfId = request.getVnfId();
+ }
+ if (request.getVfModuleId() != null) {
+ queryString += "vfModuleId = :vfModuleId, ";
+ vfModuleId = request.getVfModuleId();
+ }
+ if (request.getVolumeGroupId() != null) {
+ queryString += "volumeGroupId = :volumeGroupId, ";
+ volumeGroupId = request.getVolumeGroupId();
+ }
+ if (request.getServiceInstanceName() != null) {
+ queryString += "serviceInstanceName = :serviceInstanceName, ";
+ serviceInstanceName = request.getServiceInstanceName();
+ }
+ if (request.getVfModuleName() != null) {
+ queryString += "vfModuleName = :vfModuleName, ";
+ vfModuleName = request.getVfModuleName();
+ }
+ if (request.getConfigurationId() != null) {
+ queryString += "configurationId = :configurationId, ";
+ configurationId = request.getConfigurationId();
+ }
+ if (request.getConfigurationName() != null) {
+ queryString += "configurationName = :configurationName, ";
+ configurationName = request.getConfigurationName();
+ }
+ if (request.getRequestStatus() == RequestStatusType.COMPLETE
+ || request.getRequestStatus() == RequestStatusType.FAILED) {
+ queryString += "endTime = :endTime, ";
+ } else {
+ queryString += "modifyTime = :modifyTime, ";
+ }
+ queryString += "lastModifiedBy = :lastModifiedBy where requestId = :requestId OR clientRequestId = :requestId";
+
+ LOGGER.debug("Executing update: " + queryString);
+
+ Query query = session.createQuery(queryString);
+ query.setParameter("requestId", request.getRequestId());
+ if (statusMessage != null) {
+ query.setParameter("statusMessage", statusMessage);
+ LOGGER.debug("StatusMessage in updateInfraRequest is set to: " + statusMessage);
+ }
+ if (responseBody != null) {
+ query.setParameter("responseBody", responseBody);
+ LOGGER.debug("ResponseBody in updateInfraRequest is set to: " + responseBody);
+ }
+ if (requestStatus != null) {
+ query.setParameter("requestStatus", requestStatus.toString());
+ LOGGER.debug("RequestStatus in updateInfraRequest is set to: " + requestStatus.toString());
+ }
+
+ if (progress != null) {
+ query.setParameter("progress", Long.parseLong(progress));
+ LOGGER.debug("Progress in updateInfraRequest is set to: " + progress);
+ }
+ if (vnfOutputs != null) {
+ query.setParameter("vnfOutputs", vnfOutputs);
+ LOGGER.debug("VnfOutputs in updateInfraRequest is set to: " + vnfOutputs);
+ }
+ if (serviceInstanceId != null) {
+ query.setParameter("serviceInstanceId", serviceInstanceId);
+ LOGGER.debug("ServiceInstanceId in updateInfraRequest is set to: " + serviceInstanceId);
+ }
+ if (networkId != null) {
+ query.setParameter("networkId", networkId);
+ LOGGER.debug("NetworkId in updateInfraRequest is set to: " + networkId);
+ }
+ if (vnfId != null) {
+ query.setParameter("vnfId", vnfId);
+ LOGGER.debug("VnfId in updateInfraRequest is set to: " + vnfId);
+ }
+ if (vfModuleId != null) {
+ query.setParameter("vfModuleId", vfModuleId);
+ LOGGER.debug("vfModuleId in updateInfraRequest is set to: " + vfModuleId);
+ }
+ if (volumeGroupId != null) {
+ query.setParameter("volumeGroupId", volumeGroupId);
+ LOGGER.debug("VolumeGroupId in updateInfraRequest is set to: " + volumeGroupId);
+ }
+ if (serviceInstanceName != null) {
+ query.setParameter("serviceInstanceName", serviceInstanceName);
+ LOGGER.debug("ServiceInstanceName in updateInfraRequest is set to: " + serviceInstanceName);
+ }
+ if (configurationId != null) {
+ query.setParameter("configurationId", configurationId);
+ LOGGER.debug("configurationId in updateInfraRequest is set to: " + configurationId);
+ }
+ if (configurationName != null) {
+ query.setParameter("configurationName", configurationName);
+ LOGGER.debug("configurationName in updateInfraRequest is set to: " + configurationName);
+ }
+ if (vfModuleName != null) {
+ query.setParameter("vfModuleName", vfModuleName);
+ LOGGER.debug("vfModuleName in updateInfraRequest is set to: " + vfModuleName);
+ }
+ Timestamp nowTimeStamp = new Timestamp(System.currentTimeMillis());
+ if (request.getRequestStatus() == RequestStatusType.COMPLETE
+ || request.getRequestStatus() == RequestStatusType.FAILED) {
+ query.setParameter("endTime", nowTimeStamp);
+ LOGGER.debug("EndTime in updateInfraRequest is set to: " + nowTimeStamp);
+ } else {
+ query.setParameter("modifyTime", nowTimeStamp);
+ LOGGER.debug("ModifyTime in updateInfraRequest is set to: " + nowTimeStamp);
+ }
+ query.setParameter("lastModifiedBy", request.getLastModifiedBy());
+ LOGGER.debug("LastModifiedBy in updateInfraRequest is set to: " + request.getLastModifiedBy());
+ result = query.executeUpdate();
+ checkIfExists(result, request.getRequestId(), startTime);
+ session.getTransaction().commit();
+ } catch (HibernateException e) {
+ String error = "Unable to update MSO Requests DB: " + e.getMessage();
+ LOGGER.error(MessageEnum.RA_CANT_UPDATE_REQUEST, "infra request parameters", request.getRequestId(), "",
+ "", MsoLogger.ErrorCode.BusinessProcesssError, "HibernateException - " + error, e);
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
+ error);
+ throw new MsoRequestsDbException(error, e);
+ } finally {
+ if (session != null && session.isOpen()) {
+ session.close();
+ }
+ }
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
+ } else {
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BadRequest,
+ "Required fields: requestId and lastModifiedBy");
+ }
+ }
+
+ private void checkIfExists(int result, String requestId, long startTime) throws MsoRequestsDbException {
+ if (result == 0) {
+ String error = "Request ID does not exist in MSO Requests DB: " + requestId;
+ LOGGER.error(MessageEnum.RA_DB_REQUEST_NOT_EXIST, requestId, "", "", MsoLogger.ErrorCode.DataError, error);
+ throw new MsoRequestsDbException(error);
+ }
+ }
+
+ @Override
+ public InfraActiveRequests getInfraRequest(String requestId) throws MsoRequestsDbException {
+ long startTime = System.currentTimeMillis();
+ MsoLogger.setLogContext(requestId, null);
+ Session session = requestsDbSessionFactoryManager.getSessionFactory().openSession();
+
+ LOGGER.debug("Call to MSO Infra RequestsDb adapter get method with request Id: " + requestId);
+
+ InfraActiveRequests request = null;
+ try {
+ session.beginTransaction();
+ Query query = session.createQuery(
+ "FROM InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
+ query.setParameter("requestId", requestId);
+ request = (InfraActiveRequests) query.uniqueResult();
+ } catch (HibernateException e) {
+ String error = "Unable to retrieve MSO Infra Requests DB for Request ID " + requestId;
+ LOGGER.error(MessageEnum.RA_DB_REQUEST_NOT_EXIST, "Get Infra request", requestId, "", "",
+ MsoLogger.ErrorCode.BusinessProcesssError, "HibernateException - " + error, e);
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, error);
+ throw new MsoRequestsDbException(error, e);
+ } finally {
+ if (session != null && session.isOpen()) {
+ session.close();
+ }
+ }
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
+ return request;
+ }
+
+ /**
+ * Get SiteStatus by SiteName.
+ *
+ * @param siteName
+ * The unique name of the site
+ * @return Status of that site
+ */
+ public boolean getSiteStatus(String siteName) {
+ UUIDChecker.generateUUID(LOGGER);
+ Session session = requestsDbSessionFactoryManager.getSessionFactory().openSession();
+
+ long startTime = System.currentTimeMillis();
+ SiteStatus siteStatus = null;
+ LOGGER.debug("Request database - get Site Status with Site name:" + siteName);
+ try {
+ String hql = "FROM SiteStatus WHERE siteName = :site_name";
+ Query query = session.createQuery(hql);
+ query.setParameter("site_name", siteName);
+
+ siteStatus = (SiteStatus) query.uniqueResult();
+ } finally {
+ if (session != null && session.isOpen()) {
+ session.close();
+ }
+ }
+ if (siteStatus == null) {
+ // if not exist in DB, it means the site is not disabled, thus
+ // return true
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
+ return true;
+ } else {
+ LOGGER.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
+ return siteStatus.getStatus();
+ }
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/MsoRequestsDbException.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/MsoRequestsDbException.java new file mode 100644 index 0000000000..a495d0eac1 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/MsoRequestsDbException.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.requests.db.entities; + + + +import javax.xml.ws.WebFault; + +/** + * This class simply extends Exception (without addition additional functionality) + * to provide an identifier for RequestsDB related exceptions on create, delete, query. + * + * + */ +@WebFault (name="MsoRequestsDbException", faultBean="org.openecomp.mso.adapters.requestsdb.exceptions.MsoRequestsDbExceptionBean", targetNamespace="http://org.openecomp.mso/requestsdb") +public class MsoRequestsDbException extends Exception { + + private static final long serialVersionUID = 1L; + + private MsoRequestsDbExceptionBean faultInfo; + + public MsoRequestsDbException (String msg) { + super(msg); + faultInfo = new MsoRequestsDbExceptionBean (msg); + } + + public MsoRequestsDbException (Throwable e) { + super(e); + faultInfo = new MsoRequestsDbExceptionBean (e.getMessage()); + } + + public MsoRequestsDbException (String msg, Throwable e) { + super (msg, e); + faultInfo = new MsoRequestsDbExceptionBean (msg); + } + + public MsoRequestsDbExceptionBean getFaultInfo() { + return faultInfo; + } + + public void setFaultInfo(MsoRequestsDbExceptionBean faultInfo) { + this.faultInfo = faultInfo; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/exceptions/ExceededMaximumPollingTime.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/MsoRequestsDbExceptionBean.java index c9d675067e..f566418ade 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/exceptions/ExceededMaximumPollingTime.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/MsoRequestsDbExceptionBean.java @@ -7,9 +7,9 @@ * 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. @@ -18,17 +18,31 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.dmaap.exceptions; +package org.openecomp.mso.client.adapter.requests.db.entities; -public class ExceededMaximumPollingTime extends RuntimeException { - private static final long serialVersionUID = 2331207691092906423L; +import java.io.Serializable; - public ExceededMaximumPollingTime() { - super(); +/** + * Jax-WS Fault Bean for MsoRequestsDB Exception + */ +public class MsoRequestsDbExceptionBean implements Serializable { + + private static final long serialVersionUID = 1360000062602372639L; + + private String message; + + public MsoRequestsDbExceptionBean () {} + + public MsoRequestsDbExceptionBean (String message) { + this.message = message; + } + + public String getMessage() { + return message; } - - public ExceededMaximumPollingTime(String message) { - super(message); + + public void setMessage(String message) { + this.message = message; } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/RequestStatusType.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/RequestStatusType.java new file mode 100644 index 0000000000..2fa6f2b6a2 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/RequestStatusType.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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 file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.07.24 at 11:49:17 AM EDT +// + + +package org.openecomp.mso.client.adapter.requests.db.entities; + + + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; + + +/** + * <p>Java class for request-status-type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * <pre> + * <simpleType name="request-status-type"> + * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> + * <enumeration value="COMPLETE"/> + * <enumeration value="FAILED"/> + * <enumeration value="IN_PROGRESS"/> + * </restriction> + * </simpleType> + * </pre> + * + */ +@XmlType(name = "request-status-type") +@XmlEnum +public enum RequestStatusType { + + COMPLETE, + FAILED, + IN_PROGRESS; + + public String value() { + return name(); + } + + public static RequestStatusType fromValue(String v) { + return valueOf(v); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/AAIEntity.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/ResponseStatus.java index eb0fb48678..cc00fd1ff2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/AAIEntity.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/ResponseStatus.java @@ -7,9 +7,9 @@ * 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. @@ -18,8 +18,16 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai.entities; +package org.openecomp.mso.client.adapter.requests.db.entities; -public class AAIEntity { + +/* + * Enum for Status values returned by API Handler to Tail-F +*/ +public enum ResponseStatus { + SENDING_FINAL_NOTIFY, + SUCCESS, + FAILED, + TIMEOUT } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIResourcesObjectMapperProvider.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/Status.java index a10225956b..e9750a2b3b 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIResourcesObjectMapperProvider.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/Status.java @@ -18,21 +18,23 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai; +package org.openecomp.mso.client.adapter.requests.db.entities; -import javax.ws.rs.ext.Provider; -import com.fasterxml.jackson.databind.ObjectMapper; +/* + * Enum for Status values returned by API Handler to Tail-F +*/ +public enum Status { + PENDING, INPROGRESS, COMPLETED, FAILED, TIMEOUT; -@Provider -public class AAIResourcesObjectMapperProvider extends AAICommonObjectMapperProvider { - - public AAIResourcesObjectMapperProvider() { - super(); - } - - @Override - public ObjectMapper getContext(Class<?> type) { - return mapper; - } + public boolean isFinished () { + switch (this) { + case COMPLETED: + case FAILED: + case TIMEOUT: + return true; + default: + return false; + } + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/UpdateInfraRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/UpdateInfraRequest.java new file mode 100644 index 0000000000..15c57253f3 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/requests/db/entities/UpdateInfraRequest.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.requests.db.entities;
+
+public class UpdateInfraRequest {
+
+ private String requestId;
+ private String lastModifiedBy;
+ private String statusMessage;
+ private String responseBody;
+ private RequestStatusType requestStatus;
+ private String progress;
+ private String vnfOutputs;
+ private String serviceInstanceId;
+ private String networkId;
+ private String vnfId;
+ private String vfModuleId;
+ private String volumeGroupId;
+ private String serviceInstanceName;
+ private String configurationId;
+ private String configurationName;
+ private String vfModuleName;
+
+ public String getRequestId() {
+ return requestId;
+ }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+ public String getLastModifiedBy() {
+ return lastModifiedBy;
+ }
+ public void setLastModifiedBy(String lastModifiedBy) {
+ this.lastModifiedBy = lastModifiedBy;
+ }
+ public String getStatusMessage() {
+ return statusMessage;
+ }
+ public void setStatusMessage(String statusMessage) {
+ this.statusMessage = statusMessage;
+ }
+ public String getResponseBody() {
+ return responseBody;
+ }
+ public void setResponseBody(String responseBody) {
+ this.responseBody = responseBody;
+ }
+ public RequestStatusType getRequestStatus() {
+ return requestStatus;
+ }
+ public void setRequestStatus(RequestStatusType requestStatus) {
+ this.requestStatus = requestStatus;
+ }
+ public String getProgress() {
+ return progress;
+ }
+ public void setProgress(String progress) {
+ this.progress = progress;
+ }
+ public String getVnfOutputs() {
+ return vnfOutputs;
+ }
+ public void setVnfOutputs(String vnfOutputs) {
+ this.vnfOutputs = vnfOutputs;
+ }
+ public String getServiceInstanceId() {
+ return serviceInstanceId;
+ }
+ public void setServiceInstanceId(String serviceInstanceId) {
+ this.serviceInstanceId = serviceInstanceId;
+ }
+ public String getNetworkId() {
+ return networkId;
+ }
+ public void setNetworkId(String networkId) {
+ this.networkId = networkId;
+ }
+ public String getVnfId() {
+ return vnfId;
+ }
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+ public String getVfModuleId() {
+ return vfModuleId;
+ }
+ public void setVfModuleId(String vfModuleId) {
+ this.vfModuleId = vfModuleId;
+ }
+ public String getVolumeGroupId() {
+ return volumeGroupId;
+ }
+ public void setVolumeGroupId(String volumeGroupId) {
+ this.volumeGroupId = volumeGroupId;
+ }
+ public String getServiceInstanceName() {
+ return serviceInstanceName;
+ }
+ public void setServiceInstanceName(String serviceInstanceName) {
+ this.serviceInstanceName = serviceInstanceName;
+ }
+ public String getConfigurationId() {
+ return configurationId;
+ }
+ public void setConfigurationId(String configurationId) {
+ this.configurationId = configurationId;
+ }
+ public String getConfigurationName() {
+ return configurationName;
+ }
+ public void setConfigurationName(String configurationName) {
+ this.configurationName = configurationName;
+ }
+ public String getVfModuleName() {
+ return vfModuleName;
+ }
+ public void setVfModuleName(String vfModuleName) {
+ this.vfModuleName = vfModuleName;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/AdapterRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/AdapterRestClient.java new file mode 100644 index 0000000000..3e315a5f04 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/AdapterRestClient.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.vnf; + +import java.net.URI; +import java.security.GeneralSecurityException; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.ext.ContextResolver; + +import org.apache.commons.codec.binary.Base64; +import org.openecomp.mso.bpmn.common.util.CryptoUtils; +import org.openecomp.mso.client.ResponseExceptionMapperImpl; +import org.openecomp.mso.client.policy.JettisonStyleMapperProvider; +import org.openecomp.mso.client.policy.RestClient; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class AdapterRestClient extends RestClient { + + private final AdapterRestProperties props; + public AdapterRestClient(AdapterRestProperties props, URI uri) { + super(props, UUID.randomUUID(), Optional.of(uri)); + this.props = props; + } + + public AdapterRestClient(AdapterRestProperties props, URI uri, String accept, String contentType) { + super(props, UUID.randomUUID(), Optional.of(uri), accept, contentType); + this.props = props; + } + + @Override + protected void initializeHeaderMap(Map<String, String> headerMap) { + headerMap.put("Authorization", + this.getBasicAuth(props.getAuth(), props.getKey())); + } + + @Override + protected Optional<ClientResponseFilter> addResponseFilter() { + return Optional.of(new ResponseExceptionMapperImpl()); + } + + @Override + public RestClient addRequestId(UUID requestId) { + return null; + } + + @Override + protected ContextResolver<ObjectMapper> getMapper() { + return new JettisonStyleMapperProvider(); + } + + private String getBasicAuth(String encryptedAuth, String msoKey) { + if ((encryptedAuth == null || encryptedAuth.isEmpty()) || (msoKey == null || msoKey.isEmpty())) { + return null; + } + try { + String auth = CryptoUtils.decrypt(encryptedAuth, msoKey); + byte[] encoded = Base64.encodeBase64(auth.getBytes()); + String encodedString = new String(encoded); + encodedString = "Basic " + encodedString; + return encodedString; + } catch (GeneralSecurityException e) { + this.logger.warn(e.getMessage(), e); + return null; + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/Consumer.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/AdapterRestProperties.java index 0e00ae5da8..af429db1f2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/Consumer.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/AdapterRestProperties.java @@ -18,9 +18,12 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.dmaap; +package org.openecomp.mso.client.adapter.vnf; -public interface Consumer { +import org.openecomp.mso.client.RestProperties; - public Iterable<String> fetch(); +public interface AdapterRestProperties extends RestProperties { + + public String getAuth(); + public String getKey(); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClient.java new file mode 100644 index 0000000000..5ee38fe0fb --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClient.java @@ -0,0 +1,48 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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.mso.client.adapter.vnf;
+
+import org.openecomp.mso.adapters.vnfrest.CreateVfModuleRequest;
+import org.openecomp.mso.adapters.vnfrest.CreateVfModuleResponse;
+import org.openecomp.mso.adapters.vnfrest.DeleteVfModuleRequest;
+import org.openecomp.mso.adapters.vnfrest.DeleteVfModuleResponse;
+import org.openecomp.mso.adapters.vnfrest.QueryVfModuleResponse;
+import org.openecomp.mso.adapters.vnfrest.RollbackVfModuleRequest;
+import org.openecomp.mso.adapters.vnfrest.RollbackVfModuleResponse;
+import org.openecomp.mso.adapters.vnfrest.UpdateVfModuleRequest;
+import org.openecomp.mso.adapters.vnfrest.UpdateVfModuleResponse;
+
+public interface VnfAdapterClient {
+
+ CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req);
+
+ RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, RollbackVfModuleRequest req);
+
+ DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req);
+
+ UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req);
+
+ QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId, String tenantId,
+ String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId);
+
+ String healthCheck();
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClientImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClientImpl.java new file mode 100644 index 0000000000..2b391d302d --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterClientImpl.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.adapter.vnf; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; + +import org.openecomp.mso.adapters.vnfrest.CreateVfModuleRequest; +import org.openecomp.mso.adapters.vnfrest.CreateVfModuleResponse; +import org.openecomp.mso.adapters.vnfrest.DeleteVfModuleRequest; +import org.openecomp.mso.adapters.vnfrest.DeleteVfModuleResponse; +import org.openecomp.mso.adapters.vnfrest.QueryVfModuleResponse; +import org.openecomp.mso.adapters.vnfrest.RollbackVfModuleRequest; +import org.openecomp.mso.adapters.vnfrest.RollbackVfModuleResponse; +import org.openecomp.mso.adapters.vnfrest.UpdateVfModuleRequest; +import org.openecomp.mso.adapters.vnfrest.UpdateVfModuleResponse; + +public class VnfAdapterClientImpl implements VnfAdapterClient { + + private static final String VF_MODULES = "/vf-modules/"; + + private final VnfAdapterRestProperties props; + public VnfAdapterClientImpl() { + this.props = new VnfAdapterRestProperties(); + } + + @Override + public CreateVfModuleResponse createVfModule(String aaiVnfId, CreateVfModuleRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + "/vf-modules").build()).post(req, + CreateVfModuleResponse.class); + } + + @Override + public RollbackVfModuleResponse rollbackVfModule(String aaiVnfId, String aaiVfModuleId, + RollbackVfModuleRequest req) { + return new AdapterRestClient(this.props, + this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId + "/rollback").build()).delete(req, + RollbackVfModuleResponse.class); + } + + @Override + public DeleteVfModuleResponse deleteVfModule(String aaiVnfId, String aaiVfModuleId, DeleteVfModuleRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build()) + .delete(req, DeleteVfModuleResponse.class); + } + + @Override + public UpdateVfModuleResponse updateVfModule(String aaiVnfId, String aaiVfModuleId, UpdateVfModuleRequest req) { + return new AdapterRestClient(this.props, this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId).build()) + .put(req, UpdateVfModuleResponse.class); + } + + @Override + public QueryVfModuleResponse queryVfModule(String aaiVnfId, String aaiVfModuleId, String cloudSiteId, + String tenantId, String vfModuleName, boolean skipAAI, String requestId, String serviceInstanceId) { + UriBuilder builder = this.getUri("/" + aaiVnfId + VF_MODULES + aaiVfModuleId); + if (cloudSiteId != null) { + builder.queryParam("cloudSiteId", cloudSiteId); + } + if (tenantId != null) { + builder.queryParam("tenantId", tenantId); + } + if (vfModuleName != null) { + builder.queryParam("vfModuleName", vfModuleName); + } + + builder.queryParam("skipAAI", skipAAI); + + if (requestId != null) { + builder.queryParam("msoRequest.requestId", requestId); + } + if (serviceInstanceId != null) { + builder.queryParam("msoRequest.serviceInstanceId", serviceInstanceId); + } + return new AdapterRestClient(this.props, builder.build(), MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON) + .get(QueryVfModuleResponse.class); + } + + @Override + public String healthCheck() { + return new AdapterRestClient(this.props, this.getUri("/healthcheck").build()).get(String.class); + } + + public UriBuilder getUri(String path) { + return UriBuilder.fromPath(path); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIUpdatorImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterRestProperties.java index 575a65fa0f..e342aeedac 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIUpdatorImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/adapter/vnf/VnfAdapterRestProperties.java @@ -18,32 +18,39 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai; +package org.openecomp.mso.client.adapter.vnf; -import org.springframework.beans.factory.annotation.Autowired; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; -public class AAIUpdatorImpl implements AAIUpdator { +import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.client.adapter.vnf.AdapterRestProperties; + +public class VnfAdapterRestProperties implements AdapterRestProperties { + + private final Map<String, String> props; - @Autowired - protected AAIRestClient client; + public VnfAdapterRestProperties() { + this.props = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); + } - public AAIRestClient getClient() { - return client; + @Override + public String getAuth() { + return props.get("mso.adapters.po.auth"); } - - - public void setClient(AAIRestClient client) { - this.client = client; + @Override + public String getKey() { + return props.get("mso.msoKey"); } - @Override - public void updateVnfToLocked(String vnfId, String uuid) throws Exception { - client.updateMaintenceFlagVnfId(vnfId, true, uuid); + public URL getEndpoint() throws MalformedURLException { + return new URL(props.get("mso.adapters.vnf.rest.endpoint")); } @Override - public void updateVnfToUnLocked(String vnfId, String uuid) throws Exception { - client.updateMaintenceFlagVnfId(vnfId, false, uuid); + public String getSystemName() { + return "MSO"; } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerAction.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerAction.java new file mode 100644 index 0000000000..8b870889ac --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerAction.java @@ -0,0 +1,178 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.appc;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.openecomp.mso.client.appc.ApplicationControllerSupport.StatusCategory;
+import org.openecomp.mso.bpmn.appc.payload.PayloadClient;
+import org.openecomp.mso.bpmn.core.json.JsonUtils;
+import org.openecomp.mso.client.appc.ApplicationControllerOrchestrator;
+import java.util.Optional;
+import org.onap.appc.client.lcm.model.Action;
+import org.onap.appc.client.lcm.model.Status;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import com.att.eelf.configuration.EELFLogger.Level;
+import java.lang.NoSuchMethodError;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+public class ApplicationControllerAction {
+ protected ApplicationControllerOrchestrator client = new ApplicationControllerOrchestrator();
+ private String errorCode = "1002";
+ private String errorMessage = "Unable to reach App C Servers";
+ protected final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
+
+ public void runAppCCommand(Action action, String msoRequestId, String vnfId, Optional<String> payload, HashMap<String, String> payloadInfo){
+ Status appCStatus = null;
+ try{
+ String vnfName = payloadInfo.getOrDefault("vnfName", "");
+ String aicIdentity = payloadInfo.getOrDefault("vnfName","");
+ String vnfHostIpAddress = payloadInfo.getOrDefault("vnfHostIpAddress","");
+ String vmIdList = payloadInfo.getOrDefault("vmIdList", "");
+ String identityUrl = payloadInfo.getOrDefault("identityUrl", "");
+ switch(action){
+ case ResumeTraffic:
+ appCStatus = resumeTrafficAction(msoRequestId, vnfId, vnfName);
+ break;
+ case Start:
+ case Stop:
+ appCStatus = startStopAction(action, msoRequestId, vnfId, aicIdentity);
+ break;
+ case Unlock:
+ case Lock:
+ appCStatus = client.vnfCommand(action, msoRequestId, vnfId, Optional.empty());
+ break;
+ case QuiesceTraffic:
+ appCStatus = quiesceTrafficAction(msoRequestId, vnfId, payload, vnfName);
+ break;
+ case HealthCheck:
+ appCStatus = healthCheckAction(msoRequestId, vnfId, vnfName, vnfHostIpAddress);
+ break;
+ case Snapshot:
+ String vmIds = JsonUtils.getJsonValue(vmIdList, "vmIds");
+ String vmId = "";
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> vmIdJsonList = mapper.readValue(vmIds, new TypeReference<List<String>>(){});
+ int i = 0;
+ while(i < vmIdJsonList.size()){
+ vmId = vmIdJsonList.get(i);
+ appCStatus = snapshotAction(msoRequestId, vnfId, vmId, identityUrl);
+ i++;
+ }
+ break;
+ case ConfigModify:
+ appCStatus = payloadAction(action, msoRequestId, vnfId, payload);
+ break;
+ case UpgradePreCheck:
+ case UpgradePostCheck:
+ case UpgradeSoftware:
+ case UpgradeBackup:
+ appCStatus = upgradeAction(action,msoRequestId, vnfId, payload, vnfName);
+ break;
+ default:
+ errorMessage = "Unable to idenify Action request for AppCClient";
+ break;
+ }
+ if(appCStatus != null){
+ errorCode = Integer.toString(appCStatus.getCode());
+ errorMessage = appCStatus.getMessage();
+
+ }
+ if(ApplicationControllerSupport.getCategoryOf(appCStatus).equals(StatusCategory.NORMAL)){
+ errorCode = "0";
+ }
+ }
+ catch(JsonProcessingException e){
+ auditLogger.log(Level.ERROR, "Incorrect Payload format for action request" + action.toString(),e, e.getMessage());
+ errorMessage = e.getMessage();
+ }
+ catch(ApplicationControllerOrchestratorException e){
+ auditLogger.log(Level.ERROR, "Error building Appc request: ", e, e.getMessage());
+ errorCode = "1002";
+ errorMessage = e.getMessage();
+ }
+ catch (NoSuchMethodError e) {
+ auditLogger.log(Level.ERROR, "Error building Appc request: ", e, e.getMessage());
+ errorMessage = e.getMessage();
+ }
+ catch(Exception e){
+ auditLogger.log(Level.ERROR, "Error building Appc request: ", e, e.getMessage());
+ errorMessage = e.getMessage();
+ }
+ }
+
+ private Status payloadAction(Action action, String msoRequestId, String vnfId, Optional<String> payload) throws JsonProcessingException, Exception{
+ if(!(payload.isPresent())){
+ throw new IllegalArgumentException("Payload is not present for " + action.toString());
+ }
+ return client.vnfCommand(action, msoRequestId, vnfId, payload);
+ }
+
+ private Status quiesceTrafficAction(String msoRequestId, String vnfId, Optional<String> payload, String vnfName) throws JsonProcessingException, Exception{
+ if(!(payload.isPresent())){
+ throw new IllegalArgumentException("Payload is not present for " + Action.QuiesceTraffic.toString());
+ }
+ payload = PayloadClient.quiesceTrafficFormat(payload, vnfName);
+ return client.vnfCommand(Action.QuiesceTraffic, msoRequestId, vnfId, payload);
+ }
+
+ private Status upgradeAction(Action action, String msoRequestId, String vnfId, Optional<String> payload, String vnfName) throws JsonProcessingException, Exception{
+ if(!(payload.isPresent())){
+ throw new IllegalArgumentException("Payload is not present for " + action.toString());
+ }
+ payload = PayloadClient.upgradeFormat(payload, vnfName);
+ return client.vnfCommand(action, msoRequestId, vnfId, payload);
+ }
+
+ private Status resumeTrafficAction(String msoRequestId, String vnfId, String vnfName)throws JsonProcessingException, Exception{
+ Optional<String> payload = PayloadClient.resumeTrafficFormat(vnfName);
+ return client.vnfCommand(Action.ResumeTraffic, msoRequestId, vnfId, payload);
+ }
+
+ private Status startStopAction(Action action, String msoRequestId, String vnfId, String aicIdentity)throws JsonProcessingException, Exception{
+ Optional<String> payload = PayloadClient.startStopFormat(aicIdentity);
+ return client.vnfCommand(action, msoRequestId, vnfId, payload);
+ }
+
+ private Status healthCheckAction(String msoRequestId, String vnfId, String vnfName, String vnfHostIpAddress)throws JsonProcessingException, Exception{
+ Optional<String> payload = PayloadClient.healthCheckFormat(vnfName, vnfHostIpAddress);
+ return client.vnfCommand(Action.HealthCheck, msoRequestId, vnfId, payload);
+ }
+
+ private Status snapshotAction(String msoRequestId, String vnfId, String vmId, String identityUrl) throws JsonProcessingException, Exception{
+ Optional<String> payload = PayloadClient.snapshotFormat(vmId, identityUrl);
+ return client.vnfCommand(Action.Snapshot, msoRequestId, vnfId, payload);
+ }
+
+ public String getErrorMessage(){
+ return errorMessage;
+ }
+
+ public String getErrorCode(){
+ return errorCode;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerCallback.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerCallback.java index c84e5903c5..1bb4dc7eed 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerCallback.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerCallback.java @@ -19,8 +19,9 @@ */ package org.openecomp.mso.client.appc; -import org.openecomp.appc.client.lcm.api.ResponseHandler; -import org.openecomp.appc.client.lcm.exceptions.AppcClientException; + +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.exceptions.AppcClientException; public class ApplicationControllerCallback<T> implements ResponseHandler<T> { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java index f66034f5e9..c383408488 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java @@ -20,88 +20,79 @@ package org.openecomp.mso.client.appc; -import java.beans.BeanInfo; - -import java.util.Map; - -import org.openecomp.mso.bpmn.core.PropertyConfiguration; - -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.time.Instant; +import java.util.Map; import java.util.Properties; import java.util.UUID; +import org.openecomp.mso.bpmn.core.PropertyConfiguration; import org.springframework.beans.factory.annotation.Autowired; -import org.openecomp.appc.client.lcm.api.AppcClientServiceFactoryProvider; -import org.openecomp.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; -import org.openecomp.appc.client.lcm.api.ApplicationContext; -import org.openecomp.appc.client.lcm.api.LifeCycleManagerStateful; -import org.openecomp.appc.client.lcm.api.ResponseHandler; -import org.openecomp.appc.client.lcm.exceptions.AppcClientException; -import org.openecomp.appc.client.lcm.model.Action; -import org.openecomp.appc.client.lcm.model.ActionIdentifiers; -import org.openecomp.appc.client.lcm.model.AuditOutput; -import org.openecomp.appc.client.lcm.model.CommonHeader; -import org.openecomp.appc.client.lcm.model.Flags; -import org.openecomp.appc.client.lcm.model.Flags.Force; -import org.openecomp.appc.client.lcm.model.Flags.Mode; -import org.openecomp.appc.client.lcm.model.Payload; -import org.openecomp.appc.client.lcm.model.Status; -import org.openecomp.appc.client.lcm.model.ZULU; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import org.openecomp.mso.logger.MsoLogger; +import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider; +import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; +import org.onap.appc.client.lcm.api.ApplicationContext; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.exceptions.AppcClientException; +import org.onap.appc.client.lcm.model.Action; +import org.onap.appc.client.lcm.model.ActionIdentifiers; +import org.onap.appc.client.lcm.model.CommonHeader; +import org.onap.appc.client.lcm.model.Flags; +import org.onap.appc.client.lcm.model.Flags.Force; +import org.onap.appc.client.lcm.model.Flags.Mode; +import org.onap.appc.client.lcm.model.Payload; +import org.onap.appc.client.lcm.model.Status; +import org.onap.appc.client.lcm.model.ZULU; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; public class ApplicationControllerClient { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - private static final int PARTIAL_SERIES = 500; + private static final String CLIENT_NAME = "MSO"; - private final String apiVer = "2.00"; - private final String originatorId = "MSO"; - private final int flagsTTL = 65000; - private final static String clientName = "MSO"; + private static final String API_VER = "2.00"; + private static final String ORIGINATOR_ID = "MSO"; + private static final int FLAGS_TTL = 65000; + protected final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); @Autowired public ApplicationControllerSupport appCSupport; - private LifeCycleManagerStateful client; + private static LifeCycleManagerStateful client; - public Status runCommand(Action action, ActionIdentifiers identifier, Flags flags, Payload payload, - String requestID) throws IllegalAccessException,NoSuchMethodException,AppcClientException,JsonProcessingException,InvocationTargetException { - Object requestObject = createRequest(action, identifier, flags, payload, requestID); - client = getAppCClient(); - Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false); - appCSupport.logLCMMessage(requestObject); - Object response = lcmMethod.invoke(client, requestObject); - return appCSupport.getStatusFromGenericResponse(response); + public ApplicationControllerClient() { + appCSupport = new ApplicationControllerSupport(); + client = this.getAppCClient(); } - public void shutdownclient() { - AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class) - .shutdownLifeCycleManager(false); + public Status runCommand(Action action, org.onap.appc.client.lcm.model.ActionIdentifiers actionIdentifiers, org.onap.appc.client.lcm.model.Payload payload, String requestID) + throws ApplicationControllerOrchestratorException { + Object requestObject; + requestObject = createRequest(action, actionIdentifiers, payload, requestID); + appCSupport.logLCMMessage(requestObject); + Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false); + try { + Object response = lcmMethod.invoke(client, requestObject); + return appCSupport.getStatusFromGenericResponse(response); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e); + } } - public LifeCycleManagerStateful getAppCClient() throws AppcClientException { + public LifeCycleManagerStateful getAppCClient() { if (client == null) - client = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class) - .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties()); + try { + client = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class) + .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties()); + } catch (AppcClientException e) { + auditLogger.log(Level.ERROR, "Error in getting LifeCycleManagerStateful: ", e, e.getMessage()); + } return client; } - private Properties getLCMProperties() { - return getLCMPropertiesHelper(); - } - - protected Properties getLCMPropertiesHelper() { + protected Properties getLCMProperties() { Properties properties = new Properties(); Map<String, String> globalProperties = PropertyConfiguration.getInstance() .getProperties("mso.bpmn.urn.properties"); @@ -110,44 +101,46 @@ public class ApplicationControllerClient { properties.put("topic.read.timeout", globalProperties.get("appc.topic.read.timeout")); properties.put("client.response.timeout", globalProperties.get("appc.client.response.timeout")); properties.put("topic.write", globalProperties.get("appc.topic.write")); - properties.put("poolMembers", globalProperties.get("appc.pool.members")); + properties.put("poolMembers", globalProperties.get("appc.poolMembers")); properties.put("client.key", globalProperties.get("appc.client.key")); properties.put("client.secret", globalProperties.get("appc.client.secret")); - properties.put("client.name", clientName); + properties.put("client.name", CLIENT_NAME); + properties.put("service", globalProperties.get("appc.service")); return properties; } - public Object createRequest(Action action, ActionIdentifiers identifier, Flags flags, Payload payload, - String requestId) throws IllegalAccessException,NoSuchMethodException,InvocationTargetException { + public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId) { Object requestObject = appCSupport.getInput(action.name()); try { - org.openecomp.appc.client.lcm.model.CommonHeader commonHeader = buildCommonHeader(requestId); + CommonHeader commonHeader = buildCommonHeader(requestId); requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject, commonHeader); requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action); requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class) .invoke(requestObject, identifier); + if (payload != null) { + requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload); + } } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { - LOGGER.debug("Exception:", e); - throw new IllegalAccessException("Error Building AppC Request: " + e.getMessage()); + auditLogger.log(Level.ERROR, "Error building Appc request: ", e, e.getMessage()); } return requestObject; } - private org.openecomp.appc.client.lcm.model.CommonHeader buildCommonHeader(String requestId) { - org.openecomp.appc.client.lcm.model.CommonHeader commonHeader = new org.openecomp.appc.client.lcm.model.CommonHeader(); - commonHeader.setApiVer(apiVer); - commonHeader.setOriginatorId(originatorId); + private CommonHeader buildCommonHeader(String requestId) { + CommonHeader commonHeader = new CommonHeader(); + commonHeader.setApiVer(API_VER); + commonHeader.setOriginatorId(ORIGINATOR_ID); commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId); commonHeader.setSubRequestId(requestId); - org.openecomp.appc.client.lcm.model.Flags flags = new org.openecomp.appc.client.lcm.model.Flags(); + Flags flags = new Flags(); String flagsMode = "NORMAL"; Mode mode = Mode.valueOf(flagsMode); flags.setMode(mode); String flagsForce = "FALSE"; Force force = Force.valueOf(flagsForce); flags.setForce(force); - flags.setTtl(flagsTTL); + flags.setTtl(FLAGS_TTL); commonHeader.setFlags(flags); Instant timestamp = Instant.now(); ZULU zulu = new ZULU(timestamp.toString()); diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerOrchestrator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerOrchestrator.java new file mode 100644 index 0000000000..217525e56a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerOrchestrator.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.appc; + +import java.util.Optional; + +import org.openecomp.mso.client.appc.ApplicationControllerSupport.StatusCategory; + +import org.onap.appc.client.lcm.model.Action; +import org.onap.appc.client.lcm.model.ActionIdentifiers; +import org.onap.appc.client.lcm.model.Payload; +import org.onap.appc.client.lcm.model.Status; + +public class ApplicationControllerOrchestrator { + + public Status vnfCommand(Action action, String requestId, String vnfId, Optional<String> request) throws ApplicationControllerOrchestratorException { + ApplicationControllerClient client = new ApplicationControllerClient(); + Status status; + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setVnfId(vnfId); + Payload payload = null; + if (request.isPresent()) { + payload = new Payload(request.get()); + } + status = client.runCommand(action, actionIdentifiers, payload, requestId); + if (ApplicationControllerSupport.getCategoryOf(status).equals(StatusCategory.ERROR)) { + throw new ApplicationControllerOrchestratorException(status.getMessage(), status.getCode()); + } else { + return status; + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/exceptions/DMaaPConsumerFailure.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerOrchestratorException.java index 29472b2180..4692f1dcc2 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/exceptions/DMaaPConsumerFailure.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerOrchestratorException.java @@ -18,17 +18,19 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.dmaap.exceptions; - -public class DMaaPConsumerFailure extends Exception { - - private static final long serialVersionUID = 2499229901897110362L; - - public DMaaPConsumerFailure() { - super(); - } - - public DMaaPConsumerFailure(String message) { - super(message); - } -} +package org.openecomp.mso.client.appc;
+
+public class ApplicationControllerOrchestratorException extends Exception {
+
+ private final int appcCode;
+
+ public ApplicationControllerOrchestratorException(String message, int code) {
+ super(message);
+ appcCode = code;
+ }
+
+ public int getAppcCode()
+ {
+ return appcCode;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerSupport.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerSupport.java index f7db52b1c0..e3ed432dfc 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerSupport.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerSupport.java @@ -20,35 +20,26 @@ package org.openecomp.mso.client.appc; - import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; -import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.Properties; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.stereotype.Component; -import org.openecomp.appc.client.lcm.api.AppcClientServiceFactoryProvider; -import org.openecomp.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory; -import org.openecomp.appc.client.lcm.api.ApplicationContext; -import org.openecomp.appc.client.lcm.api.LifeCycleManagerStateful; -import org.openecomp.appc.client.lcm.api.ResponseHandler; -import org.openecomp.appc.client.lcm.exceptions.AppcClientException; -import org.openecomp.appc.client.lcm.model.Status; +import org.onap.appc.client.lcm.api.LifeCycleManagerStateful; +import org.onap.appc.client.lcm.api.ResponseHandler; +import org.onap.appc.client.lcm.model.Status; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.configuration.EELFLogger.Level; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; - @Component public class ApplicationControllerSupport { @@ -61,14 +52,8 @@ public class ApplicationControllerSupport { private static final int PARTIAL_SUCCESS_STATUS = PARTIAL_SERIES; private static final int PARTIAL_FAILURE_STATUS = PARTIAL_SERIES + 1; - @Value("${lcm.model.package:org.openecomp.appc.client.lcm.model}") - private String lcmModelPackage; - - public LifeCycleManagerStateful createService() throws AppcClientException, IOException { - AppcLifeCycleManagerServiceFactory factory = AppcClientServiceFactoryProvider - .getFactory(AppcLifeCycleManagerServiceFactory.class); - return factory.createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties()); - } + protected final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); + private String lcmModelPackage = "org.onap.appc.client.lcm.model"; /** * @param action @@ -114,26 +99,18 @@ public class ApplicationControllerSupport { "Unable to derive viable LCM Kit API method for action", action, async)); } - public Method getCommonHeaderSetterMethod(String action) { - return getBeanPropertyMethodFor(getInputClass(action), "commonHeader", true); - } - - public Method getPayloadSetterMethod(String action) { - return getBeanPropertyMethodFor(getInputClass(action), "payload", true); - } - public Status getStatusFromGenericResponse(Object response) { Method statusReader = getBeanPropertyMethodFor(response.getClass(), "status", false); if (statusReader != null) { try { return (Status) statusReader.invoke(response); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException("Unable to obtain status from LCM Kit response", e); + auditLogger.log(Level.ERROR, "Unable to obtain status from LCM Kit response", e, e.getMessage()); } } return new Status(); } - + public static StatusCategory getCategoryOf(Status status) { int codeSeries = status.getCode() - (status.getCode() % 100); switch (codeSeries) { @@ -157,7 +134,7 @@ public class ApplicationControllerSupport { return StatusCategory.WARNING; } } - + public static boolean getFinalityOf(Status status) { int codeSeries = status.getCode() - (status.getCode() % 100); switch (codeSeries) { @@ -173,16 +150,6 @@ public class ApplicationControllerSupport { } } - /** - * @return - * @throws IOException - */ - private Properties getLCMProperties() throws IOException { - Resource resource = new ClassPathResource("/lcm.properties"); - Properties properties = PropertiesLoaderUtils.loadProperties(resource); - return properties; - } - private Method getBeanPropertyMethodFor(Class<?> clazz, String propertyName, boolean isWriter) { BeanInfo beanInfo; try { @@ -213,34 +180,36 @@ public class ApplicationControllerSupport { try { return Class.forName(lcmModelPackage + '.' + action + "Input"); } catch (ClassNotFoundException e) { - throw new RuntimeException(String.format("%s : %s using package : ", + throw new RuntimeException(String.format("%s : %s using package : %s", "Unable to identify viable LCM Kit input class for action", action, lcmModelPackage), e); } } - - public static enum StatusCategory { - NORMAL("normal"), - WARNING("warning"), - ERROR("error"); - - private final String category; - - private StatusCategory(final String category) { - this.category = category; - } - - @Override - public String toString() { - return category; - } + + public enum StatusCategory { + NORMAL("normal"), WARNING("warning"), ERROR("error"); + + private final String category; + + private StatusCategory(final String category) { + this.category = category; + } + + @Override + public String toString() { + return category; + } } - - public void logLCMMessage(Object message) throws JsonProcessingException { + + public void logLCMMessage(Object message) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(Include.NON_NULL); ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter(); - String inputAsJSON = writer.writeValueAsString(message); - System.out.println("LCM Kit input message follows."); - System.out.println(inputAsJSON); + String inputAsJSON; + try { + inputAsJSON = writer.writeValueAsString(message); + auditLogger.log(Level.INFO, "\nLCM Kit input message follows: \n" + inputAsJSON, null); + } catch (JsonProcessingException e) { + auditLogger.log(Level.ERROR, "Error in logging LCM Message: ", e, e.getMessage()); + } } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapClient.java deleted file mode 100644 index 7862c9d41d..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapClient.java +++ /dev/null @@ -1,68 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Base64; -import java.util.Map; -import java.util.Properties; - -import org.openecomp.mso.bpmn.core.PropertyConfiguration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public abstract class DmaapClient { - - protected final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger(); - protected final Map<String, String> msoProperties; - protected final Properties properties; - public DmaapClient(String filepath) throws FileNotFoundException, IOException { - Resource resource = new ClassPathResource(filepath); - DmaapProperties dmaapProperties = DmaapPropertiesLoader.getInstance().getImpl(); - if (dmaapProperties == null) { - dmaapProperties = new DefaultDmaapPropertiesImpl(); - } - this.msoProperties = dmaapProperties.getProperties(); - this.properties = new Properties(); - this.properties.load(resource.getInputStream()); - this.properties.put("password", this.deobfuscatePassword(this.getPassword())); - this.properties.put("username", this.getUserName()); - this.properties.put("topic", this.getTopic()); - } - protected String deobfuscatePassword(String password) { - - try { - return new String(Base64.getDecoder().decode(password.getBytes())); - } catch(IllegalArgumentException iae) { - - return password; - } - } - - - public abstract String getUserName(); - public abstract String getPassword(); - public abstract String getTopic(); -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapConsumer.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapConsumer.java deleted file mode 100644 index 033951612d..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapConsumer.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import org.openecomp.mso.client.dmaap.exceptions.DMaaPConsumerFailure; -import org.openecomp.mso.client.dmaap.exceptions.ExceededMaximumPollingTime; -import org.openecomp.mso.client.dmaap.rest.RestConsumer; - -import com.google.common.base.Stopwatch; - -public abstract class DmaapConsumer extends DmaapClient { - - public DmaapConsumer() throws FileNotFoundException, IOException { - super("dmaap/default-consumer.properties"); - } - - public Consumer getConsumer() throws FileNotFoundException, IOException { - return new RestConsumer(this.properties); - } - public boolean consume() throws Exception { - - Consumer mrConsumer = this.getConsumer(); - int iterations = 0; - boolean accepted = false; - Stopwatch stopwatch = Stopwatch.createUnstarted(); - try { - while (this.continuePolling()) { - if (stopwatch.elapsed(TimeUnit.MILLISECONDS) >= this.getMaximumElapsedTime()) { - final String message = "exceeded maximum retries on " + this.getRequestId() + " on " + this.getTopic(); - auditLogger.error(message); - throw new ExceededMaximumPollingTime(message); - } - stopwatch.start(); - Iterable<String> itr = mrConsumer.fetch(); - stopwatch.stop(); - for (String message : itr) { - if (!accepted && this.isAccepted(message)) { - auditLogger.info("accepted message found for " + this.getRequestId() + " on " + this.getTopic()); - accepted = true; - } - if (accepted) { - if (this.isFailure(message)) { - this.stopProcessingMessages(); - auditLogger.info("received dmaap message: " + message); - final String errorMsg = "failure received from dmaap topic " + this.getTopic(); - auditLogger.error(errorMsg); - throw new DMaaPConsumerFailure(errorMsg); - } else { - auditLogger.info("received dmaap message: " + message); - this.processMessage(message); - } - } - } - iterations++; - } - return true; - } catch (Exception e ) { - throw e; - } finally { - if (stopwatch.isRunning()) { - stopwatch.stop(); - } - } - } - - /** - * Should this consumer continue to consume messages from the topic? - * @return - */ - public abstract boolean continuePolling(); - /** - * Process a message from a DMaaP topic - * - * @param message - * @throws Exception - */ - public abstract void processMessage(String message) throws Exception; - /** - * Has the request been accepted by the receiving system? - * Should the consumer move to processing messages? - * - * @param message - * @return - */ - public abstract boolean isAccepted(String message); - /** - * has the request failed? - * - * @param message - * @return - */ - public abstract boolean isFailure(String message); - /** - * The request id to filter messages on - * @return - */ - public abstract String getRequestId(); - /** - * Logic that defines when the consumer should stop processing messages - */ - public abstract void stopProcessingMessages(); - - /** - * time in milliseconds - */ - public int getMaximumElapsedTime() { - return 180000; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPropertiesLoader.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPropertiesLoader.java deleted file mode 100644 index 1bdecbf2a7..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPropertiesLoader.java +++ /dev/null @@ -1,48 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap; - -import java.util.Iterator; -import java.util.ServiceLoader; - -public class DmaapPropertiesLoader { - - private final ServiceLoader<DmaapProperties> services; - private DmaapPropertiesLoader() { - services = ServiceLoader.load(DmaapProperties.class); - } - - private static class Helper { - private static final DmaapPropertiesLoader INSTANCE = new DmaapPropertiesLoader(); - } - - public static DmaapPropertiesLoader getInstance() { - return Helper.INSTANCE; - } - - public DmaapProperties getImpl() { - for (DmaapProperties service : services) { - return service; - } - - return null; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPublisher.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPublisher.java deleted file mode 100644 index d2752c531b..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DmaapPublisher.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.openecomp.mso.client.dmaap.rest.RestPublisher; - -public abstract class DmaapPublisher extends DmaapClient { - - private long seconds; - private final Publisher publisher; - public DmaapPublisher() throws FileNotFoundException, IOException { - super("dmaap/default-consumer.properties"); - this.publisher = new RestPublisher(properties); - this.seconds = 20; - - } - - public DmaapPublisher(long seconds) throws FileNotFoundException, IOException { - this(); - this.seconds = seconds; - } - - public void send(String json) throws IOException, InterruptedException { - auditLogger.info("publishing message to dmaap topic " + this.getTopic() + ": " + json); - publisher.send(json); - //publisher.close(seconds, TimeUnit.SECONDS); - } - - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/Publisher.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/Publisher.java deleted file mode 100644 index d89ee6e5c6..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/Publisher.java +++ /dev/null @@ -1,26 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap; - -public interface Publisher { - - public void send(String json); -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/DMaaPRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/DMaaPRestClient.java deleted file mode 100644 index f54eba406e..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/DMaaPRestClient.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap.rest; - -import java.net.URL; -import java.util.Base64; -import java.util.Map; -import java.util.Optional; - -import javax.ws.rs.client.ClientResponseFilter; - -import org.openecomp.mso.client.ResponseExceptionMapperImpl; -import org.openecomp.mso.client.policy.RestClient; - -public class DMaaPRestClient extends RestClient { - - private final String username; - private final String password; - public DMaaPRestClient(URL url, String contentType, String username, String password) { - super(url, contentType); - this.username = username; - this.password = password; - } - - @Override - protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes())); - } - - @Override - protected Optional<ClientResponseFilter> addResponseFilter() { - return Optional.of(new ResponseExceptionMapperImpl()); - } - - @Override - public RestClient addRequestId(String requestId) { - return null; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/PropertiesBean.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/PropertiesBean.java deleted file mode 100644 index fb914a0c13..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/PropertiesBean.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap.rest; - -import java.util.Properties; - -public class PropertiesBean { - - private String username; - private String password; - private String environment; - private String partition; - private String contentType; - private String host; - private String topic; - private String timeout; - - - public PropertiesBean(Properties properties) { - this.withUsername(properties.getProperty("username")) - .withPassword(properties.getProperty("password")) - .withTopic(properties.getProperty("topic")) - .withEnvironment(properties.getProperty("environment")) - .withHost(properties.getProperty("host")) - .withTimeout(properties.getProperty("timeout", "20000")) - .withPartition(properties.getProperty("partition")) - .withContentType(properties.getProperty("contentType", "application/json")); - } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public PropertiesBean withUsername(String username) { - this.username = username; - return this; - } - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - public PropertiesBean withPassword(String password) { - this.password = password; - return this; - } - public String getEnvironment() { - return environment; - } - public void setEnvironment(String environment) { - this.environment = environment; - } - public PropertiesBean withEnvironment(String environment) { - this.environment = environment; - return this; - } - public String getPartition() { - return partition; - } - public void setPartition(String partition) { - this.partition = partition; - } - public PropertiesBean withPartition(String partition) { - this.partition = partition; - return this; - } - public String getContentType() { - return contentType; - } - public void setContentType(String contentType) { - this.contentType = contentType; - } - public PropertiesBean withContentType(String contentType) { - this.contentType = contentType; - return this; - } - public String getHost() { - return host; - } - public void setHost(String host) { - this.host = host; - } - public PropertiesBean withHost(String host) { - this.host = host; - return this; - } - public String getTopic() { - return topic; - } - public void setTopic(String topic) { - this.topic = topic; - } - public PropertiesBean withTopic(String topic) { - this.topic = topic; - return this; - } - public String getTimeout() { - return timeout; - } - public void setTimeout(String timeout) { - this.timeout = timeout; - } - public PropertiesBean withTimeout(String timeout) { - this.timeout = timeout; - return this; - } - - - - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestConsumer.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestConsumer.java deleted file mode 100644 index ff199e2373..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestConsumer.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap.rest; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Properties; - -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.UriBuilder; - -import org.openecomp.mso.client.dmaap.Consumer; -import org.openecomp.mso.client.policy.RestClient; - -public class RestConsumer implements Consumer { - - private final RestClient client; - public RestConsumer(Properties properties) { - PropertiesBean bean = new PropertiesBean(properties); - client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getUsername(), bean.getPassword()); - } - - private URL createURL(PropertiesBean properties) { - try { - return UriBuilder.fromUri("http://" + properties.getHost()) - .path("events").path(properties.getTopic()) - .path(properties.getPartition()) - .path("consumer1") - .queryParam("timeout", properties.getTimeout()).build().toURL(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - @Override - public Iterable<String> fetch() { - - return client.get(new GenericType<List<String>>() {}); - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestPublisher.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestPublisher.java deleted file mode 100644 index e8e685932a..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/rest/RestPublisher.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.dmaap.rest; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Properties; - -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriBuilderException; - -import org.openecomp.mso.client.dmaap.Publisher; -import org.openecomp.mso.client.policy.RestClient; - -public class RestPublisher implements Publisher { - - private final RestClient client; - - public RestPublisher(Properties properties) { - PropertiesBean bean = new PropertiesBean(properties); - client = new DMaaPRestClient(this.createURL(bean), bean.getContentType(), bean.getUsername(), bean.getPassword()); - } - - private URL createURL(PropertiesBean properties) { - try { - return UriBuilder.fromUri("http://" + properties.getHost()) - .path("events").path(properties.getTopic()) - .queryParam("timeout", properties.getTimeout()).build().toURL(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - @Override - public void send(String json) { - client.post(json); - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DefaultDmaapPropertiesImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaaproperties/DefaultDmaapPropertiesImpl.java index 9af1fd3f7e..c3bf53cfde 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaap/DefaultDmaapPropertiesImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/dmaaproperties/DefaultDmaapPropertiesImpl.java @@ -17,12 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - -package org.openecomp.mso.client.dmaap; + +package org.openecomp.mso.client.dmaaproperties; import java.util.Map; import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.client.dmaap.DmaapProperties; public class DefaultDmaapPropertiesImpl implements DmaapProperties { diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/AAIOrchestrator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/AAIOrchestrator.java new file mode 100644 index 0000000000..73bad21c87 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/AAIOrchestrator.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.orchestration; + +import java.util.Optional; +import java.util.logging.Logger; + +import org.modelmapper.ModelMapper; +import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition; +import org.openecomp.mso.client.aai.AAIResourcesClient; +import org.openecomp.mso.client.aai.entities.AAIEntityObject; +import org.openecomp.mso.client.aai.objects.AAIOwningEntity; +import org.openecomp.mso.client.aai.objects.AAIProject; +import org.openecomp.mso.client.aai.objects.AAIServiceInstance; + +public class AAIOrchestrator { + + private static Logger LOGGER = Logger.getLogger("AAIOrchestrator"); + + public void createServiceInstance(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject serviceInstance = modelMapper.map(serviceDecomp.getServiceInstance(), AAIServiceInstance.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.createIfNotExists(serviceInstance.getUri(), Optional.of(serviceInstance)); + }catch(Exception ex) { + String msg = "Failed to create service instance in A&AI."; + throw new IllegalStateException(msg); + } + } + + public void deleteServiceInstance(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject serviceInstance = modelMapper.map(serviceDecomp.getServiceInstance(), AAIServiceInstance.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.delete(serviceInstance.getUri()); + } catch (Exception ex) { + String msg = "Failed to delete service instance in A&AI."; + throw new IllegalStateException(msg); + } + } + + public void createProject(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject project = modelMapper.map(serviceDecomp.getProject(), AAIProject.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.createIfNotExists(project.getUri(), Optional.of(project)); + }catch(Exception ex) { + String msg = "Failed to create project in A&AI."; + throw new IllegalStateException(msg); } + } + + public void createProjectandConnectServiceInstance(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject project = modelMapper.map(serviceDecomp.getProject(), AAIProject.class); + AAIEntityObject serviceInstance = modelMapper.map(serviceDecomp.getServiceInstance(), AAIServiceInstance.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.createIfNotExists(project.getUri(), Optional.of(project)).connect(project.getUri(), serviceInstance.getUri()); + } catch(Exception ex) { + String msg = "Failed to create project and connect service instance in A&AI."; + throw new IllegalStateException(msg); + } + } + + public void createOwningEntity(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject owningEntity = modelMapper.map(serviceDecomp.getOwningEntity(), AAIOwningEntity.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.createIfNotExists(owningEntity.getUri(), Optional.of(owningEntity)); + }catch(Exception ex) { + String msg = "Failed to create owning entity in A&AI."; + throw new IllegalStateException(msg); + } + } + + public void createOwningEntityandConnectServiceInstance(ServiceDecomposition serviceDecomp) { + try{ + ModelMapper modelMapper = new ModelMapper(); + AAIEntityObject owningEntity = modelMapper.map(serviceDecomp.getOwningEntity(), AAIOwningEntity.class); + AAIEntityObject serviceInstance = modelMapper.map(serviceDecomp.getServiceInstance(), AAIServiceInstance.class); + AAIResourcesClient aaiRC = this.getClient(); + aaiRC.createIfNotExists(owningEntity.getUri(), Optional.of(owningEntity)).connect(owningEntity.getUri(), serviceInstance.getUri()); + }catch(Exception ex) { + String msg = "Failed to create owning entity and connect service instance in A&AI."; + throw new IllegalStateException(msg); } + } + + protected AAIResourcesClient getClient() { + return new AAIResourcesClient(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/SDNCOrchestrator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/SDNCOrchestrator.java new file mode 100644 index 0000000000..4cefad2a3b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/orchestration/SDNCOrchestrator.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.orchestration;
+
+import java.util.Optional;
+import java.util.logging.Logger;
+
+import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
+import org.openecomp.mso.client.sdnc.beans.SDNCRequest;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcAction;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcOperation;
+import org.openecomp.mso.client.sdnc.mapper.ServiceTopologyOperationRequestMapper;
+import org.openecomp.mso.client.sdnc.sync.SDNCSyncRpcClient;
+import org.openecomp.mso.properties.MsoPropertiesFactory;
+
+public class SDNCOrchestrator {
+
+ private static MsoPropertiesFactory msoPF = new MsoPropertiesFactory();
+
+ public void createServiceInstance (ServiceDecomposition serviceDecomp) {
+
+ try{
+ msoPF.initializeMsoProperties("MSO_PROP_SDNC_ADAPTER", "mso.sdnc.properties");
+ Optional<String> msoAction = getMSOAction(serviceDecomp);
+ ServiceTopologyOperationRequestMapper sdncRM = new ServiceTopologyOperationRequestMapper(msoAction, SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, "CreateServiceInstance");
+ SDNCRequest request = sdncRM.reqMapper(serviceDecomp);
+ SDNCSyncRpcClient sdncRC = new SDNCSyncRpcClient (request, msoPF);
+ sdncRC.run();
+ } catch (Exception ex) {
+ throw new IllegalStateException();
+ }
+ }
+
+ private Optional<String> getMSOAction (ServiceDecomposition serviceDecomp){
+ String serviceType = serviceDecomp.getServiceInstance().getServiceType();
+ if(serviceType == null || serviceType.equals("")){
+ return Optional.empty();
+ }
+
+ return Optional.of(serviceType);
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/CommonObjectMapperProvider.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/CommonObjectMapperProvider.java deleted file mode 100644 index 0ea15ab204..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/CommonObjectMapperProvider.java +++ /dev/null @@ -1,51 +0,0 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * 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.mso.client.policy;
-
-import javax.ws.rs.ext.ContextResolver;
-
-import javax.ws.rs.ext.Provider;
-
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.MapperFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
-
-@Provider
-public class CommonObjectMapperProvider implements ContextResolver<ObjectMapper> {
-
- final ObjectMapper mapper;
-
- public CommonObjectMapperProvider() {
-
- mapper = new ObjectMapper();
- mapper.setSerializationInclusion(Include.NON_NULL);
- mapper.enable(MapperFeature.USE_ANNOTATIONS);
- mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
- mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
- }
-
- @Override
- public ObjectMapper getContext(Class<?> type) {
- return mapper;
- }
-}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/DecisionAttributes.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/DecisionAttributes.java deleted file mode 100644 index 7b765ebb5f..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/DecisionAttributes.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.policy; - - - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ "ServiceType", "VNFType", "BB_ID", "WorkStep", "ErrorCode" }) -public class DecisionAttributes { - - @JsonProperty("ServiceType") - private String serviceType; - @JsonProperty("VNFType") - private String vNFType; - @JsonProperty("BB_ID") - private String bbID; - @JsonProperty("WorkStep") - private String workStep; - @JsonProperty("ErrorCode") - private String errorCode; - - @JsonProperty("ServiceType") - public String getServiceType() { - return serviceType; - } - - @JsonProperty("ServiceType") - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - @JsonProperty("VNFType") - public String getVNFType() { - return vNFType; - } - - @JsonProperty("VNFType") - public void setVNFType(String vNFType) { - this.vNFType = vNFType; - } - - @JsonProperty("BB_ID") - public String getBBID() { - return bbID; - } - - @JsonProperty("BB_ID") - public void setBBID(String bBID) { - this.bbID = bBID; - } - - @JsonProperty("WorkStep") - public String getWorkStep() { - return workStep; - } - - @JsonProperty("WorkStep") - public void setWorkStep(String workStep) { - this.workStep = workStep; - } - - @JsonProperty("ErrorCode") - public String getErrorCode() { - return errorCode; - } - - @JsonProperty("ErrorCode") - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java deleted file mode 100644 index e02941944a..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/LoggingFilter.java +++ /dev/null @@ -1,138 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.policy; - -import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.logging.Logger; - -import javax.annotation.Priority; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.client.ClientRequestContext; -import javax.ws.rs.client.ClientRequestFilter; -import javax.ws.rs.client.ClientResponseContext; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.ext.WriterInterceptor; -import javax.ws.rs.ext.WriterInterceptorContext; - -@Priority(Integer.MIN_VALUE) -public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor { - - private static final Logger logger = Logger.getLogger(LoggingFilter.class.getName()); - private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream"; - private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; - private final int maxEntitySize; - - public LoggingFilter() { - maxEntitySize = 1024 * 1024; - } - - public LoggingFilter(int maxPayloadSize) { - this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024); - } - - private void log(StringBuilder sb) { - logger.info(sb.toString()); - } - - private InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset) - throws IOException { - if (!stream.markSupported()) { - stream = new BufferedInputStream(stream); - } - stream.mark(maxEntitySize + 1); - final byte[] entity = new byte[maxEntitySize + 1]; - final int entitySize = stream.read(entity); - if (entitySize != -1) { - b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset)); - } - if (entitySize > maxEntitySize) { - b.append("...more..."); - } - b.append('\n'); - stream.reset(); - return stream; - } - - @Override - public void filter(ClientRequestContext requestContext) throws IOException { - if (requestContext.hasEntity()) { - final OutputStream stream = new LoggingStream(requestContext.getEntityStream()); - requestContext.setEntityStream(stream); - requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream); - } - } - - @Override - public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - final StringBuilder sb = new StringBuilder(); - if (responseContext.hasEntity()) { - responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET)); - log(sb); - } - } - - @Override - public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { - final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY); - context.proceed(); - if (stream != null) { - log(stream.getStringBuilder(DEFAULT_CHARSET)); - } - } - - private class LoggingStream extends FilterOutputStream { - - private final StringBuilder sb = new StringBuilder(); - private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - LoggingStream(OutputStream out) { - super(out); - } - - StringBuilder getStringBuilder(Charset charset) { - // write entity to the builder - final byte[] entity = baos.toByteArray(); - - sb.append(new String(entity, 0, entity.length, charset)); - if (entity.length > maxEntitySize) { - sb.append("...more..."); - } - sb.append('\n'); - - return sb; - } - - @Override - public void write(final int i) throws IOException { - if (baos.size() <= maxEntitySize) { - baos.write(i); - } - out.write(i); - } - } -}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java deleted file mode 100644 index 4ed2a887ef..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestClient.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * OPENECOMP - MSO - * ================================================================================ - * 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.mso.client.policy; - -import java.net.MalformedURLException; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; - -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.core.UriBuilderException; - -import org.openecomp.mso.client.ResponseExceptionMapperImpl; -import org.openecomp.mso.client.RestProperties; -import org.openecomp.mso.client.policy.entities.PolicyServiceType; -import org.springframework.stereotype.Service; - -@Service -public class PolicyRestClient extends RestClient { - - private static final String X_ECOMP_REQUESTID = String.valueOf(UUID.randomUUID()); - private final PolicyRestProperties properties; - public PolicyRestClient(PolicyRestProperties props, PolicyServiceType serviceType) { - super(props, Optional.of(UriBuilder.fromPath(serviceType.toString()).build())); - this.properties = props; - this.getClient(); - } - - @Override - protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("ClientAuth", properties.getClientAuth()); - headerMap.put("Authorization", properties.getAuth()); - headerMap.put("Environment", properties.getEnvironment()); - this.addRequestId(X_ECOMP_REQUESTID); - } - - @Override - protected Optional<ClientResponseFilter> addResponseFilter() { - return Optional.of(new ResponseExceptionMapperImpl()); - } - - @Override - public RestClient addRequestId(String requestId) { - this.headerMap.put("X-ECOMP-RequestID", requestId); - return this; - } -}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java deleted file mode 100644 index 1436d83a94..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/RestClient.java +++ /dev/null @@ -1,220 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.policy; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.client.ClientResponseFilter; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation.Builder; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; -import javax.ws.rs.ext.ContextResolver; - -import org.apache.log4j.Logger; -import org.openecomp.mso.client.RestProperties; -import org.openecomp.mso.logger.MsoLogger; -import org.springframework.stereotype.Service; - -import com.fasterxml.jackson.databind.ObjectMapper; - -@Service -public abstract class RestClient { - protected static final String ECOMP_COMPONENT_NAME = "MSO"; - - private static final int MAX_PAYLOAD_SIZE = 1024 * 1024; - private WebTarget webTarget; - - protected final Map<String, String> headerMap; - protected final MsoLogger msoLogger; - protected URL host; - protected Optional<URI> path; - protected Logger logger; - protected String accept; - protected String contentType; - - protected RestClient(RestProperties props, Optional<URI> path) { - logger = Logger.getLogger(getClass().getName()); - msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); - - headerMap = new HashMap<>(); - try { - host = props.getEndpoint(); - } catch (MalformedURLException e) { - logger.error("url not valid", e); - throw new RuntimeException(e); - } - - this.path = path; - initializeClient(getClient()); - } - - protected RestClient(RestProperties props, Optional<URI> path, String accept, String contentType) { - this(props, path); - this.accept = accept; - this.contentType = contentType; - - } - - protected RestClient(URL host, String contentType) { - headerMap = new HashMap<>(); - logger = Logger.getLogger(getClass().getName()); - msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL); - this.path = Optional.empty(); - this.host = host; - this.contentType = contentType; - initializeClient(getClient()); - } - - /** - * Override method to return false to disable logging. - * - * @return true - to enable logging, false otherwise - */ - protected boolean enableLogging() { - return true; - } - - /** - * Override method to return custom value for max payload size. - * - * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024 - */ - protected int getMaxPayloadSize() - { - return MAX_PAYLOAD_SIZE; - } - - protected Builder getBuilder() { - - Builder builder = webTarget.request(); - initializeHeaderMap(headerMap); - - for (Entry<String, String> entry : headerMap.entrySet()) { - builder.header(entry.getKey(), entry.getValue()); - } - return builder; - } - - protected abstract void initializeHeaderMap(Map<String, String> headerMap); - - protected abstract Optional<ClientResponseFilter> addResponseFilter(); - - public abstract RestClient addRequestId(String requestId); - - protected ContextResolver<ObjectMapper> getMapper() { - return new CommonObjectMapperProvider(); - } - - protected String getAccept() { - return accept; - } - - protected String getContentType() { - return contentType; - } - - protected String getMergeContentType() { - return "application/merge-patch+json"; - } - - protected Client getClient() { - return ClientBuilder.newBuilder().build(); - } - - protected void initializeClient(Client client) { - if (this.enableLogging()) { - client.register(logger).register(new LoggingFilter(this.getMaxPayloadSize())); - } - client.register(this.getMapper()); - Optional<ClientResponseFilter> responseFilter = this.addResponseFilter(); - responseFilter.ifPresent(clientResponseFilter -> client.register(clientResponseFilter)); - webTarget = path.<WebTarget>map(uri -> client.target(UriBuilder.fromUri(host + uri.toString()))) - .orElseGet(() -> client.target(host.toString())); - this.accept = MediaType.APPLICATION_JSON; - this.contentType = MediaType.APPLICATION_JSON; - } - - public Response get() { - return this.getBuilder().accept(this.getAccept()).get(); - } - - public Response post(Object obj) { - return this.getBuilder().accept(this.getAccept()).post(Entity.entity(obj, this.getContentType())); - } - - public Response patch(Object obj) { - return this.getBuilder().header("X-HTTP-Method-Override", "PATCH").accept(this.getAccept()) - .post(Entity.entity(obj, this.getMergeContentType())); - } - - public Response put(Object obj) { - return this.getBuilder().accept(this.getAccept()).put(Entity.entity(obj, this.getContentType())); - } - - public Response delete() { - return this.getBuilder().accept(this.getAccept()).delete(); - } - - public Response delete(Object obj) { - return this.getBuilder().header("X-HTTP-Method-Override", "DELETE").accept(this.getAccept()) - .put(Entity.entity(obj, this.getContentType())); - } - - public <T> T get(Class<T> resultClass) { - return this.get().readEntity(resultClass); - } - - public <T> T get(GenericType<T> resultClass) { - return this.get().readEntity(resultClass); - } - - public <T> T post(Object obj, Class<T> resultClass) { - return this.post(obj).readEntity(resultClass); - } - - public <T> T patch(Object obj, Class<T> resultClass) { - return this.patch(obj).readEntity(resultClass); - } - - public <T> T put(Object obj, Class<T> resultClass) { - return this.put(obj).readEntity(resultClass); - } - - public <T> T delete(Class<T> resultClass) { - return this.delete().readEntity(resultClass); - } - - public <T> T delete(Object obj, Class<T> resultClass) { - return this.delete(obj).readEntity(resultClass); - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/RestProperties.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/restproperties/AAIPropertiesImpl.java index ae8862de5e..27352dc11d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/RestProperties.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/restproperties/AAIPropertiesImpl.java @@ -18,13 +18,38 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client; +package org.openecomp.mso.client.restproperties; import java.net.MalformedURLException; import java.net.URL; +import java.util.Map; -public interface RestProperties { +import org.openecomp.mso.bpmn.core.PropertyConfiguration; +import org.openecomp.mso.client.aai.AAIProperties; +import org.openecomp.mso.client.aai.AAIVersion; + +public class AAIPropertiesImpl implements AAIProperties { + + final Map<String, String> props; + + public AAIPropertiesImpl() { + this.props = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); + + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(props.get("aai.endpoint")); + } + + @Override + public String getSystemName() { + return "MSO"; + } + + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } - public URL getEndpoint() throws MalformedURLException; - public String getSystemName(); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestProperties.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/restproperties/PolicyRestPropertiesImpl.java index d9336768fc..eccf87c09d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/PolicyRestProperties.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/restproperties/PolicyRestPropertiesImpl.java @@ -18,20 +18,20 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.policy; +package org.openecomp.mso.client.restproperties; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import org.openecomp.mso.bpmn.core.PropertyConfiguration; -import org.openecomp.mso.client.RestProperties; +import org.openecomp.mso.client.policy.PolicyRestProperties; -public class PolicyRestProperties implements RestProperties { +public class PolicyRestPropertiesImpl implements PolicyRestProperties { final Map<String, String> props; - public PolicyRestProperties() { + public PolicyRestPropertiesImpl() { this.props = PropertyConfiguration.getInstance().getProperties("mso.bpmn.urn.properties"); } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCRequest.java new file mode 100644 index 0000000000..cd04fc5ef0 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCRequest.java @@ -0,0 +1,95 @@ +/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * 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.mso.client.sdnc.beans;
+
+public class SDNCRequest {
+ private String requestId;
+ private String svcInstanceId;
+ private SDNCSvcAction svcAction;
+ private SDNCSvcOperation svcOperation;
+ private String callbackUrl;
+ private String msoAction;
+ private String requestData;
+
+ public SDNCRequest(String requestId, String svcInstanceId, SDNCSvcAction svcAction, SDNCSvcOperation svcOperation,
+ String callbackUrl, String msoAction, String requestData) {
+ this.requestId = requestId;
+ this.svcInstanceId = svcInstanceId;
+ this.svcAction = svcAction;
+ this.svcOperation = svcOperation;
+ this.callbackUrl = callbackUrl;
+ this.msoAction = msoAction;
+ this.requestData = requestData;
+ }
+ public SDNCRequest(){
+
+ }
+
+ public String getRequestId() {
+ return requestId;
+ }
+ public void setRequestId(String requestId) {
+ this.requestId = requestId;
+ }
+ public String getSvcInstanceId() {
+ return svcInstanceId;
+ }
+ public void setSvcInstanceId(String svcInstanceId) {
+ this.svcInstanceId = svcInstanceId;
+ }
+ public SDNCSvcAction getSvcAction() {
+ return svcAction;
+ }
+ public void setSvcAction(SDNCSvcAction svcAction) {
+ this.svcAction = svcAction;
+ }
+ public SDNCSvcOperation getSvcOperation() {
+ return svcOperation;
+ }
+ public void setSvcOperation(SDNCSvcOperation svcOperation) {
+ this.svcOperation = svcOperation;
+ }
+ public String getCallbackUrl() {
+ return callbackUrl;
+ }
+ public void setCallbackUrl(String callbackUrl) {
+ this.callbackUrl = callbackUrl;
+ }
+ public String getMsoAction() {
+ return msoAction;
+ }
+ public void setMsoAction(String msoAction) {
+ this.msoAction = msoAction;
+ }
+
+ public String getRequestData() {
+ return requestData;
+ }
+ public void setRequestData(String requestData) {
+ this.requestData = requestData;
+ }
+ @Override
+ public String toString() {
+ return "SDNCRequest [requestId=" + requestId + ", svcInstanceId=" + svcInstanceId + ", svcAction=" + svcAction
+ + ", svcOperation=" + svcOperation + ", callbackUrl=" + callbackUrl + ", msoAction=" + msoAction
+ + ", requestData=" + requestData + "]";
+ }
+
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/entities/PolicyServiceType.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCSvcAction.java index 01f6738947..91e3a59276 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/policy/entities/PolicyServiceType.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCSvcAction.java @@ -18,31 +18,29 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.policy.entities; - -public enum PolicyServiceType { - GET_CONFIG("getConfig"), - SEND_EVENT("sendEvent"), - PUSH_POLICY("pushPolicy"), - CREATE_POLICY("createPolicy"), - UPDATE_POLICY("updatePolicy"), - GET_DECISION("getDecision"), - GET_METRICS("getMetrics"), - DELETE_POLICY("deletePolicy"), - LIST_CONFIG("listConfig"), - CREATE_DICTIONARY_ITEM("createDictionaryItem"), - UPDATE_DICTIONARY_ITEM("updateDictionaryItem"), - GET_DICTIONARY_ITEMS("getDictionaryItems"); - - private final String name; - - PolicyServiceType(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } - -} +package org.openecomp.mso.client.sdnc.beans;
+
+public enum SDNCSvcAction {
+ ACTIVATE("activate"),
+ DELETE("delete"),
+ ASSIGN("assign"),
+ ROLLBACK("rollback"),
+ UNASSIGN("unassign"),
+ DEACTIVATE("deactivate"),
+ CHANGE_DELETE("changedelete"),
+ CHANGE_ASSIGN("changeassign"),
+ CREATE("create"),
+ ENABLE("enable"),
+ DISABLE("disable");
+
+ private final String name;
+
+ private SDNCSvcAction(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCSvcOperation.java index 73f06b8e58..8cf1052064 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/dmaap/SDNOHealthCheckDmaapPublisher.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/beans/SDNCSvcOperation.java @@ -18,33 +18,26 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.sdno.dmaap; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.openecomp.mso.client.dmaap.DmaapPublisher; - -public class SDNOHealthCheckDmaapPublisher extends DmaapPublisher { - - public SDNOHealthCheckDmaapPublisher() throws FileNotFoundException, IOException { - super(); - } - - @Override - public String getUserName() { - return msoProperties.get("sdno.health-check.dmaap.username"); - } - - @Override - public String getPassword() { - return msoProperties.get("sdno.health-check.dmaap.password"); - } - - @Override - public String getTopic() { - return msoProperties.get("sdno.health-check.dmaap.publisher.topic"); - } - - -} +package org.openecomp.mso.client.sdnc.beans;
+
+public enum SDNCSvcOperation {
+
+ VF_MODULE_TOPOLOGY_OPERATION("vf-module-topology-operation"),
+ NETWORK_TOPOLOGY_OPERATION("network-topology-operation"),
+ VNF_TOPOLOGY_OPERATION("vnf-topology-operation"),
+ CONTRAIL_ROUTE_TOPOLOGY_OPERATION("contrail-route-topology-operation"),
+ SECURITY_ZONE_TOPOLOGY_OPERATION("security-zone-topology-operation"),
+ PORT_MIRROR_TOPOLOGY_OPERATION("port-mirror-topology-operation"),
+ SERVICE_TOPOLOGY_OPERATION("service-topology-operation");
+
+ private final String name;
+
+ private SDNCSvcOperation(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/ResponseExceptionMapperImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/mapper/SDNCRequestMapper.java index 0845a2fbcd..3e714e901d 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/ResponseExceptionMapperImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/mapper/SDNCRequestMapper.java @@ -18,22 +18,29 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Optional; - -import org.apache.commons.io.IOUtils; - -public class ResponseExceptionMapperImpl extends ResponseExceptionMapper { - - @Override - public Optional<String> extractMessage(InputStream stream) throws IOException { - final String input = IOUtils.toString(stream, "UTF-8"); - IOUtils.closeQuietly(stream); - return Optional.of(input); - } - - -} +package org.openecomp.mso.client.sdnc.mapper;
+
+import java.util.Optional;
+
+import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
+import org.openecomp.mso.client.sdnc.beans.SDNCRequest;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcAction;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcOperation;
+
+public abstract class SDNCRequestMapper {
+
+ protected final Optional<String> msoAction;
+ protected final SDNCSvcOperation svcOperation;
+ protected final SDNCSvcAction svcAction;
+ protected final String requestAction;
+
+ public SDNCRequestMapper (Optional<String> msoAction, SDNCSvcOperation svcOperation,
+ SDNCSvcAction svcAction, String requestAction) {
+ this.msoAction = msoAction;
+ this.svcOperation = svcOperation;
+ this.svcAction = svcAction;
+ this.requestAction = requestAction;
+ }
+
+ public abstract SDNCRequest reqMapper (ServiceDecomposition serviceDecomp);
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/mapper/ServiceTopologyOperationRequestMapper.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/mapper/ServiceTopologyOperationRequestMapper.java new file mode 100644 index 0000000000..b87ed00650 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/mapper/ServiceTopologyOperationRequestMapper.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.mapper;
+
+import java.io.StringWriter;
+import java.util.Optional;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+
+import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
+import org.openecomp.mso.client.sdnc.beans.SDNCRequest;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcAction;
+import org.openecomp.mso.client.sdnc.beans.SDNCSvcOperation;
+
+import openecomp.org.mso.workflow.schema.v1.EcompModelInformation;
+import openecomp.org.mso.workflow.schema.v1.RequestInformation;
+import openecomp.org.mso.workflow.schema.v1.SDNCServiceInstanceRequestData;
+import openecomp.org.mso.workflow.schema.v1.ServiceInformation;
+import openecomp.org.mso.workflow.schema.v1.ServiceRequestInput;
+
+public class ServiceTopologyOperationRequestMapper extends SDNCRequestMapper{
+
+ public ServiceTopologyOperationRequestMapper(Optional<String> msoAction, SDNCSvcOperation svcOperation,
+ SDNCSvcAction svcAction, String requestAction) {
+ super(msoAction, svcOperation, svcAction, requestAction);
+ }
+
+ @Override
+ public SDNCRequest reqMapper (ServiceDecomposition serviceDecomp) {
+ SDNCRequest req = new SDNCRequest();
+ req.setCallbackUrl(serviceDecomp.getCallbackURN());
+ if(msoAction.isPresent()){
+ req.setMsoAction(msoAction.get());
+ }
+ req.setRequestId(serviceDecomp.getRequest().getSdncRequestId());
+ req.setSvcInstanceId(serviceDecomp.getServiceInstance().getInstanceId());
+ req.setSvcAction(svcAction);
+ req.setSvcOperation(svcOperation);
+ String reqData ="";
+
+ RequestInformation reqInfo = new RequestInformation();
+ reqInfo.setRequestAction(requestAction);
+ reqInfo.setSource("MSO");
+ reqInfo.setRequestId(serviceDecomp.getRequest().getRequestId());
+ ServiceInformation servInfo = new ServiceInformation();
+ EcompModelInformation emi = new EcompModelInformation();
+ emi.setModelInvariantUuid(serviceDecomp.getRequest().getModelInfo().getModelInvariantUuid());
+ emi.setModelName(serviceDecomp.getRequest().getModelInfo().getModelName());
+ emi.setModelVersion(serviceDecomp.getRequest().getModelInfo().getModelVersion() );
+ servInfo.setEcompModelInformation(emi);
+ servInfo.setServiceId(serviceDecomp.getServiceInstance().getServiceId());
+ servInfo.setSubscriptionServiceType(serviceDecomp.getCustomer().getSubscriptionServiceType());
+ servInfo.setServiceInstanceId(serviceDecomp.getServiceInstance().getInstanceName());
+ servInfo.setGlobalCustomerId(serviceDecomp.getCustomer().getGlobalSubscriberId());
+ ServiceRequestInput servReqInput = new ServiceRequestInput();
+ servReqInput.setServiceInstanceName(serviceDecomp.getServiceInstance().getInstanceName());
+ SDNCServiceInstanceRequestData sdncSIRD = new SDNCServiceInstanceRequestData();
+ sdncSIRD.setRequestInformation(reqInfo);
+ sdncSIRD.setServiceInformation(servInfo);
+ sdncSIRD.setServiceRequestInput(servReqInput);
+
+ try {
+ JAXBContext context = JAXBContext.newInstance(SDNCServiceInstanceRequestData.class);
+
+ Marshaller jaxbMarshaller = context.createMarshaller();
+ jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+
+ StringWriter sw = new StringWriter();
+ jaxbMarshaller.marshal(sdncSIRD, sw);
+ reqData = sw.toString();
+ req.setRequestData(reqData);
+ } catch (JAXBException e) {
+ e.printStackTrace();
+ }
+
+ return req;
+ }
+}
diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/CallbackHeader.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/CallbackHeader.java new file mode 100644 index 0000000000..2ddafc1c17 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/CallbackHeader.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="ResponseCode" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="ResponseMessage" type="{http://www.w3.org/2001/XMLSchema}string"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Async response header +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestId", + "responseCode", + "responseMessage" +}) +@XmlRootElement(name = "CallbackHeader") +public class CallbackHeader { + + @XmlElement(name = "RequestId", required = true) + protected String requestId; + @XmlElement(name = "ResponseCode", required = true) + protected String responseCode; + @XmlElement(name = "ResponseMessage", required = true) + protected String responseMessage; + + public CallbackHeader() { + } + + public CallbackHeader(String reqId, String respCode, String respMsg) { + this.requestId = reqId; + this.responseCode = respCode; + this.responseMessage = respMsg; + } + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + /** + * Gets the value of the responseCode property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponseCode() { + return responseCode; + } + + /** + * Sets the value of the responseCode property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponseCode(String value) { + this.responseCode = value; + } + + /** + * Gets the value of the responseMessage property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getResponseMessage() { + return responseMessage; + } + + /** + * Sets the value of the responseMessage property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setResponseMessage(String value) { + this.responseMessage = value; + } + + @Override + public String toString() { + return "CallbackHeader [requestId=" + requestId + ", responseCode=" + + responseCode + ", responseMessage=" + responseMessage + "]"; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Constants.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Constants.java new file mode 100644 index 0000000000..331fefa677 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Constants.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +public interface Constants { + + public static final String BPEL_REST_URL_PROP = "org.openecomp.mso.adapters.sdnc.rest.bpelurl"; + public static final String BPEL_URL_PROP = "org.openecomp.mso.adapters.sdnc.bpelurl"; + public static final String DEFAULT_BPEL_URL = "http://localhost:8080//active-bpel/services/SDNCAdapterCallbackV1"; + + public static final String MY_URL_PROP = "org.openecomp.mso.adapters.sdnc.myurl"; + public static final String DEFAULT_MY_URL = "https://localhost:8443/adapters/rest/SDNCNotify"; + + public static final String SDNC_AUTH_PROP = "org.openecomp.mso.adapters.sdnc.sdncauth"; + public static final String DEFAULT_SDNC_AUTH = "406B2AE613211B6FB52466DE6E1769AC"; + + public static final String DEFAULT_BPEL_AUTH = "05FDA034C27D1CA51AAB8FAE512EDE45241E16FC8C137D292AA3A964431C82DB"; + public static final String BPEL_AUTH_PROP = "org.openecomp.mso.adapters.sdnc.bpelauth"; + + + public static final String SDNC_SVCCFGRESP_ROOT = "input"; + public static final String SDNC_REQ_ID = "/svc-request-id"; + public static final String SDNC_RESP_CODE = "/response-code"; + public static final String SDNC_RESP_MSG = "/response-message"; + public static final String SDNC_CONNECTTIME_PROP = "org.openecomp.mso.adapters.sdnc.sdncconnecttime"; + public static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + + public static final String REQUEST_TUNABLES = "org.openecomp.mso.adapters.sdnc"; +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/ObjectFactory.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/ObjectFactory.java new file mode 100644 index 0000000000..3ddfdb2925 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/ObjectFactory.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.xml.bind.annotation.XmlRegistry; + + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.openecomp.mso.adapters.sdnc package. + * <p>An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.mso.adapters.sdnc + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link RequestHeader } + * + */ + public RequestHeader createRequestHeader() { + return new RequestHeader(); + } + + /** + * Create an instance of {@link SDNCAdapterResponse } + * + */ + public SDNCAdapterResponse createSDNCAdapterResponse() { + return new SDNCAdapterResponse(); + } + + /** + * Create an instance of {@link SDNCAdapterRequest } + * + */ + public SDNCAdapterRequest createSDNCAdapterRequest() { + return new SDNCAdapterRequest(); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestHeader.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestHeader.java new file mode 100644 index 0000000000..dee79898fa --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestHeader.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element name="RequestId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcInstanceId" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcAction" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="SvcOperation" type="{http://www.w3.org/2001/XMLSchema}string"/> + * <element name="CallbackUrl" type="{http://www.w3.org/2001/XMLSchema}string"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//BPEL to SDNCAdapter request header +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestId", + "svcInstanceId", + "svcAction", + "svcOperation", + "callbackUrl", + "msoAction" +}) +@XmlRootElement(name = "RequestHeader") +public class RequestHeader { + + @XmlElement(name = "RequestId", required = true) + protected String requestId; + @XmlElement(name = "SvcInstanceId") + protected String svcInstanceId; + @XmlElement(name = "SvcAction", required = true) + protected String svcAction; + @XmlElement(name = "SvcOperation", required = true) + protected String svcOperation; + @XmlElement(name = "CallbackUrl", required = true) + protected String callbackUrl; + @XmlElement(name = "MsoAction") + protected String msoAction; + + /** + * Gets the value of the requestId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getRequestId() { + return requestId; + } + + /** + * Sets the value of the requestId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setRequestId(String value) { + this.requestId = value; + } + + public String getSvcInstanceId() { + return svcInstanceId; + } + + public void setSvcInstanceId(String svcInstanceId) { + this.svcInstanceId = svcInstanceId; + } + + /** + * Gets the value of the svcAction property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcAction() { + return svcAction; + } + + /** + * Sets the value of the svcAction property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcAction(String value) { + this.svcAction = value; + } + + /** + * Gets the value of the svcOperation property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSvcOperation() { + return svcOperation; + } + + /** + * Sets the value of the svcOperation property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSvcOperation(String value) { + this.svcOperation = value; + } + + /** + * Gets the value of the callbackUrl property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getCallbackUrl() { + return callbackUrl; + } + + /** + * Sets the value of the callbackUrl property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setCallbackUrl(String value) { + this.callbackUrl = value; + } + + /** + * Gets the value of the callbackUrl property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getMsoAction() { + return msoAction; + } + + /** + * Sets the value of the callbackUrl property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMsoAction(String value) { + this.msoAction = value; + } + + + @Override + public String toString() { + return "RequestHeader [requestId=" + requestId + + ", svcInstanceId=" + svcInstanceId + + ", svcAction=" + svcAction + + ", svcOperation=" + svcOperation + + ", callbackUrl=" + callbackUrl + + ", msoAction=" + msoAction + "]"; + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestTunables.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestTunables.java new file mode 100644 index 0000000000..55d42df6e1 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/RequestTunables.java @@ -0,0 +1,222 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import org.openecomp.mso.logger.MsoAlarmLogger; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +import org.openecomp.mso.logger.MessageEnum; +public class RequestTunables { + + private MsoPropertiesFactory msoPropertiesFactory; + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + public static final String MSO_PROP_SDNC_ADAPTER="MSO_PROP_SDNC_ADAPTER"; + + //criteria + private String reqId = ""; + private String msoAction = ""; + private String operation = ""; + private String action = ""; + + //tunables + private String reqMethod = "POST"; + private String sdncUrl = null; + private String timeout = "60000"; + private String headerName = "sdnc-request-header"; + private String namespace = ""; + private String asyncInd = "N"; //future use + + private String sdncaNotificationUrl = null; + + public RequestTunables(String reqId, String msoAction, String operation, String action, MsoPropertiesFactory msoPropFactory) { + super(); + msoPropertiesFactory = msoPropFactory; + if (reqId != null) { + this.reqId = reqId; + } + if (msoAction != null) { + this.msoAction = msoAction; + } + if (operation != null) { + this.operation = operation; + } + if (action != null) { + this.action = action; + } + } + + public String getReqId() { + return reqId; + } + public void setReqId(String reqId) { + this.reqId = reqId; + } + public String getReqMethod() { + return reqMethod; + } + public void setReqMethod(String reqMethod) { + this.reqMethod = reqMethod; + } + public String getMsoAction() { + return msoAction; + } + public void setMsoAction(String msoAction) { + this.msoAction = msoAction; + } + public String getAction() { + return action; + } + public void setAction(String action) { + this.action = action; + } + public String getOperation() { + return operation; + } + public void setOperation(String operation) { + this.operation = operation; + } + public String getSdncUrl() { + return sdncUrl; + } + public void setSdncUrl(String sdncUrl) { + this.sdncUrl = sdncUrl; + } + public String getTimeout() { + return timeout; + } + public void setTimeout(String timeout) { + this.timeout = timeout; + } + public String getAsyncInd() { + return asyncInd; + } + public void setAsyncInd(String asyncInd) { + this.asyncInd = asyncInd; + } + public String getHeaderName() { + return headerName; + } + public void setHeaderName(String headerName) { + this.headerName = headerName; + } + + + public String getSdncaNotificationUrl() { + return sdncaNotificationUrl; + } + + public void setSdncaNotificationUrl(String sdncaNotificationUrl) { + this.sdncaNotificationUrl = sdncaNotificationUrl; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + @Override + public String toString() { + return "RequestTunables [reqId=" + reqId + ", msoAction=" + msoAction + + ", operation=" + operation + ", action=" + action + + ", reqMethod=" + reqMethod + ", sdncUrl=" + sdncUrl + + ", timeout=" + timeout + ", headerName=" + headerName + + ", sdncaNotificationUrl=" + sdncaNotificationUrl + + ", namespace=" + namespace + "]"; + } + + public void setTunables() + { + String error = null; + String key = null; + if ("query".equals(action)) { //due to variable format for operation eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 + key = Constants.REQUEST_TUNABLES + "." + msoAction + ".." + action; + msoLogger.debug("Generated key: " + key); + } + else if ("put".equals(action) || "restdelete".equals(action)) { //due to variable format for operation eg services/layer3-service-list/8fe4ba4f-35cf-4d9b-a04a-fd3f5d4c5cc9 + key = Constants.REQUEST_TUNABLES + "..." + action; + msoLogger.debug("Generated key: " + key); + } else { + key = Constants.REQUEST_TUNABLES + "." + msoAction + "." + operation +"." + action; + msoLogger.debug("Generated key: " + key); + } + + String value; + try { + value = msoPropertiesFactory.getMsoJavaProperties(MSO_PROP_SDNC_ADAPTER).getProperty(key, ""); + } catch (MsoPropertiesException e) { + msoLogger.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Mso Properties ID not found in cache: " + MSO_PROP_SDNC_ADAPTER, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - Mso Properties ID not found in cache", e); + value=""; + } + + if (value != null && value.length() > 0) { + + String[] parts = value.split("\\|"); //escape pipe + if (parts.length < 3) { + msoLogger.warn(MessageEnum.RA_SDNC_INVALID_CONFIG, key, value, "SDNC", "", MsoLogger.ErrorCode.DataError, "Invalid config"); + } + + for (int i = 0; i < parts.length; i++) { + if (i == 0) { + reqMethod = parts[i]; + msoLogger.debug("Request Method is set to: " + reqMethod); + } else if (i == 1) { + timeout = parts[i]; + msoLogger.debug("Timeout is set to: " + timeout); + } else if (i == 2) { + sdncUrl = SDNCAdapterPortTypeImpl.getProperty(Constants.REQUEST_TUNABLES + "." + parts[i], "",msoPropertiesFactory); + if (operation != null && sdncUrl != null) { + sdncUrl = sdncUrl + operation; + } + msoLogger.debug("SDNC Url is set to: " + sdncUrl); + } else if (i == 3) { + headerName = parts[i]; + msoLogger.debug("HeaderName is set to: " + headerName); + } else if (i == 4) { + namespace = parts[i]; + msoLogger.debug("NameSpace is set to: " + namespace); + } else if (i == 5) { + asyncInd = parts[i]; + msoLogger.debug("AsyncInd is set to: " + asyncInd); + } + } + if (sdncUrl == null) { + error = "Invalid configuration, sdncUrl required for:" + key + " value:" + value; + } + } else { + error = "Missing configuration for:" + key; + } + if (error != null) { + msoLogger.error(MessageEnum.RA_SDNC_MISS_CONFIG_PARAM, key, "SDNC", "", MsoLogger.ErrorCode.DataError, "Missing config param"); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, error); + } + msoLogger.debug ("RequestTunables Key:" + key + " Value:" + value + " Tunables:" + this.toString()); + return; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterCallbackRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterCallbackRequest.java new file mode 100644 index 0000000000..6e9d6757ad --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterCallbackRequest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import java.io.StringWriter; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.logger.MessageEnum; +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element ref="{http://org.openecomp/workflow/sdnc/adapter/schema/v1}CallbackHeader"/> + * <element name="RequestData" type="{http://www.w3.org/2001/XMLSchema}anyType"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Async response +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "callbackHeader", + "requestData" +}) +@XmlRootElement(name = "SDNCAdapterCallbackRequest") +public class SDNCAdapterCallbackRequest { + + @XmlElement(name = "CallbackHeader", required = true) + protected CallbackHeader callbackHeader; + @XmlElement(name = "RequestData") + protected Object requestData; + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + + /** + * Gets the value of the callbackHeader property. + * + * @return + * possible object is + * {@link CallbackHeader } + * + */ + public CallbackHeader getCallbackHeader() { + return callbackHeader; + } + + /** + * Sets the value of the callbackHeader property. + * + * @param value + * allowed object is + * {@link CallbackHeader } + * + */ + public void setCallbackHeader(CallbackHeader value) { + this.callbackHeader = value; + } + + /** + * Gets the value of the requestData property. + * + * @return + * possible object is + * {@link Object } + * + */ + public Object getRequestData() { + return requestData; + } + + /** + * Sets the value of the requestData property. + * + * @param value + * allowed object is + * {@link Object } + * + */ + public void setRequestData(Object value) { + this.requestData = value; + } + + @Override + public String toString() { + try { + JAXBContext ctx = JAXBContext.newInstance("org.openecomp.mso.adapters.sdnc.client"); + Marshaller m = ctx.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); + StringWriter w = new StringWriter(); + m.marshal(this, w); + return (w.toString()); + } + catch (Exception e) + { + msoLogger.error(MessageEnum.RA_MARSHING_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception - MARSHING_ERROR", e); + } + return(""); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortType.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortType.java new file mode 100644 index 0000000000..8b56932769 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortType.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; + +import org.openecomp.mso.client.sdnc.beans.SDNCRequest; + + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-27T18:25:50.914-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//BPEL SDNCAdapter SOAP WebService - impl class in impl pkg +@WebService(targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/wsdl/v1", name = "SDNCAdapterPortType") +@XmlSeeAlso({ObjectFactory.class}) +@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) +public interface SDNCAdapterPortType { + + @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterResponse") + @WebMethod(operationName = "SDNCAdapter") + public SDNCAdapterResponse sdncAdapter( + @WebParam(partName = "SDNCAdapterRequest", name = "SDNCAdapterRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1") + SDNCAdapterRequest sdncAdapterRequest + ); + + @WebMethod + public void healthCheck(); + + SDNCAdapterResponse sdncAdapter(SDNCRequest bpelRequest); +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortTypeImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortTypeImpl.java new file mode 100644 index 0000000000..3d9aab666a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterPortTypeImpl.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + +import javax.annotation.PostConstruct; +import javax.jws.WebService; +import javax.servlet.http.HttpServletResponse; + +import org.openecomp.mso.client.sdnc.beans.SDNCRequest; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoAlarmLogger; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.properties.MsoPropertiesException; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +//BPEL SDNCAdapter SOAP Web Service implementation +@WebService(serviceName = "SDNCAdapterService", endpointInterface = "org.openecomp.mso.client.sdnc.sync.SDNCAdapterPortType", targetNamespace = "http://org.openecomp/workflow/sdnc/ad") +public class SDNCAdapterPortTypeImpl implements SDNCAdapterPortType { + + private MsoPropertiesFactory msoPropertiesFactory=new MsoPropertiesFactory(); + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + private static final String LOG_SERVICE_NAME = "MSO-BPMN:MSO-SDNCAdapter."; + private static final String LOG_REPLY_NAME = "MSO-SDNCAdapter:MSO-BPMN."; + public static final String MSO_PROP_SDNC_ADAPTER="MSO_PROP_SDNC_ADAPTER"; + + @PostConstruct + public void init () { + msoLogger.info(MessageEnum.RA_INIT_SDNC_ADAPTER, "SDNC", "SDNCAdapterPortType"); + } + + /** + * Health Check web method. Does nothing but return to show the adapter is deployed. + */ + @Override + public void healthCheck () + { + msoLogger.debug("Health check call in SDNC Adapter"); + } + + public static String getProperty(String key, String defaultValue, MsoPropertiesFactory msoPropertiesFactoryp) { + String value; + try { + value = msoPropertiesFactoryp.getMsoJavaProperties(MSO_PROP_SDNC_ADAPTER).getProperty(key, defaultValue); + } catch (MsoPropertiesException e) { + msoLogger.error (MessageEnum.NO_PROPERTIES, "Unknown. Mso Properties ID not found in cache: " + MSO_PROP_SDNC_ADAPTER, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - Mso Properties ID not found in cache", e); + return null; + } + msoLogger.debug("Config read for " + MSO_PROP_SDNC_ADAPTER + " - key:" + key + " value:" + value); + return value; + } + + @Override + public SDNCAdapterResponse sdncAdapter(SDNCRequest bpelRequest) { + String bpelReqId = bpelRequest.getRequestId(); + String callbackUrl = bpelRequest.getCallbackUrl(); + long startTime = System.currentTimeMillis (); + MsoLogger.setLogContext(SDNCRequestIdUtil.getSDNCOriginalRequestId (bpelReqId), bpelRequest.getSvcInstanceId()); + MsoLogger.setServiceName (bpelRequest.getSvcAction().toString()); + msoLogger.info(MessageEnum.RA_RECEIVE_BPEL_REQUEST, bpelReqId, callbackUrl, "SDNC", ""); + + SDNCSyncRpcClient sdncClient = new SDNCSyncRpcClient(bpelRequest,msoPropertiesFactory); + long subStartTime = System.currentTimeMillis (); + try { + Thread sdncClientThread = new Thread(sdncClient); + sdncClientThread.start(); + } + catch (Exception e){ + String respMsg = "Error sending request to SDNC. Failed to start SDNC Client thread " + e.getMessage(); + msoLogger.error(MessageEnum.RA_SEND_REQUEST_SDNC_ERR, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception sending request to SDNC. Failed to start SDNC Client thread", e); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, respMsg); + SDNCResponse sdncResp = new SDNCResponse(bpelReqId); + sdncResp.setRespCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + sdncResp.setRespMsg(respMsg); + } + + msoLogger.debug("Sending synchronous response to BPEL"); + SDNCAdapterResponse wsResp = new SDNCAdapterResponse(); + msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful"); + return (wsResp); + } + + @Override + public org.openecomp.mso.client.sdnc.sync.SDNCAdapterResponse sdncAdapter( + org.openecomp.mso.client.sdnc.sync.SDNCAdapterRequest sdncAdapterRequest) { + // TODO Auto-generated method stub + return null; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterRequest.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterRequest.java new file mode 100644 index 0000000000..5beedb12be --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterRequest.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.w3c.dom.Document; +import org.w3c.dom.Node; + +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * <sequence> + * <element ref="{http://org.openecomp/workflow/sdnc/adapter/schema/v1}RequestHeader"/> + * <element name="RequestData" type="{http://www.w3.org/2001/XMLSchema}anyType"/> + * </sequence> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//BPEL to SDNCAdapter request +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "requestHeader", + "requestData" +}) +@XmlRootElement(name = "SDNCAdapterRequest") +public class SDNCAdapterRequest { + + @XmlElement(name = "RequestHeader", required = true) + protected RequestHeader requestHeader; + @XmlElement(name = "RequestData", required = true) + protected Object requestData; + + /** + * Gets the value of the requestHeader property. + * + * @return + * possible object is + * {@link RequestHeader } + * + */ + public RequestHeader getRequestHeader() { + return requestHeader; + } + + /** + * Sets the value of the requestHeader property. + * + * @param value + * allowed object is + * {@link RequestHeader } + * + */ + public void setRequestHeader(RequestHeader value) { + this.requestHeader = value; + } + + /** + * Gets the value of the requestData property. + * + * @return + * possible object is + * {@link Object } + * + */ + public Object getRequestData() { + return requestData; + } + + /** + * Sets the value of the requestData property. + * + * @param value + * allowed object is + * {@link Object } + * + */ + public void setRequestData(Object value) { + this.requestData = value; + } + + @Override + public String toString() { + + String rd = ""; + if (requestData != null) + { + Node node = (Node) requestData; + Document doc = node.getOwnerDocument(); + rd = Utils.domToStr(doc); + } + return "SDNCAdapterRequest [requestHeader=" + requestHeader.toString() + + ", requestData=" + rd + "]"; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/Results.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterResponse.java index aea223da56..4625bfb74f 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/entities/Results.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCAdapterResponse.java @@ -7,9 +7,9 @@ * 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. @@ -18,36 +18,36 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client.aai.entities; +package org.openecomp.mso.client.sdnc.sync; -import java.util.ArrayList; -import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +/** + * <p>Java class for anonymous complex type. + * + * <p>The following schema fragment specifies the expected content contained within this class. + * + * <pre> + * <complexType> + * <complexContent> + * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> + * </restriction> + * </complexContent> + * </complexType> + * </pre> + * + * + */ +//SDNCAdapter to BPEL Sync Response(ACK) - async response(s) follow @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "results" -}) -@XmlRootElement(name = "results") -public class Results<T> { - - @XmlElement(name="results") - protected List<T> result; - - public List<T> getResult() { - if (result == null) { - result = new ArrayList<>(); - } - return this.result; - } - - public void setResult(List<T> result) { - this.result=result; - } +@XmlType(name = "") +@XmlRootElement(name = "SDNCAdapterResponse") +public class SDNCAdapterResponse { + + } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterPortType.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterPortType.java new file mode 100644 index 0000000000..08d3bdbad7 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterPortType.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.jws.soap.SOAPBinding; +import javax.xml.bind.annotation.XmlSeeAlso; + + + +//SDNCAdapter to BPEL Async response WEB Service +@WebService(targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/callback/wsdl/v1", name = "SDNCCallbackAdapterPortType") +@XmlSeeAlso({ObjectFactory.class}) +@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) +public interface SDNCCallbackAdapterPortType { + + @WebResult(name = "SDNCAdapterResponse", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1", partName = "SDNCAdapterCallbackResponse") + @WebMethod(operationName = "SDNCAdapterCallback") + public SDNCAdapterResponse sdncAdapterCallback( + @WebParam(partName = "SDNCAdapterCallbackRequest", name = "SDNCAdapterCallbackRequest", targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/schema/v1") + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest + ); +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterService.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterService.java new file mode 100644 index 0000000000..0e65a3080f --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCCallbackAdapterService.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceFeature; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; + +/** + * This class was generated by Apache CXF 2.7.11.redhat-3 + * 2015-01-28T11:07:02.074-05:00 + * Generated source version: 2.7.11.redhat-3 + * + */ +//SDNCAdapter to BPEL Async response WEB Service +@WebServiceClient(name = "SDNCCallbackAdapterService", + wsdlLocation = "main/resources/SDNCCallbackAdapter.wsdl", + targetNamespace = "http://org.openecomp/workflow/sdnc/adapter/callback/wsdl/v1") +public class SDNCCallbackAdapterService extends Service { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + + public final static URL WSDL_LOCATION; + public final static QName SERVICE = new QName("http://org.openecomp/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterService"); + public final static QName SDNCCallbackAdapterSoapHttpPort = new QName("http://org.openecomp/workflow/sdnc/adapter/callback/wsdl/v1", "SDNCCallbackAdapterSoapHttpPort"); + static { + URL wsdlUrl = null; + try { + wsdlUrl = Thread.currentThread().getContextClassLoader().getResource("main/resources/SDNCCallbackAdapter.wsdl"); + //wsdlUrl = SDNCCallbackAdapterService.class.getClassLoader().getResource("SDNCCallbackAdapter.wsdl"); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - WSDL not found", e); + } + if(wsdlUrl == null) { + msoLogger.error(MessageEnum.RA_WSDL_NOT_FOUND, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "WSDL not found"); + } else { + try { + msoLogger.info(MessageEnum.RA_PRINT_URL, "SDNCCallbackAdapter.wsdl", wsdlUrl.toURI().toString(), "SDNC", ""); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_WSDL_URL_CONVENTION_EXC, "SDNCCallbackAdapter.wsdl", "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception - URL convention problem", e); + } + } + WSDL_LOCATION = wsdlUrl; + } + + public SDNCCallbackAdapterService(URL wsdlLocation) { + super(wsdlLocation, SERVICE); + } + + public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public SDNCCallbackAdapterService() { + super(WSDL_LOCATION, SERVICE); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(WebServiceFeature ... features) { + super(WSDL_LOCATION, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(URL wsdlLocation, WebServiceFeature ... features) { + super(wsdlLocation, SERVICE, features); + } + + //This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2 + //API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1 + //compliant code instead. + public SDNCCallbackAdapterService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { + super(wsdlLocation, serviceName, features); + } + + /** + * + * @return + * returns SDNCCallbackAdapterPortType + */ + @WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort") + public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort() { + return super.getPort(SDNCCallbackAdapterSoapHttpPort, SDNCCallbackAdapterPortType.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values. + * @return + * returns SDNCCallbackAdapterPortType + */ + @WebEndpoint(name = "SDNCCallbackAdapterSoapHttpPort") + public SDNCCallbackAdapterPortType getSDNCCallbackAdapterSoapHttpPort(WebServiceFeature... features) { + return super.getPort(SDNCCallbackAdapterSoapHttpPort, SDNCCallbackAdapterPortType.class, features); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/PreconditionFailedException.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCRequestIdUtil.java index df28baac74..d905748591 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/PreconditionFailedException.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCRequestIdUtil.java @@ -7,9 +7,9 @@ * 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. @@ -18,18 +18,22 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.client; +package org.openecomp.mso.client.sdnc.sync; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; -public class PreconditionFailedException extends WebApplicationException { - /** - * - */ - private static final long serialVersionUID = 1L; +public class SDNCRequestIdUtil { + // Add private constructor to prevent instance creation. + private SDNCRequestIdUtil () {} - public PreconditionFailedException(String message) { - super(message, Response.Status.PRECONDITION_FAILED); + public static String getSDNCOriginalRequestId (String newRequestId) { + + // Camunda scripts will add postfix, such as -1, -2, on the original requestID, to make sure requestID is unique while sending request to SDNC + // In order to use the unique requestID in logging, need to remove the postfix added by the Camunda scripts + // Verify whether the requestId is a valid UUID with postfix (-1, -2). If yes, it should contain 5 times char '-', since valid UUID contains 4 times '-' + // If the requestId is not a valid UUID with postfix, we do nothing + if (newRequestId.split("-").length == 6) { + return newRequestId.substring(0, newRequestId.lastIndexOf('-')); + } + return newRequestId; } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCResponse.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCResponse.java new file mode 100644 index 0000000000..850f5b4734 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCResponse.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import java.io.Serializable; + +public class SDNCResponse implements Serializable { + + private static final long serialVersionUID = 1L; + private String reqId = null; + private int respCode = 0; + private String respMsg = null; + private String sdncResp = null; + + public SDNCResponse(String reqId) { + this.reqId = reqId; + } + public SDNCResponse(String reqId, int respCode, String respMsg) { + this.reqId = reqId; + this.respCode = respCode; + this.respMsg = respMsg; + } + + public String getReqId() { + return reqId; + } + public void setReqId(String reqId) { + this.reqId = reqId; + } + public int getRespCode() { + return respCode; + } + public void setRespCode(int respCode) { + this.respCode = respCode; + } + public String getRespMsg() { + return respMsg; + } + public void setRespMsg(String respMsg) { + this.respMsg = respMsg; + } + public String getSdncResp() { + return sdncResp; + } + public void setSdncResp(String sdncResp) { + this.sdncResp = sdncResp; + } + + @Override + public String toString() { + return "SDNCResponse [reqId=" + reqId + ", respCode=" + respCode + + ", respMsg=" + respMsg + ", sdncResp=" + sdncResp + "]"; + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCSyncRpcClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCSyncRpcClient.java new file mode 100644 index 0000000000..ce9b706760 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/SDNCSyncRpcClient.java @@ -0,0 +1,317 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.XMLConstants; +import javax.xml.bind.DatatypeConverter; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.handler.MessageContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.mso.client.sdnc.beans.SDNCRequest; +import org.openecomp.mso.client.sdnc.beans.SDNCSvcAction; +import org.openecomp.mso.client.sdnc.beans.SDNCSvcOperation; +import org.openecomp.mso.logger.MsoAlarmLogger; +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.properties.MsoJavaProperties; +import org.openecomp.mso.properties.MsoPropertiesFactory; + +//SDNCAdapter to SDNC Rest Client +public class SDNCSyncRpcClient implements Runnable { + + private MsoPropertiesFactory msoPropertiesFactory; + + private SDNCRequest bpelRequest; + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + public static final String MSO_PROP_SDNC_ADAPTER="MSO_PROP_SDNC_ADAPTER"; + + + public SDNCSyncRpcClient(SDNCRequest bpelRequest,MsoPropertiesFactory msoPropFactory) { + this.bpelRequest = bpelRequest; + msoPropertiesFactory = msoPropFactory; + } + + @Override + public void run() + { + String action = bpelRequest.getSvcAction().toString(); + String operation = bpelRequest.getSvcOperation().toString(); + String bpelReqId = bpelRequest.getRequestId(); + String msoAction = bpelRequest.getMsoAction(); + MsoLogger.setLogContext(SDNCRequestIdUtil.getSDNCOriginalRequestId (bpelReqId), bpelRequest.getSvcInstanceId()); + MsoLogger.setServiceName("SDNCRestClient"); + String sdncReqBody = ""; + + msoLogger.debug("BPEL Request:" + bpelRequest.toString()); + RequestTunables rt = new RequestTunables(bpelReqId, msoAction, operation, action, msoPropertiesFactory); + rt.setTunables(); + rt.setSdncaNotificationUrl(SDNCAdapterPortTypeImpl.getProperty(Constants.MY_URL_PROP, Constants.DEFAULT_MY_URL,msoPropertiesFactory)); + + if ("POST".equals(rt.getReqMethod())) { + try { + DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(bpelRequest.getRequestData())); + Document reqDoc = db.parse(is); + sdncReqBody = Utils.genSdncReq(reqDoc, rt); + }catch(Exception ex) { + throw new IllegalStateException(); + } + } else if("PUT".equals(rt.getReqMethod())) { + try { + DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(bpelRequest.getRequestData())); + Document reqDoc = db.parse(is); + sdncReqBody = Utils.genSdncPutReq(reqDoc, rt); + }catch(Exception ex) { + throw new IllegalStateException(); + } + } + long sdncStartTime = System.currentTimeMillis(); + SDNCResponse sdncResp = getSdncResp(sdncReqBody, rt, msoPropertiesFactory); + msoLogger.recordMetricEvent (sdncStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from SDNC", "SDNC", action + "." + operation, null); + msoLogger.debug ("Got the SDNC Code : " + sdncResp.getRespCode()); + msoLogger.debug ("Got the SDNC Response Message:" + sdncResp.getRespMsg()); + validateSDNCResponse(sdncResp.getSdncResp()); + return; + } + + public static SDNCResponse getSdncResp(String sdncReqBody, RequestTunables rt, MsoPropertiesFactory msoPropertiesFactoryp) { + URL url; + HttpURLConnection con = null; + DataOutputStream out = null; + BufferedReader in = null; + SDNCResponse sdncResp = new SDNCResponse(rt.getReqId()); + StringBuffer response = new StringBuffer(); + + msoLogger.info(MessageEnum.RA_SEND_REQUEST_SDNC, rt.toString(), "SDNC", ""); + msoLogger.debug("SDNC Request Body:\n" + sdncReqBody); + + try { + msoLogger.debug("url is: " + rt.getSdncUrl()); + url = new URL(rt.getSdncUrl()); + con = (HttpURLConnection) url.openConnection(); + con.setConnectTimeout(Integer.parseInt(SDNCAdapterPortTypeImpl.getProperty(Constants.SDNC_CONNECTTIME_PROP, "2000",msoPropertiesFactoryp))); + con.setReadTimeout(Integer.parseInt(rt.getTimeout())); + con.setRequestProperty("Accept", "application/json"); + String userCredentials = msoPropertiesFactoryp.getMsoJavaProperties(MSO_PROP_SDNC_ADAPTER).getEncryptedProperty(Constants.SDNC_AUTH_PROP, Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); + + String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + con.setRequestProperty ("Authorization", basicAuth); + con.setRequestMethod(rt.getReqMethod()); + + if ("POST".equals(rt.getReqMethod()) || "PUT".equals(rt.getReqMethod())) { + con.setRequestProperty("Content-type", "application/json"); + con.setRequestProperty("Content-length",String.valueOf(sdncReqBody.length())); + con.setDoOutput(true); + out = new DataOutputStream(con.getOutputStream()); + out.writeBytes(sdncReqBody); + out.flush(); + out.close(); + } + + //Get response + sdncResp.setRespCode(con.getResponseCode()); + sdncResp.setRespMsg(con.getResponseMessage()); + + if (con.getResponseCode()>= 200 && con.getResponseCode()<=299) { + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + String inputLine; + //Not parsing the response -it contains a responseHdr section and data section + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + } + + sdncResp.setSdncResp(response.toString()); + msoLogger.info(MessageEnum.RA_RESPONSE_FROM_SDNC, sdncResp.toString(), "SDNC", ""); + return(sdncResp); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception processing request to SDNC", e); + //default + sdncResp.setRespCode(HttpURLConnection.HTTP_INTERNAL_ERROR); + String respMsg = "Error processing request to SDNC. "; + String sdncErrMsg = null; + + if (e instanceof java.net.SocketTimeoutException ) { + sdncResp.setRespCode(HttpURLConnection.HTTP_CLIENT_TIMEOUT); + respMsg = "Request to SDNC timed out. "; + } + if (con != null) { + try { //e1 + if (con.getResponseCode() != HttpURLConnection.HTTP_OK) //seen in SocketException connection reset + sdncResp.setRespCode(con.getResponseCode()); + respMsg = respMsg + con.getResponseMessage() + ". "; + InputStream is = con.getErrorStream(); + if (is != null) { + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature (XMLConstants.FEATURE_SECURE_PROCESSING, true); + DocumentBuilder db; + Document doc = null; + try { //e2 + db = dbf.newDocumentBuilder(); + doc = db.parse(is); + NodeList errors = (NodeList)xpath.evaluate("errors/error", doc, XPathConstants.NODESET); + for (int i = 0; i < errors.getLength(); i++) { + Element error = (Element) errors.item(i); + String eType = null; + try { + eType = xpath.evaluate("error-type", error); + sdncErrMsg = ". SDNC Returned-[error-type:" + eType; + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-type", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + + String eTag = null; + try { + eTag = xpath.evaluate( "error-tag", error); + sdncErrMsg = sdncErrMsg + ", error-tag:" + eTag; + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-tag", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + + String eMsg = null; + try { + eMsg = xpath.evaluate("error-message", error); + sdncErrMsg = sdncErrMsg + ", error-message:" + eMsg + "]"; + } catch (Exception e3) { + msoLogger.error (MessageEnum.RA_EVALUATE_XPATH_ERROR, "error-message", error.toString(), "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while evaluate xpath", e3); + } + } + } catch (Exception e2) { + msoLogger.error (MessageEnum.RA_ANALYZE_ERROR_EXC, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception while analyse error", e2); + } + } //is != null + } catch (Exception e1) { + msoLogger.error (MessageEnum.RA_ERROR_GET_RESPONSE_SDNC, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception while get SDNC response", e1); + } + } //con != null + + if (e.getMessage() != null) { + respMsg = respMsg + e.getMessage(); + } + if (sdncErrMsg != null) { + respMsg = respMsg + sdncErrMsg; + } + + sdncResp.setRespMsg(respMsg); + + msoLogger.error(MessageEnum.RA_EXCEPTION_COMMUNICATE_SDNC, "SDNC", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with SDNC", e); + alarmLogger.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, respMsg); + return(sdncResp); + } + finally { + if (con != null) { + con.disconnect(); + } + } + } + public void validateSDNCResponse (String sdncResponse){ + String msg; + msoLogger.debug ("Starting validate sdnc response"); + String responseMessage = ""; + String responseCode = ""; + if (sdncResponse != null || !sdncResponse.equals("")){ + try{ + msoLogger.debug ("Got the SDNC Response: " + sdncResponse); + JSONObject jsonObj = new JSONObject(sdncResponse); + msoLogger.debug ("jsonObj has been created"); + + JSONObject requestData = jsonObj.getJSONObject("v1:RequestData"); + JSONObject output = requestData.getJSONObject("output"); + try{ + responseMessage = output.getString("response-message"); + responseCode = output.getString("response-code"); + } catch (Exception ex) { + msoLogger.debug("Response not in lower hyphen"); + } + if(responseMessage.equals("")&&responseCode.equals("")){ + try{ + responseMessage = output.getString("ResponseMessage"); + responseCode = output.getString("ResponseCode"); + } catch (Exception ex) { + msoLogger.debug("Response does not exist"); + } + } + msoLogger.debug("ResponseMessage is: " + responseMessage); + msoLogger.debug("Response Code is: " + responseCode); + if(responseMessage.equals("")){ + msg = "Error from SDNC: Response Message is empty."; + msoLogger.debug(msg); + throw new IllegalStateException(msg); + } + + if(responseCode.equals("")){ + responseCode = "0"; + } + + int code = Integer.parseInt(responseCode); + if(code >=200 && code <=299 || code ==0){ + msoLogger.debug ("Successful Response from SDNC"); + + } else { + msg = "Error from SDNC: Code is not 200-299 or 0."; + msoLogger.debug(msg); + throw new IllegalStateException(msg); + } + } catch (Exception ex) { + msg = "Validate SDNC Response has failed."; + msoLogger.debug(msg); + throw new IllegalStateException(msg); + } + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Utils.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Utils.java new file mode 100644 index 0000000000..7457b59390 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdnc/sync/Utils.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * 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.mso.client.sdnc.sync; + + +import java.io.StringWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.openecomp.mso.logger.MsoLogger; +import org.openecomp.mso.logger.MessageEnum; +public class Utils { + + private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + + public static String genSdncReq(Document reqDoc, RequestTunables rt) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + Element root = newdoc.createElementNS(rt.getNamespace(), "input"); + newdoc.appendChild(root); + + //Header + Element hdr = newdoc.createElement(rt.getHeaderName()); + root.appendChild(hdr); + + String elemData = rt.getReqId(); + Element hdrChild; + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-request-id"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + elemData = rt.getAction(); + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-action"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + elemData = rt.getSdncaNotificationUrl(); + if (elemData != null && elemData.length() > 0) + { + hdrChild = newdoc.createElement("svc-notification-url"); + hdrChild.appendChild(newdoc.createTextNode(elemData)); + hdr.appendChild(hdrChild); + } + + //RequestData + NodeList nodes = reqDoc.getDocumentElement().getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node n = nodes.item(i); + Node newNode = newdoc.importNode(n, true); + root.appendChild(newNode); + } + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncReq:\n" + s); + return (s); + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in genSdncReq", e); + } + return(null); + } + + public static String genSdncPutReq(Document reqDoc, RequestTunables rt) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + + //RequestData + NodeList nodes = reqDoc.getDocumentElement().getChildNodes(); + + + Element root = newdoc.createElement(nodes.item(0).getNodeName()); + newdoc.appendChild(root); + + NodeList childNodes = nodes.item(0).getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node n = childNodes.item(i); + Node newNode = newdoc.importNode(n, true); + root.appendChild(newNode); + } + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncPutReq:\n" + s); + return (s); + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_REQUEST, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genSdncPutReq", e); + } + return(null); + } + + public static String genMsoFailResp(SDNCResponse resp) { + try { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + + //NewDoc for output + //Root + Document newdoc = db.newDocument(); + Element root = newdoc.createElement("output"); + newdoc.appendChild(root); + + Element elem1 = newdoc.createElement("svc-request-id"); + elem1.appendChild(newdoc.createTextNode(resp.getReqId())); + root.appendChild(elem1); + + Element elem2 = newdoc.createElement("response-code"); + elem2.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespCode()))); + root.appendChild(elem2); + + Element elem3 = newdoc.createElement("response-message"); + elem3.appendChild(newdoc.createTextNode(String.valueOf(resp.getRespMsg()))); + root.appendChild(elem3); + + String s = domToStr(newdoc); + msoLogger.debug("Formatted SdncReq:" + s); + return (s); + + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CREATE_SDNC_RESPONSE, "SDNC", "", MsoLogger.ErrorCode.DataError, "Exception in genMsoFailResp", e); + } + return(null); + } + + + public static String domToStr(Document doc) + { + if (doc != null) + { + try { + DOMSource ds = new DOMSource(doc); + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(); + //t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//<?xml version="1.0" encoding="UTF-8"?> + t.transform(ds, sr); + String s = sw.toString(); + + // This is an awful fix for now but we don't want that xmlns="" to be generated + s = s.replaceAll("xmlns=\"\"", ""); + return(s); + } catch (Exception e) { + msoLogger.error(MessageEnum.RA_ERROR_CONVERT_XML2STR, "", "", MsoLogger.ErrorCode.DataError, "Exception - domToStr", e); + } + } + return(null); + } +} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidator.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidator.java deleted file mode 100644 index df30e43822..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidator.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno; - -import java.io.IOException; - -public interface SDNOValidator { - - /** - * Issues a health diagnostic request for a given vnf to SDN-O - * - * @param vnfId - * @param requestingUserId - * @throws IOException - * @throws Exception - */ - public void healthDiagnostic(String vnfId, String requestingUserId) throws IOException, Exception; - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidatorImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidatorImpl.java deleted file mode 100644 index bdb4aa94ee..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/SDNOValidatorImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Optional; - -import org.openecomp.mso.client.dmaap.Consumer; -import org.openecomp.mso.client.dmaap.DmaapConsumer; -import org.openecomp.mso.client.dmaap.DmaapPublisher; -import org.openecomp.mso.client.exceptions.SDNOException; -import org.openecomp.mso.jsonpath.JsonPathUtil; - -public class SDNOValidatorImpl implements SDNOValidator { - - private final static String aafUserName = "something"; - private final static String clientName = "MSO"; - private final static String healthDiagnosticPath = "body.output.response-healthdiagnostic"; - private final static String producerFilePath = ""; - private String uuid; - private boolean continuePolling = true; - @Override - public void healthDiagnostic(String vnfName, String uuid) { - //Query A&AI data - // setup SDNO Entity - //Call SDNO for Health Diagnostic - //create producer file for MRClient https://wiki.web.att.com/display/MessageRouter/DMaaP_MR_JavaReferenceClient - // final MRBatchingPublisher pub = MRClientFactory.createBatchingPublisher(producerFilePath); - // pub.send("Mypartitionkey",JSON.toString(object)); - //create consumer file for MRClient https://wiki.web.att.com/display/MessageRouter/DMaaP_MR_JavaReferenceClient - //check for error in subscription feed filter via jsonpath - //block and continue to poll waiting for response - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Body.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Body.java deleted file mode 100644 index 26c74b0615..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Body.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.beans; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "input" -}) -public class Body implements Serializable -{ - - @JsonProperty("input") - private Input input; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); - private final static long serialVersionUID = 9101706044452851559L; - - @JsonProperty("input") - public Input getInput() { - return input; - } - - @JsonProperty("input") - public void setInput(Input input) { - this.input = input; - } - - public Body withInput(Input input) { - this.input = input; - return this; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public Body withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Input.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Input.java deleted file mode 100644 index 579f481ba8..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/Input.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.beans; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "request-healthdiagnostic", - "request-hd-custom" -}) -public class Input implements Serializable -{ - - @JsonProperty("request-healthdiagnostic") - private RequestHealthDiagnostic RequestHealthDiagnostic; - - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); - private final static long serialVersionUID = 7155546785389227528L; - - @JsonProperty("request-healthdiagnostic") - public RequestHealthDiagnostic getRequestHealthDiagnostic() { - return RequestHealthDiagnostic; - } - - @JsonProperty("request-healthdiagnostic") - public void setRequestHealthDiagnostic(RequestHealthDiagnostic RequestHealthDiagnostic) { - this.RequestHealthDiagnostic = RequestHealthDiagnostic; - } - - public Input withRequestHealthDiagnostic(RequestHealthDiagnostic RequestHealthDiagnostic) { - this.RequestHealthDiagnostic = RequestHealthDiagnostic; - return this; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public Input withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/RequestHealthDiagnostic.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/RequestHealthDiagnostic.java deleted file mode 100644 index 2cddd0331e..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/RequestHealthDiagnostic.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.beans; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "request-client-name", - "request-node-name", - "request-node-ip", - "request-id", - "request-user-id", - "request-node-type", - "health-diagnostic-code" -}) -public class RequestHealthDiagnostic implements Serializable -{ - - @JsonProperty("request-client-name") - private String requestClientName; - @JsonProperty("request-node-name") - private String requestNodeName; - @JsonProperty("request-node-ip") - private String requestNodeIp; - @JsonProperty("request-id") - private String requestId; - @JsonProperty("request-user-id") - private String requestUserId; - @JsonProperty("request-node-type") - private String requestNodeType; - @JsonProperty("health-diagnostic-code") - private String healthDiagnosticCode; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); - private final static long serialVersionUID = 1166788526178388021L; - - @JsonProperty("request-client-name") - public String getRequestClientName() { - return requestClientName; - } - - @JsonProperty("request-client-name") - public void setRequestClientName(String requestClientName) { - this.requestClientName = requestClientName; - } - - public RequestHealthDiagnostic withRequestClientName(String requestClientName) { - this.requestClientName = requestClientName; - return this; - } - - @JsonProperty("request-node-name") - public String getRequestNodeName() { - return requestNodeName; - } - - @JsonProperty("request-node-name") - public void setRequestNodeName(String requestNodeName) { - this.requestNodeName = requestNodeName; - } - - public RequestHealthDiagnostic withRequestNodeName(String requestNodeName) { - this.requestNodeName = requestNodeName; - return this; - } - - @JsonProperty("request-node-ip") - public String getRequestNodeIp() { - return requestNodeIp; - } - - @JsonProperty("request-node-ip") - public void setRequestNodeIp(String requestNodeIp) { - this.requestNodeIp = requestNodeIp; - } - - public RequestHealthDiagnostic withRequestNodeIp(String requestNodeIp) { - this.requestNodeIp = requestNodeIp; - return this; - } - - @JsonProperty("request-id") - public String getRequestId() { - return requestId; - } - - @JsonProperty("request-id") - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public RequestHealthDiagnostic withRequestId(String requestId) { - this.requestId = requestId; - return this; - } - - @JsonProperty("request-user-id") - public String getRequestUserId() { - return requestUserId; - } - - @JsonProperty("request-user-id") - public void setRequestUserId(String requestUserId) { - this.requestUserId = requestUserId; - } - - public RequestHealthDiagnostic withRequestUserId(String requestUserId) { - this.requestUserId = requestUserId; - return this; - } - - @JsonProperty("request-node-type") - public String getRequestNodeType() { - return requestNodeType; - } - - @JsonProperty("request-node-type") - public void setRequestNodeType(String requestNodeType) { - this.requestNodeType = requestNodeType; - } - - public RequestHealthDiagnostic withRequestNodeType(String requestNodeType) { - this.requestNodeType = requestNodeType; - return this; - } - - @JsonProperty("health-diagnostic-code") - public String getHealthDiagnosticCode() { - return healthDiagnosticCode; - } - - @JsonProperty("health-diagnostic-code") - public void setHealthDiagnosticCode(String healthDiagnosticCode) { - this.healthDiagnosticCode = healthDiagnosticCode; - } - - public RequestHealthDiagnostic withHealthDiagnosticCode(String healthDiagnosticCode) { - this.healthDiagnosticCode = healthDiagnosticCode; - return this; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public RequestHealthDiagnostic withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/ResultInfo.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/ResultInfo.java deleted file mode 100644 index 976f5b9a33..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/ResultInfo.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.beans; - -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ -"client-name", -"code", -"processing-host", -"request-id", -"status" -}) -public class ResultInfo { - -@JsonProperty("client-name") -private String clientName; -@JsonProperty("code") -private String code; -@JsonProperty("processing-host") -private String processingHost; -@JsonProperty("request-id") -private String requestId; -@JsonProperty("status") -private String status; -@JsonIgnore -private Map<String, Object> additionalProperties = new HashMap<>(); - -@JsonProperty("client-name") -public String getClientName() { -return clientName; -} - -@JsonProperty("client-name") -public void setClientName(String clientName) { -this.clientName = clientName; -} - -@JsonProperty("code") -public String getCode() { -return code; -} - -@JsonProperty("code") -public void setCode(String code) { -this.code = code; -} - -@JsonProperty("processing-host") -public String getProcessingHost() { -return processingHost; -} - -@JsonProperty("processing-host") -public void setProcessingHost(String processingHost) { -this.processingHost = processingHost; -} - -@JsonProperty("request-id") -public String getRequestId() { -return requestId; -} - -@JsonProperty("request-id") -public void setRequestId(String requestId) { -this.requestId = requestId; -} - -@JsonProperty("status") -public String getStatus() { -return status; -} - -@JsonProperty("status") -public void setStatus(String status) { -this.status = status; -} - -@JsonAnyGetter -public Map<String, Object> getAdditionalProperties() { -return this.additionalProperties; -} - -@JsonAnySetter -public void setAdditionalProperty(String name, Object value) { -this.additionalProperties.put(name, value); -} - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/SDNO.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/SDNO.java deleted file mode 100644 index 8505ec9a74..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/beans/SDNO.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.beans; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "operation", - "nodeLoc", - "nodeType", - "body" -}) -public class SDNO implements Serializable -{ - - @JsonProperty("operation") - private String operation; - @JsonProperty("nodeLoc") - private String nodeLoc; - @JsonProperty("nodeType") - private String nodeType; - @JsonProperty("body") - private Body body; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); - private final static long serialVersionUID = -5303297382564282650L; - - @JsonProperty("operation") - public String getOperation() { - return operation; - } - - @JsonProperty("operation") - public void setOperation(String operation) { - this.operation = operation; - } - - @JsonProperty("nodeLoc") - public String getNodeLoc() { - return nodeLoc; - } - - @JsonProperty("nodeLoc") - public void setNodeLoc(String nodeLoc) { - this.nodeLoc = nodeLoc; - } - - public SDNO withNodeLoc(String nodeLoc) { - this.nodeLoc = nodeLoc; - return this; - } - - public SDNO withOperation(String operation) { - this.operation = operation; - return this; - } - - @JsonProperty("nodeType") - public String getNodeType() { - return nodeType; - } - - @JsonProperty("nodeType") - public void setNodeType(String nodeType) { - this.nodeType = nodeType; - } - - public SDNO withNodeType(String nodeType) { - this.nodeType = nodeType; - return this; - } - - @JsonProperty("body") - public Body getBody() { - return body; - } - - @JsonProperty("body") - public void setBody(Body body) { - this.body = body; - } - - public SDNO withBody(Body body) { - this.body = body; - return this; - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public SDNO SDNO (String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java deleted file mode 100644 index f23d882b53..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java +++ /dev/null @@ -1,156 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.client.sdno.dmaap; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Optional; - -import org.openecomp.mso.client.dmaap.DmaapConsumer; -import org.openecomp.mso.client.exceptions.SDNOException; -import org.openecomp.mso.jsonpath.JsonPathUtil; - -public class SDNOHealthCheckDmaapConsumer extends DmaapConsumer { - - private final String uuid; - private boolean continuePolling = true; - private final static String healthDiagnosticPath = "body.output.*"; - - public SDNOHealthCheckDmaapConsumer() throws FileNotFoundException, IOException { - this("none"); - } - - public SDNOHealthCheckDmaapConsumer(String uuid) throws FileNotFoundException, IOException { - super(); - this.uuid = uuid; - } - - @Override - public String getUserName() { - return msoProperties.get("sdno.health-check.dmaap.username"); - } - - @Override - public String getPassword() { - return msoProperties.get("sdno.health-check.dmaap.password"); - } - - @Override - public String getTopic() { - return msoProperties.get("sdno.health-check.dmaap.subscriber.topic"); - } - - @Override - public boolean continuePolling() { - return continuePolling; - } - - @Override - public void stopProcessingMessages() { - continuePolling = false; - } - @Override - public void processMessage(String message) throws Exception { - if (isHealthDiagnostic(message, this.getRequestId())) { - if (!healthDiagnosticSuccessful(message)) { - Optional<String> statusMessage = this.getStatusMessage(message); - if (statusMessage.isPresent()) { - throw new SDNOException("failed with message " + statusMessage.get()); - } else { - throw new SDNOException("failed with no status message"); - } - } else { - auditLogger.info("successful health diagnostic found for request: " + this.getRequestId()); - stopProcessingMessages(); - } - } - } - - @Override - public boolean isAccepted(String message) { - if (isResultInfo(message)) { - Optional<String> code = isAccepted(message, this.getRequestId()); - if (code.isPresent()) { - if ("202".equals(code.get())) { - return true; - } else { - //TODO check other statuses 400 and 500 - } - } else { - //TODO throw error - } - } - - return false; - } - - @Override - public boolean isFailure(String message) { - if (isResultInfo(message)) { - Optional<String> code = isFailure(message, this.getRequestId()); - if (code.isPresent()) { - if ("500".equals(code.get())) { - return true; - } else { - //TODO check other statuses 400 and 500 - } - } else { - //TODO throw error - } - } - - return false; - } - - @Override - public String getRequestId() { - return uuid; - } - - protected Optional<String> isAccepted(String json, String uuid) { - return JsonPathUtil.getInstance().locateResult(json, String.format("$.result-info[?(@.status=='ACCEPTED' && @.request-id=='%s')].code", uuid)); - } - - protected Optional<String> isFailure(String json, String uuid) { - return JsonPathUtil.getInstance().locateResult(json, String.format("$.result-info[?(@.status=='FAILURE' && @.request-id=='%s')].code", uuid)); - } - - protected boolean isResultInfo(String json) { - return JsonPathUtil.getInstance().pathExists(json, "$[?(@.result-info)]"); - } - - protected boolean isHealthDiagnostic(String json, String uuid) { - return JsonPathUtil.getInstance().pathExists(json, String.format("$[?(@.result-info.request-id=='%s')].%s", uuid, healthDiagnosticPath)); - } - - protected boolean healthDiagnosticSuccessful(String json) { - return JsonPathUtil.getInstance().pathExists(json, "$." + healthDiagnosticPath + "[?(@.response-status=='Success')]"); - } - - protected Optional<String> getStatusMessage(String json) { - return JsonPathUtil.getInstance().locateResult(json, "$." + healthDiagnosticPath + ".error-message"); - } - - @Override - public int getMaximumElapsedTime() { - return 300000; - } -} diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/jsonpath/JsonPathUtil.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/jsonpath/JsonPathUtil.java deleted file mode 100644 index ca0d8e9d70..0000000000 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/jsonpath/JsonPathUtil.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * 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.mso.jsonpath; - -import java.util.Optional; - -import com.jayway.jsonpath.Configuration; -import com.jayway.jsonpath.JsonPath; -import com.jayway.jsonpath.Option; - -import net.minidev.json.JSONArray; - -public class JsonPathUtil { - - - private final Configuration conf; - - private JsonPathUtil() { - conf = Configuration.defaultConfiguration().addOptions(Option.ALWAYS_RETURN_LIST, Option.SUPPRESS_EXCEPTIONS); - } - - private static class Helper { - private static final JsonPathUtil INSTANCE = new JsonPathUtil(); - } - - public static JsonPathUtil getInstance() { - return Helper.INSTANCE; - } - public boolean pathExists(String json, String jsonPath) { - return !JsonPath.using(conf).parse(json).<JSONArray>read(jsonPath).isEmpty(); - } - - public <T> Optional<T> locateResult(String json, String jsonPath) { - final JSONArray result = JsonPath.using(conf).parse(json).read(jsonPath); - if (result.isEmpty()) { - return Optional.empty(); - } else { - return Optional.of((T)result.get(0)); - } - } -} |