Also introduce some minor improvements to robustness, efficiency, & formatting.
Issue-ID: APPC-1789
Signed-off-by: Dunietz, Irwin <id1681@att.com>
Change-Id: I82d970c2f7cde6c8dab1222af86ea70ce93b7e50
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import org.onap.appc.domainmodel.Vserver;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.i18n.Msg;
-import org.onap.ccsdk.sli.adaptors.aai.AAIClient;
-import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
+import org.onap.ccsdk.sli.adaptors.aai.AAIClient;
+import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
throw new APPCException(msg);
}
- String msg = EELFResourceManager
- .format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", STR_VNF_ID + vnfId);
+ String msg =
+ EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "PostGenericVnfData", STR_VNF_ID + vnfId);
ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
} catch (SvcLogicException e) {
String key = "vnf-id = '" + vnfId + "'";
try {
- SvcLogicResource.QueryStatus response = aaiClient
- .query(PARAM_GENERIC_VNF, false, null, key, prefix, null, ctx);
+ SvcLogicResource.QueryStatus response =
+ aaiClient.query(PARAM_GENERIC_VNF, false, null, key, prefix, null, ctx);
if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
String msg = EELFResourceManager.format(Msg.VNF_NOT_FOUND, vnfId);
ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
}
ctx.setAttribute(Constants.IS_RELEASE_ENTITLEMENT_REQUIRE,
- Boolean.toString(!aaiEntitlementPoolUuid.isEmpty()));
+ Boolean.toString(!aaiEntitlementPoolUuid.isEmpty()));
ctx.setAttribute(Constants.IS_RELEASE_LICENSE_REQUIRE, Boolean.toString(!aaiLicenseKeyGroupUuid.isEmpty()));
String msg = EELFResourceManager.format(Msg.SUCCESS_EVENT_MESSAGE, "GetGenericVnfData", STR_VNF_ID + vnfId);
ctx.setAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE, msg);
Vnfc newVnfc = createVnfc(vnfcName, vnfcType);
if (vnfcSet.contains(newVnfc)) {
- Vnfc vnfcFromSet = vnfcSet.stream().filter(vnfc -> vnfc.equals(newVnfc))
- .collect(Collectors.toList()).get(0);
+ Vnfc vnfcFromSet =
+ vnfcSet.stream().filter(vnfc -> vnfc.equals(newVnfc))
+ .collect(Collectors.toList()).get(0);
vnfcFromSet.addVserver(vm);
vm.setVnfc(vnfcFromSet);
} else {
ctx.setAttribute("getVnfHierarchy_result", "FAILURE");
String msg = EELFResourceManager.format(Msg.AAI_QUERY_FAILED, vnfId);
ctx.setAttribute(Constants.ATTRIBUTE_ERROR_MESSAGE, msg);
- logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: " + ctx
- .getAttribute("getResource_result"), e);
+ logger.error("Failed in getVnfHierarchy, Error retrieving VNF details. Error message: "
+ + ctx.getAttribute("getResource_result"), e);
logger.warn("Incorrect or Incomplete VNF Hierarchy");
throw new APPCException("Error Retrieving VNF hierarchy");
}
String resourceType = "vnfc";
SvcLogicContext vnfContext = readResource(query, prefix, resourceType);
String[] additionalProperties = new String[]{PROPERTY_VNFC_TYPE, PROPERTY_VNFC_NAME,
- PROPERTY_VNFC_FUNC_CODE, PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS,
- PROPERTY_LOOP_DISABLED, PROPERTY_ORCHESTRATION_STATUS, PROPERTY_RESOURCE_VERSION};
+ PROPERTY_VNFC_FUNC_CODE, PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS,
+ PROPERTY_LOOP_DISABLED, PROPERTY_ORCHESTRATION_STATUS, PROPERTY_RESOURCE_VERSION};
return readRelationDataAndProperties(prefix, vnfContext, additionalProperties);
}
protected AAIQueryResult readVM(String vmId, String tenantId, String cloudOwner, String cloudRegionId)
throws AAIQueryException {
String query = "vserver.vserver-id = '" + vmId + "' AND tenant.tenant_id = '" + tenantId
- + "' AND cloud-region.cloud-owner = '"
- + cloudOwner + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";
+ + "' AND cloud-region.cloud-owner = '" + cloudOwner
+ + "' AND cloud-region.cloud-region-id = '" + cloudRegionId + "'";
String prefix = "VM";
String resourceType = "vserver";
SvcLogicContext vnfContext = readResource(query, prefix, resourceType);
String[] additionalProperties = new String[]{PROPERTY_VSERVER_ID, PROPERTY_VSERVER_SLINK,
- PROPERTY_VSERVER_NAME, PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS, PROPERTY_LOOP_DISABLED,
- PROPERTY_VSERVER_NAME_2, PROPERTY_RESOURCE_VERSION,};
+ PROPERTY_VSERVER_NAME, PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS, PROPERTY_LOOP_DISABLED,
+ PROPERTY_VSERVER_NAME_2, PROPERTY_RESOURCE_VERSION,};
return readRelationDataAndProperties(prefix, vnfContext, additionalProperties);
}
SvcLogicContext vnfContext = readResource(query, prefix, PARAM_GENERIC_VNF);
String[] additionalProperties = new String[]{PROPERTY_VNF_TYPE, PROPERTY_VNF_NEM,
- PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS, PROPERTY_HEAT_STACK_ID,
- PROPERTY_LOOP_DISABLED, PROPERTY_ORCHESTRATION_STATUS, PROPERTY_RESOURCE_VERSION, Constants.AAI_VNF_MODEL_VERSION_ID};
+ PROPERTY_IN_MAINT, PROPERTY_PROV_STATUS, PROPERTY_HEAT_STACK_ID,
+ PROPERTY_LOOP_DISABLED, PROPERTY_ORCHESTRATION_STATUS, PROPERTY_RESOURCE_VERSION,
+ Constants.AAI_VNF_MODEL_VERSION_ID};
return readRelationDataAndProperties(prefix, vnfContext, additionalProperties);
}
private AAIQueryResult readRelationDataAndProperties(String prefix, SvcLogicContext context,
- String[] additionalProperties) {
+ String[] additionalProperties) {
AAIQueryResult result = new AAIQueryResult();
if (context != null && context.getAttribute(prefix + ".relationship-list.relationship_length") != null) {
- Integer relationsCount = Integer.parseInt(context.getAttribute(
- prefix + ".relationship-list.relationship_length"));
+ Integer relationsCount =
+ Integer.parseInt(context.getAttribute(prefix + ".relationship-list.relationship_length"));
for (int i = 0; i < relationsCount; i++) {
String rsKey = prefix + ".relationship-list.relationship[" + i + "]";
Relationship relationShip = new Relationship();
}
} else {
logger.error("Relationship-list not present in the SvcLogicContext attributes set."
- + (context == null ? "" : "Attribute KeySet = " + context.getAttributeKeySet()));
+ + (context == null ? "" : " Attribute KeySet = " + context.getAttributeKeySet()));
}
if (context != null) {
protected SvcLogicContext readResource(String query, String prefix, String resourceType) throws AAIQueryException {
SvcLogicContext resourceContext = new SvcLogicContext();
try {
- SvcLogicResource.QueryStatus response = aaiClient
- .query(resourceType, false, null, query, prefix, null, resourceContext);
+ SvcLogicResource.QueryStatus response =
+ aaiClient.query(resourceType, false, null, query, prefix, null, resourceContext);
logger.info(STR_AAI_RESPONSE + response.toString());
if (!SvcLogicResource.QueryStatus.SUCCESS.equals(response)) {
throw new AAIQueryException("Error Retrieving VNF hierarchy from A&AI");
String ctxPrefix = params.get("prefix");
String resourceKey = params.get(PARAM_RESOURCE_KEY);
if (logger.isDebugEnabled()) {
- logger.debug("inside getResorce");
- logger.debug("Retrieving " + resourceType + " details from A&AI for Key : " + resourceKey);
+ logger.debug("inside getResource");
+ logger.debug("Retrieving " + resourceType + " details from A&AI for Key: " + resourceKey);
}
try {
SvcLogicResource.QueryStatus response =
- aaiClient.query(resourceType, false, null, resourceKey, ctxPrefix, null, ctx);
+ aaiClient.query(resourceType, false, null, resourceKey, ctxPrefix, null, ctx);
logger.info(STR_AAI_RESPONSE + response.toString());
ctx.setAttribute("getResource_result", response.toString());
} catch (SvcLogicException e) {
logger.error(EELFResourceManager.format(Msg.AAI_GET_DATA_FAILED, resourceKey), e);
}
- if (logger.isDebugEnabled()) {
- logger.debug("exiting getResource======");
- }
+ logger.debug("exiting getResource======");
}
@Override
String attributeValue = params.get("attributeValue");
if (logger.isDebugEnabled()) {
logger.debug("inside postResource");
- logger.debug("Updating " + resourceType + " details in A&AI for Key : " + resourceKey);
- logger.debug("Updating " + attributeName + " to : " + attributeValue);
+ logger.debug("Updating " + resourceType + " details in A&AI for Key: " + resourceKey);
+ logger.debug("Updating " + attributeName + " to: " + attributeValue);
}
Map<String, String> data = new HashMap<>();
data.put(attributeName, attributeValue);
} catch (SvcLogicException e) {
logger.error(EELFResourceManager.format(Msg.AAI_UPDATE_FAILED, resourceKey, attributeValue), e);
}
- if (logger.isDebugEnabled()) {
- logger.debug("exiting postResource======");
- }
+ logger.debug("exiting postResource======");
}
@Override
if (logger.isDebugEnabled()) {
logger.debug("inside deleteResource");
- logger.debug("Deleting " + resourceType + " details From A&AI for Key : " + resourceKey);
+ logger.debug("Deleting " + resourceType + " details from A&AI for Key: " + resourceKey);
}
try {
SvcLogicResource.QueryStatus response = aaiClient.delete(resourceType, resourceKey, ctx);
} catch (SvcLogicException e) {
logger.error(EELFResourceManager.format(Msg.AAI_DELETE_FAILED, resourceKey), e);
}
- if (logger.isDebugEnabled()) {
- logger.debug("exiting deleteResource======");
- }
+ logger.debug("exiting deleteResource======");
}
}
* ONAP : APPC
* ================================================================================
* Copyright (C) 2018 Ericsson
+ * ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
impl.postGenericVnfData(params, ctx);
- Assert.assertThat(ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE), CoreMatchers.containsString(
- "Operation PostGenericVnfData succeed for VNF ID null"));
+ Assert.assertThat(ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE),
+ CoreMatchers.containsString("Operation PostGenericVnfData succeed for VNF ID null"));
}
@Test
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
impl.getGenericVnfData(params, ctx);
- Assert.assertThat(ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE), CoreMatchers.containsString(
- "Operation GetGenericVnfData succeed for VNF ID null"));
+ Assert.assertThat(ctx.getAttribute(org.onap.appc.Constants.ATTRIBUTE_SUCCESS_MESSAGE),
+ CoreMatchers.containsString("Operation GetGenericVnfData succeed for VNF ID null"));
}
@Test
public void testGetGenericVnfDataFailureThrownExeption() throws APPCException, SvcLogicException {
- Mockito.doThrow(new SvcLogicException()).when(aaiClient).query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
- Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class));
+ Mockito.doThrow(new SvcLogicException()).when(aaiClient).query(Mockito.anyString(), Mockito.anyBoolean(),
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
+ Mockito.any(SvcLogicContext.class));
ctx = new SvcLogicContext();
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
@Test
public void testGetVnfHierarchyAaiExceptionFlow2() throws APPCException, SvcLogicException {
- Mockito.doThrow(new SvcLogicException()).when(aaiClient).query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
- Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class));
+ Mockito.doThrow(new SvcLogicException()).when(aaiClient).query(Mockito.anyString(), Mockito.anyBoolean(),
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
+ Mockito.any(SvcLogicContext.class));
ctx = new SvcLogicContext();
params.put(Constants.RESOURCEKEY, "TEST_RESOURCE_KEY");
AAIPluginImpl impl = new AAIPluginImpl();
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
impl.getResource(params, ctx);
- Assert.assertEquals("SUCCESS",ctx.getAttribute("getResource_result"));
+ Assert.assertEquals("SUCCESS", ctx.getAttribute("getResource_result"));
}
@Test
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
impl.postResource(params, ctx);
- Assert.assertEquals("SUCCESS",ctx.getAttribute("postResource_result"));
+ Assert.assertEquals("SUCCESS", ctx.getAttribute("postResource_result"));
}
@Test
AAIPluginImpl impl = new AAIPluginImpl();
impl.initialize();
impl.deleteResource(params, ctx);
- Assert.assertEquals("SUCCESS",ctx.getAttribute("deleteResource_result"));
+ Assert.assertEquals("SUCCESS", ctx.getAttribute("deleteResource_result"));
}
}
* Copyright 2018 TechMahindra
* ================================================================================
* Modifications Copyright (C) 2019 Ericsson
+* ================================================================================
+* Modifications Copyright (C) 2019 AT&T Intellectual Property
*=================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
import org.onap.appc.dg.aai.impl.Constants.SDC_ARTIFACTS_FIELDS;
public class TestConstants {
- private SDC_ARTIFACTS_FIELDS c=SDC_ARTIFACTS_FIELDS.SERVICE_NAME;
+ private SDC_ARTIFACTS_FIELDS c = SDC_ARTIFACTS_FIELDS.SERVICE_NAME;
- @Test
- public void testConstants() {
- Assert.assertEquals("sdnctl",Constants.NETCONF_SCHEMA);
- }
+ @Test
+ public void testConstants() {
+ Assert.assertEquals("sdnctl", Constants.NETCONF_SCHEMA);
+ }
- @Test
- public void testName() {
- Assert.assertEquals("SERVICE_NAME",c.name());
- }
+ @Test
+ public void testName() {
+ Assert.assertEquals("SERVICE_NAME", c.name());
+ }
- @Test
- public void testEqual() {
- Assert.assertTrue(c.equals(SDC_ARTIFACTS_FIELDS.SERVICE_NAME));
- Assert.assertFalse(c.equals(null));
- }
+ @Test
+ public void testEqual() {
+ Assert.assertTrue(c.equals(SDC_ARTIFACTS_FIELDS.SERVICE_NAME));
+ Assert.assertFalse(c.equals(null));
+ }
}
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
try {
validateInputs(params, context);
String jsonMessage = getJsonMessage(params, context);
- logger.debug("Constructed JSON Message : " + jsonMessage);
+ logger.debug("Constructed JSON Message: " + jsonMessage);
messageService.publishMessage(PROPERTIES_PREFIX, "", jsonMessage);
context.setAttribute(prefix + STATUS, SUCCESS);
} catch (Exception e) {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class JsonDgUtilImplTest {
- private static final ThreadLocal<SimpleDateFormat> DATE_TIME_PARSER_THREAD_LOCAL = ThreadLocal
- .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
+ private static final ThreadLocal<SimpleDateFormat> DATE_TIME_PARSER_THREAD_LOCAL =
+ ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
private JsonDgUtilImpl jsonDgUtil;
@Before
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Ericsson. All rights reserved.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
@PrepareForTest(ResolverFactory.class)
public class TestDgResolverPluginImpl {
- private DgResolverPluginImpl dgResolverPluginImpl;
- private Map<String, String> params;
- private SvcLogicContext ctx;
- private AbstractResolver abstractResolver;
- private FlowKey flowKey;
+ private DgResolverPluginImpl dgResolverPluginImpl;
+ private Map<String, String> params;
+ private SvcLogicContext ctx;
+ private AbstractResolver abstractResolver;
+ private FlowKey flowKey;
- @Before
- public void setUp() {
- params = new HashMap<>();
- ctx = new SvcLogicContext();
- PowerMockito.mockStatic(ResolverFactory.class);
- flowKey = Mockito.mock(FlowKey.class);
- abstractResolver = Mockito.mock(AbstractResolver.class);
- PowerMockito.when(ResolverFactory.createResolver(anyString())).thenReturn(abstractResolver);
- dgResolverPluginImpl = new DgResolverPluginImpl();
- PowerMockito.when(flowKey.name()).thenReturn("flowName");
- }
+ @Before
+ public void setUp() {
+ params = new HashMap<>();
+ ctx = new SvcLogicContext();
+ PowerMockito.mockStatic(ResolverFactory.class);
+ flowKey = Mockito.mock(FlowKey.class);
+ abstractResolver = Mockito.mock(AbstractResolver.class);
+ PowerMockito.when(ResolverFactory.createResolver(anyString())).thenReturn(abstractResolver);
+ dgResolverPluginImpl = new DgResolverPluginImpl();
+ PowerMockito.when(flowKey.name()).thenReturn("flowName");
+ }
- @Test
- public void testResolveDgVNF() throws APPCException {
- params.put("action", "healthcheck");
- params.put("vnfVersion", "1");
- params.put("api-ver", "1.0");
- params.put("DGResolutionType", "VNF");
- params.put("vnfType", "vnfType");
- PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "1", "1.0"))
- .thenReturn(flowKey);
- dgResolverPluginImpl.resolveDg(params, ctx);
- assertEquals("flowName", ctx.getAttribute("dg_name"));
- }
+ @Test
+ public void testResolveDgVNF() throws APPCException {
+ params.put("action", "healthcheck");
+ params.put("vnfVersion", "1");
+ params.put("api-ver", "1.0");
+ params.put("DGResolutionType", "VNF");
+ params.put("vnfType", "vnfType");
+ PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "1", "1.0"))
+ .thenReturn(flowKey);
+ dgResolverPluginImpl.resolveDg(params, ctx);
+ assertEquals("flowName", ctx.getAttribute("dg_name"));
+ }
- @Test
- public void testResolveDgVNFC() throws APPCException {
- params.put("action", "healthcheck");
- params.put("vnfcType", "vnfcType");
- params.put("api-ver", "1.0");
- params.put("DGResolutionType", "VNFC");
- params.put("vnfType", "vnfType");
- PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "vnfcType", "1.0"))
- .thenReturn(flowKey);
- dgResolverPluginImpl.resolveDg(params, ctx);
- assertEquals("flowName", ctx.getAttribute("dg_name"));
- }
+ @Test
+ public void testResolveDgVNFC() throws APPCException {
+ params.put("action", "healthcheck");
+ params.put("vnfcType", "vnfcType");
+ params.put("api-ver", "1.0");
+ params.put("DGResolutionType", "VNFC");
+ params.put("vnfType", "vnfType");
+ PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "vnfcType", "1.0"))
+ .thenReturn(flowKey);
+ dgResolverPluginImpl.resolveDg(params, ctx);
+ assertEquals("flowName", ctx.getAttribute("dg_name"));
+ }
- @Test(expected = DgResolverException.class)
- public void testResolveDgWithException() throws APPCException {
- params.put("action", "healthcheck");
- params.put("vnfcType", "vnfcType");
- params.put("api-ver", "1.0");
- params.put("DGResolutionType", "VNFC");
- params.put("vnfType", "vnfType1");
- PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "vnfcType", "1.0"))
- .thenReturn(flowKey);
- dgResolverPluginImpl.resolveDg(params, ctx);
- }
+ @Test(expected = DgResolverException.class)
+ public void testResolveDgWithException() throws APPCException {
+ params.put("action", "healthcheck");
+ params.put("vnfcType", "vnfcType");
+ params.put("api-ver", "1.0");
+ params.put("DGResolutionType", "VNFC");
+ params.put("vnfType", "vnfType1");
+ PowerMockito.when(abstractResolver.resolve("healthcheck", "vnfType", "vnfcType", "1.0"))
+ .thenReturn(flowKey);
+ dgResolverPluginImpl.resolveDg(params, ctx);
+ }
- @Test(expected = DgResolverException.class)
- public void testResolveDgResolverNull() throws APPCException {
- PowerMockito.when(ResolverFactory.createResolver(anyString())).thenReturn(null);
- dgResolverPluginImpl.resolveDg(params, ctx);
- }
+ @Test(expected = DgResolverException.class)
+ public void testResolveDgResolverNull() throws APPCException {
+ PowerMockito.when(ResolverFactory.createResolver(anyString())).thenReturn(null);
+ dgResolverPluginImpl.resolveDg(params, ctx);
+ }
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.att.eelf.configuration.EELFManager;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MDSALStoreImpl.class,MDSALStoreFactory.class})
+@PrepareForTest({MDSALStoreImpl.class, MDSALStoreFactory.class})
public class TestVNFConfiguratorImpl {
private static final EELFLogger logger = EELFManager.getInstance().getLogger(TestVNFConfiguratorImpl.class);
@Test(expected = APPCException.class)
public void testValidations() throws APPCException {
VNFConfigurator configurator = new VNFConfiguratorImpl();
- Map<String,String> params = new HashMap<String, String>();
- params.put("uniqueId","uniqueId");
- params.put("yang","yang");
- params.put("configJSON","configJSON");
- configurator.storeConfig(params,new SvcLogicContext());
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("uniqueId", "uniqueId");
+ params.put("yang", "yang");
+ params.put("configJSON", "configJSON");
+ configurator.storeConfig(params, new SvcLogicContext());
}
@Test
PowerMockito.mockStatic(MDSALStoreFactory.class);
MDSALStore mdsalStore = PowerMockito.mock(MDSALStoreImpl.class);
PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore);
- PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(true);
-
- Map<String,String> params = new HashMap<String, String>();
- params.put("uniqueId","uniqueId");
- params.put("yang","yang");
- params.put("configJSON","configJSON");
- params.put("requestId","requestId");
- configurator.storeConfig(params,new SvcLogicContext());
+ PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(), (Date) Matchers.anyObject()))
+ .thenReturn(true);
+
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("uniqueId", "uniqueId");
+ params.put("yang", "yang");
+ params.put("configJSON", "configJSON");
+ params.put("requestId", "requestId");
+ configurator.storeConfig(params, new SvcLogicContext());
}
@Test
PowerMockito.when(MDSALStoreFactory.createMDSALStore()).thenReturn(mdsalStore);
- PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(),(Date) Matchers.anyObject())).thenReturn(false);
+ PowerMockito.when(mdsalStore.isModulePresent(Matchers.anyString(), (Date) Matchers.anyObject()))
+ .thenReturn(false);
- PowerMockito.doNothing().when(mdsalStore).storeYangModule(Matchers.anyString(),(BundleInfo)Matchers.anyObject());
+ PowerMockito.doNothing()
+ .when(mdsalStore).storeYangModule(Matchers.anyString(), (BundleInfo) Matchers.anyObject());
- Map<String,String> params = new HashMap<>();
- params.put("uniqueId","uniqueId");
- params.put("yang","yang");
- params.put("configJSON","configJSON");
- params.put("requestId","requestId");
- configurator.storeConfig(params,new SvcLogicContext());
+ Map<String, String> params = new HashMap<String, String>();
+ params.put("uniqueId", "uniqueId");
+ params.put("yang", "yang");
+ params.put("configJSON", "configJSON");
+ params.put("requestId", "requestId");
+ configurator.storeConfig(params, new SvcLogicContext());
}
}
* ================================================================================
* Copyright (C) 2019 IBM.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
import org.junit.Test;
public class TestVNFResolverDataReader {
-
+
VNFResolverDataReader vNFResolverDataReader;
Collection<String> list = Arrays.asList("action", "api_version", "vnf_type", "vnf_version");
- String queryStatement = "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING";
+ String queryStatement =
+ "select vnf_type,vnf_version,api_version,action,dg_name,dg_version,dg_module FROM VNF_DG_MAPPING";
@Before
public void setUp() {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.att.eelf.configuration.EELFManager;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({FrameworkUtil.class,DependencyManager.class,DependencyModelFactory.class})
+@PrepareForTest({FrameworkUtil.class, DependencyManager.class, DependencyModelFactory.class})
@SuppressWarnings("unchecked")
public class VnfExecutionFlowImplTest {
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
Whitebox.setInternalState(vnfExecutionFlow, "logger", logger);
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
@Test
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
Whitebox.setInternalState(vnfExecutionFlow, "logger", logger);
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
@Test(expected = RuntimeException.class)
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
Whitebox.setInternalState(vnfExecutionFlow, "logger", logger);
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
private VnfcDependencyModel readCyclicDependencyModel() {
- Vnfc a = createVnfc("A","Active-Passive",null,false);
- Vnfc b = createVnfc("B","Active-Active",null,false);
- Vnfc c = createVnfc("C","Active-Active",null,false);
- Vnfc d = createVnfc("D","Active-Active",null,false);
- Vnfc e = createVnfc("E","Active-Active",null,false);
- Vnfc f = createVnfc("F","Active-Active",null,false);
- Vnfc g = createVnfc("G","Active-Active",null,false);
+ Vnfc a = createVnfc("A", "Active-Passive", null, false);
+ Vnfc b = createVnfc("B", "Active-Active", null, false);
+ Vnfc c = createVnfc("C", "Active-Active", null, false);
+ Vnfc d = createVnfc("D", "Active-Active", null, false);
+ Vnfc e = createVnfc("E", "Active-Active", null, false);
+ Vnfc f = createVnfc("F", "Active-Active", null, false);
+ Vnfc g = createVnfc("G", "Active-Active", null, false);
Node aNode = new Node(a);
Node bNode = new Node(b);
}
- private Vnfc createVnfc(String vnfcType,String resilienceType,String vnfcName,boolean mandatory) {
+ private Vnfc createVnfc(String vnfcType, String resilienceType, String vnfcName, boolean mandatory) {
Vnfc vnfc = new Vnfc();
vnfc.setVnfcType(vnfcType);
vnfc.setResilienceType(resilienceType);
private SvcLogicContext prepareContextForComplexDependency() {
SvcLogicContext context = new SvcLogicContext();
- context.setAttribute("input.action-identifiers.vnf-id","1");
- context.setAttribute("vnf.type","vSCP");
- context.setAttribute("vnf.vnfcCount","7");
-
- context.setAttribute("vnf.vnfc[0].name","A");
- context.setAttribute("vnf.vnfc[0].type","A");
- context.setAttribute("vnf.vnfc[0].vm_count","2");
- context.setAttribute("vnf.vnfc[0].vm[0].url","A1");
- context.setAttribute("vnf.vnfc[0].vm[1].url","A2");
-
- context.setAttribute("vnf.vnfc[1].name","B");
- context.setAttribute("vnf.vnfc[1].type","B");
- context.setAttribute("vnf.vnfc[1].vm_count","5");
- context.setAttribute("vnf.vnfc[1].vm[0].url","B1");
- context.setAttribute("vnf.vnfc[1].vm[1].url","B2");
- context.setAttribute("vnf.vnfc[1].vm[2].url","B3");
- context.setAttribute("vnf.vnfc[1].vm[3].url","B4");
- context.setAttribute("vnf.vnfc[1].vm[4].url","B5");
-
- context.setAttribute("vnf.vnfc[2].name","C");
- context.setAttribute("vnf.vnfc[2].type","C");
- context.setAttribute("vnf.vnfc[2].vm_count","4");
- context.setAttribute("vnf.vnfc[2].vm[0].url","C1");
- context.setAttribute("vnf.vnfc[2].vm[1].url","C2");
- context.setAttribute("vnf.vnfc[2].vm[2].url","C3");
- context.setAttribute("vnf.vnfc[2].vm[3].url","C4");
-
- context.setAttribute("vnf.vnfc[3].name","D");
- context.setAttribute("vnf.vnfc[3].type","D");
- context.setAttribute("vnf.vnfc[3].vm_count","3");
- context.setAttribute("vnf.vnfc[3].vm[0].url","D1");
- context.setAttribute("vnf.vnfc[3].vm[1].url","D2");
- context.setAttribute("vnf.vnfc[3].vm[2].url","D3");
-
- context.setAttribute("vnf.vnfc[4].name","E");
- context.setAttribute("vnf.vnfc[4].type","E");
- context.setAttribute("vnf.vnfc[4].vm_count","2");
- context.setAttribute("vnf.vnfc[4].vm[0].url","E1");
- context.setAttribute("vnf.vnfc[4].vm[1].url","E2");
-
- context.setAttribute("vnf.vnfc[5].name","F");
- context.setAttribute("vnf.vnfc[5].type","F");
- context.setAttribute("vnf.vnfc[5].vm_count","1");
- context.setAttribute("vnf.vnfc[5].vm[0].url","F1");
-
- context.setAttribute("vnf.vnfc[6].name","G");
- context.setAttribute("vnf.vnfc[6].type","G");
- context.setAttribute("vnf.vnfc[6].vm_count","1");
- context.setAttribute("vnf.vnfc[6].vm[0].url","G1");
-
+ context.setAttribute("input.action-identifiers.vnf-id", "1");
+ context.setAttribute("vnf.type", "vSCP");
+ context.setAttribute("vnf.vnfcCount", "7");
+
+ context.setAttribute("vnf.vnfc[0].name", "A");
+ context.setAttribute("vnf.vnfc[0].type", "A");
+ context.setAttribute("vnf.vnfc[0].vm_count", "2");
+ context.setAttribute("vnf.vnfc[0].vm[0].url", "A1");
+ context.setAttribute("vnf.vnfc[0].vm[1].url", "A2");
+
+ context.setAttribute("vnf.vnfc[1].name", "B");
+ context.setAttribute("vnf.vnfc[1].type", "B");
+ context.setAttribute("vnf.vnfc[1].vm_count", "5");
+ context.setAttribute("vnf.vnfc[1].vm[0].url", "B1");
+ context.setAttribute("vnf.vnfc[1].vm[1].url", "B2");
+ context.setAttribute("vnf.vnfc[1].vm[2].url", "B3");
+ context.setAttribute("vnf.vnfc[1].vm[3].url", "B4");
+ context.setAttribute("vnf.vnfc[1].vm[4].url", "B5");
+
+ context.setAttribute("vnf.vnfc[2].name", "C");
+ context.setAttribute("vnf.vnfc[2].type", "C");
+ context.setAttribute("vnf.vnfc[2].vm_count", "4");
+ context.setAttribute("vnf.vnfc[2].vm[0].url", "C1");
+ context.setAttribute("vnf.vnfc[2].vm[1].url", "C2");
+ context.setAttribute("vnf.vnfc[2].vm[2].url", "C3");
+ context.setAttribute("vnf.vnfc[2].vm[3].url", "C4");
+
+ context.setAttribute("vnf.vnfc[3].name", "D");
+ context.setAttribute("vnf.vnfc[3].type", "D");
+ context.setAttribute("vnf.vnfc[3].vm_count", "3");
+ context.setAttribute("vnf.vnfc[3].vm[0].url", "D1");
+ context.setAttribute("vnf.vnfc[3].vm[1].url", "D2");
+ context.setAttribute("vnf.vnfc[3].vm[2].url", "D3");
+
+ context.setAttribute("vnf.vnfc[4].name", "E");
+ context.setAttribute("vnf.vnfc[4].type", "E");
+ context.setAttribute("vnf.vnfc[4].vm_count", "2");
+ context.setAttribute("vnf.vnfc[4].vm[0].url", "E1");
+ context.setAttribute("vnf.vnfc[4].vm[1].url", "E2");
+
+ context.setAttribute("vnf.vnfc[5].name", "F");
+ context.setAttribute("vnf.vnfc[5].type", "F");
+ context.setAttribute("vnf.vnfc[5].vm_count", "1");
+ context.setAttribute("vnf.vnfc[5].vm[0].url", "F1");
+
+ context.setAttribute("vnf.vnfc[6].name", "G");
+ context.setAttribute("vnf.vnfc[6].type", "G");
+ context.setAttribute("vnf.vnfc[6].vm_count", "1");
+ context.setAttribute("vnf.vnfc[6].vm[0].url", "G1");
return context;
}
private VnfcDependencyModel readComplexDependencyModel() {
- Vnfc a = createVnfc("A","Active-Passive",null,false);
- Vnfc b = createVnfc("B","Active-Active",null,false);
- Vnfc c = createVnfc("C","Active-Active",null,false);
- Vnfc d = createVnfc("D","Active-Active",null,false);
- Vnfc e = createVnfc("E","Active-Active",null,false);
- Vnfc f = createVnfc("F","Active-Active",null,false);
- Vnfc g = createVnfc("G","Active-Active",null,false);
-
+ Vnfc a = createVnfc("A", "Active-Passive", null, false);
+ Vnfc b = createVnfc("B", "Active-Active", null, false);
+ Vnfc c = createVnfc("C", "Active-Active", null, false);
+ Vnfc d = createVnfc("D", "Active-Active", null, false);
+ Vnfc e = createVnfc("E", "Active-Active", null, false);
+ Vnfc f = createVnfc("F", "Active-Active", null, false);
+ Vnfc g = createVnfc("G", "Active-Active", null, false);
Node aNode = new Node(a);
Node bNode = new Node(b);
private VnfcDependencyModel readDependencyModel() {
- Vnfc smp = createVnfc("SMP","Active-Passive",null,false);
- Vnfc be = createVnfc("BE","Active-Active",null,false);
- Vnfc fe = createVnfc("FE","Active-Active",null,false);
-
+ Vnfc smp = createVnfc("SMP", "Active-Passive", null, false);
+ Vnfc be = createVnfc("BE", "Active-Active", null, false);
+ Vnfc fe = createVnfc("FE", "Active-Active", null, false);
Node smpNode = new Node(smp);
Node beNode = new Node(be);
}
private Map<String, String> prepareParams() {
- Map<String,String> params = new HashMap<>();
- params.put(Constants.DEPENDENCY_TYPE,"RESOURCE");
- params.put(Constants.FLOW_STRATEGY,"FORWARD");
+ Map<String, String> params = new HashMap<>();
+ params.put(Constants.DEPENDENCY_TYPE, "RESOURCE");
+ params.put(Constants.FLOW_STRATEGY, "FORWARD");
- params.put(Constants.VNF_TYPE,"vSCP");
- params.put(Constants.VNF_VERION,"1.00");
+ params.put(Constants.VNF_TYPE, "vSCP");
+ params.put(Constants.VNF_VERION, "1.00");
return params;
}
private SvcLogicContext prepareContext() {
SvcLogicContext context = new SvcLogicContext();
- context.setAttribute("input.action-identifiers.vnf-id","1");
- context.setAttribute("vnf.type","vSCP");
- context.setAttribute("vnf.vnfcCount","3");
-
- context.setAttribute("vnf.vnfc[0].name","SMPname");
- context.setAttribute("vnf.vnfc[0].type","SMP");
- context.setAttribute("vnf.vnfc[0].vm_count","2");
- context.setAttribute("vnf.vnfc[0].vm[0].url","SMP_URL1");
- context.setAttribute("vnf.vnfc[0].vm[1].url","SMP_URL2");
-
- context.setAttribute("vnf.vnfc[1].name","BEname");
- context.setAttribute("vnf.vnfc[1].type","BE");
- context.setAttribute("vnf.vnfc[1].vm_count","5");
- context.setAttribute("vnf.vnfc[1].vm[0].url","BE_URL1");
- context.setAttribute("vnf.vnfc[1].vm[1].url","BE_URL2");
- context.setAttribute("vnf.vnfc[1].vm[2].url","BE_URL3");
- context.setAttribute("vnf.vnfc[1].vm[3].url","BE_URL4");
- context.setAttribute("vnf.vnfc[1].vm[4].url","BE_URL5");
-
- context.setAttribute("vnf.vnfc[2].name","FEname");
- context.setAttribute("vnf.vnfc[2].type","FE");
- context.setAttribute("vnf.vnfc[2].vm_count","2");
- context.setAttribute("vnf.vnfc[2].vm[0].url","FE_URL1");
- context.setAttribute("vnf.vnfc[2].vm[1].url","FE_URL2");
+ context.setAttribute("input.action-identifiers.vnf-id", "1");
+ context.setAttribute("vnf.type", "vSCP");
+ context.setAttribute("vnf.vnfcCount", "3");
+
+ context.setAttribute("vnf.vnfc[0].name", "SMPname");
+ context.setAttribute("vnf.vnfc[0].type", "SMP");
+ context.setAttribute("vnf.vnfc[0].vm_count", "2");
+ context.setAttribute("vnf.vnfc[0].vm[0].url", "SMP_URL1");
+ context.setAttribute("vnf.vnfc[0].vm[1].url", "SMP_URL2");
+
+ context.setAttribute("vnf.vnfc[1].name", "BEname");
+ context.setAttribute("vnf.vnfc[1].type", "BE");
+ context.setAttribute("vnf.vnfc[1].vm_count", "5");
+ context.setAttribute("vnf.vnfc[1].vm[0].url", "BE_URL1");
+ context.setAttribute("vnf.vnfc[1].vm[1].url", "BE_URL2");
+ context.setAttribute("vnf.vnfc[1].vm[2].url", "BE_URL3");
+ context.setAttribute("vnf.vnfc[1].vm[3].url", "BE_URL4");
+ context.setAttribute("vnf.vnfc[1].vm[4].url", "BE_URL5");
+
+ context.setAttribute("vnf.vnfc[2].name", "FEname");
+ context.setAttribute("vnf.vnfc[2].type", "FE");
+ context.setAttribute("vnf.vnfc[2].vm_count", "2");
+ context.setAttribute("vnf.vnfc[2].vm[0].url", "FE_URL1");
+ context.setAttribute("vnf.vnfc[2].vm[1].url", "FE_URL2");
return context;
}
public void testMissingVnfcTypeInDependencyModel() throws DependencyModelNotFound, InvalidDependencyModelException {
Map<String, String> params = prepareParams();
SvcLogicContext context = prepareContext();
- context.setAttribute("vnf.vnfc[3].name","XEname");
- context.setAttribute("vnf.vnfc[3].type","XE");
- context.setAttribute("vnf.vnfc[3].vm_count","2");
- context.setAttribute("vnf.vnfc[3].vm[0].url","XE_URL1");
- context.setAttribute("vnf.vnfc[3].vm[1].url","XE_URL2");
- context.setAttribute("vnf.vnfcCount","4");
+ context.setAttribute("vnf.vnfc[3].name", "XEname");
+ context.setAttribute("vnf.vnfc[3].type", "XE");
+ context.setAttribute("vnf.vnfc[3].vm_count", "2");
+ context.setAttribute("vnf.vnfc[3].vm[0].url", "XE_URL1");
+ context.setAttribute("vnf.vnfc[3].vm[1].url", "XE_URL2");
+ context.setAttribute("vnf.vnfcCount", "4");
VnfcDependencyModel dependencyModel = readDependencyModel();
.thenReturn(dependencyModel);
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
@Test(expected = RuntimeException.class)
- public void testMissingMandatoryVnfcTypeInInventoryModel() throws DependencyModelNotFound, InvalidDependencyModelException {
+ public void testMissingMandatoryVnfcTypeInInventoryModel()
+ throws DependencyModelNotFound, InvalidDependencyModelException {
Map<String, String> params = prepareParams();
SvcLogicContext context = prepareContext();
VnfcDependencyModel dependencyModel = readDependencyModel();
- Vnfc xe = createVnfc("XE","Active-Active",null, true);
+ Vnfc xe = createVnfc("XE", "Active-Active", null, true);
Node xeNode = new Node(xe);
dependencyModel.getDependencies().add(xeNode);
.thenReturn(dependencyModel);
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
@Test
- public void testMissingOptionalVnfcTypeInInventoryModel() throws DependencyModelNotFound, InvalidDependencyModelException {
+ public void testMissingOptionalVnfcTypeInInventoryModel()
+ throws DependencyModelNotFound, InvalidDependencyModelException {
Map<String, String> params = prepareParams();
SvcLogicContext context = prepareContext();
VnfcDependencyModel dependencyModel = readDependencyModel();
- Vnfc xe = createVnfc("XE","Active-Active",null, false);
+ Vnfc xe = createVnfc("XE", "Active-Active", null, false);
Node xeNode = new Node(xe);
dependencyModel.getDependencies().add(xeNode);
.thenReturn(dependencyModel);
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
@Test
- public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild() throws DependencyModelNotFound, InvalidDependencyModelException {
+ public void testMissingOptionalVnfcTypeInInventoryModelWithDependentChild()
+ throws DependencyModelNotFound, InvalidDependencyModelException {
Map<String, String> params = prepareParams();
SvcLogicContext context = prepareContext();
- context.setAttribute("vnf.vnfc[3].name","YEname");
- context.setAttribute("vnf.vnfc[3].type","YE");
- context.setAttribute("vnf.vnfc[3].vm_count","2");
- context.setAttribute("vnf.vnfc[3].vm[0].url","YE_URL1");
- context.setAttribute("vnf.vnfc[3].vm[1].url","YE_URL2");
- context.setAttribute("vnf.vnfcCount","4");
+ context.setAttribute("vnf.vnfc[3].name", "YEname");
+ context.setAttribute("vnf.vnfc[3].type", "YE");
+ context.setAttribute("vnf.vnfc[3].vm_count", "2");
+ context.setAttribute("vnf.vnfc[3].vm[0].url", "YE_URL1");
+ context.setAttribute("vnf.vnfc[3].vm[1].url", "YE_URL2");
+ context.setAttribute("vnf.vnfcCount", "4");
VnfcDependencyModel dependencyModel = readDependencyModel();
- Vnfc xe = createVnfc("XE","Active-Active",null, false);
- Vnfc ye = createVnfc("YE","Active-Active",null, true);
+ Vnfc xe = createVnfc("XE", "Active-Active", null, false);
+ Vnfc ye = createVnfc("YE", "Active-Active", null, true);
Node xeNode = new Node(xe);
Node yeNode = new Node(ye);
yeNode.addParent(xe);
.thenReturn(dependencyModel);
VnfExecutionFlow vnfExecutionFlow = new VnfExecutionFlowImpl();
- vnfExecutionFlow.getVnfExecutionFlowData(params,context);
+ vnfExecutionFlow.getVnfExecutionFlowData(params, context);
}
-
-
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
-* Copyright 2018 AT&T
+* Copyright 2018-2019 AT&T
*=================================================================================
* Modifications Copyright 2018 IBM.
*=================================================================================
public void testFromJsonReader() {
try {
- JSONUtilVnfTest jOut = JSONUtil.fromJson(new FileReader("src/test/resources/data/input.json"), JSONUtilVnfTest.class);
+ JSONUtilVnfTest jOut =
+ JSONUtil.fromJson(new FileReader("src/test/resources/data/input.json"), JSONUtilVnfTest.class);
assertEquals("I1", jOut.getVnfId());
assertEquals("T1", jOut.getVnfType());
} catch (UncheckedIOException uioe) {
Map<String, String> map = JSONUtil.extractPlainValues(refJson, "vnfId", "vnfType");
HashMap<String, String> hashMap =
- (map instanceof HashMap)
- ? (HashMap) map
- : new HashMap<String, String>(map);
+ (map instanceof HashMap)
+ ? (HashMap) map
+ : new HashMap<String, String>(map);
assertEquals(hashMap.get("vnfId"), "I2");
assertEquals(hashMap.get("vnfType"), "T2");
fail(uioe.getMessage() + " Unchecked IO exception encountered");
}
}
-
+
@Test(expected=UncheckedIOException.class)
- public void testCatchSectionOfToJson() throws IOException
- {
- JSONUtil.toJson(new Object());
+ public void testCatchSectionOfToJson() throws IOException {
+ JSONUtil.toJson(new Object());
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
private static final String PROPERTIES = "properties";
private static final String ACTIVE_ACTIVE = "Active-Active";
private static final String ACTIVE_PASSIVE = "Active-Passive";
- private static final String HIGH_AVAILABLITY = "high_availablity";
+ private static final String HIGH_AVAILABLITY = "high_availablity"; // Deprecated original spelling
private static final String HIGH_AVAILABILITY = "high_availability";
private static final String MANDATORY = "mandatory";
private static final String TOPOLOGY_TEMPLATE = "topology_template";
}
public VnfcDependencyModel generateDependencyModel(String vnfModel, String vnfType)
- throws InvalidDependencyModelException {
+ throws InvalidDependencyModelException {
Set<Node<Vnfc>> dependencies = new HashSet<>();
ObjectMapper mapper = getMapper();
boolean mandatory;
try {
ObjectNode root = (ObjectNode) mapper.readTree(vnfModel);
- if (root.get(TOPOLOGY_TEMPLATE) == null || root.get(TOPOLOGY_TEMPLATE).get("node_templates") == null) {
+ JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE);
+ JsonNode nodeTemplateNode;
+
+ if (topologyTemplateNode == null
+ || (nodeTemplateNode = topologyTemplateNode.get("node_templates")) == null) {
throw new InvalidDependencyModelException(
- "Dependency model is missing 'topology_template' or 'node_templates' elements");
+ "Dependency model is missing 'topology_template' or 'node_templates' elements");
}
- JsonNode topologyTemplateNode = root.get(TOPOLOGY_TEMPLATE);
- JsonNode nodeTemplateNode = topologyTemplateNode.get("node_templates");
Iterator<Map.Entry<String, JsonNode>> iterator = nodeTemplateNode.fields();
for (JsonNode yamlNode : nodeTemplateNode) {
logger.debug("Processing node: " + yamlNode);
String vnfcType = getQualifiedVnfcType(fullvnfcType);
String type = yamlNode.get("type").textValue();
type = type.substring(0, type.lastIndexOf('.') + 1);
- if (type.concat(vnfcType).toLowerCase().startsWith(prefix.concat(vnfcType).toLowerCase())) {
+ if (type.toLowerCase().startsWith(prefix.toLowerCase())) {
resilienceType = resolveResilienceType(yamlNode);
mandatory = resolveMandatory(yamlNode);
logger.debug("Dependency node already exists for vnfc Type: " + vnfcType);
if (StringUtils.isEmpty(vnfcNode.getChild().getResilienceType())) {
logger.debug("Updating resilience type, "
- + "dependencies and mandatory attribute for VNFC type: " + vnfcType);
+ + "dependencies and mandatory attribute for VNFC type: " + vnfcType);
vnfcNode.getChild().setResilienceType(resilienceType);
tryFillNode(dependencies, parentList, vnfcNode);
vnfcNode.getChild().setMandatory(mandatory);
}
} else {
- logger.debug("Creating dependency node for : " + vnfcType);
+ logger.debug("Creating dependency node for: " + vnfcType);
vnfcNode = new Node<>(createVnfc(mandatory, resilienceType, vnfcType));
tryFillNode(dependencies, parentList, vnfcNode);
- logger.debug("Adding VNFC to dependency model : " + vnfcNode);
+ logger.debug("Adding VNFC to dependency model: " + vnfcNode);
dependencies.add(vnfcNode);
}
}
}
} catch (IOException e) {
- logger.error("Error parsing dependency model : " + vnfModel);
- logger.error("Error message : " + e);
+ logger.error("Error parsing dependency model: " + vnfModel);
+ logger.error("Error message: " + e);
throw new InvalidDependencyModelException("Error parsing dependency model. " + e.getMessage());
}
return new VnfcDependencyModel(dependencies);
}
private boolean mandatoryDoesNotExist(JsonNode yamlNode) {
- return yamlNode.get(PROPERTIES).findValue(MANDATORY) == null ||
- yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty();
+ return yamlNode.get(PROPERTIES).findValue(MANDATORY) == null
+ || yamlNode.get(PROPERTIES).findValue(MANDATORY).asText().isEmpty();
}
private String resolveResilienceType(JsonNode yamlNode) {
resilienceType = dependencyMap
.get(yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABILITY).textValue());
}
- // The property name "high_availability" was misspelled in the code so leaving in the code to check for the
+ // The property name "high_availability" was misspelled in the code so leaving in the code to check for the
// incorrectly spelled version to avoid breaking existing configurations using the misspelled version
- else if (yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null ||
- yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) {
+ else if (yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY) == null
+ || yamlNode.get(PROPERTIES).findValue(HIGH_AVAILABLITY).asText().isEmpty()) {
resilienceType = ACTIVE_ACTIVE;
} else {
resilienceType = dependencyMap
String parentType = getVnfcType(type);
Node<Vnfc> parentNode = getNode(nodes, parentType);
if (parentNode != null) {
- logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list ");
+ logger.debug("VNFC already exists for VNFC type: " + parentType + ". Adding it to parent list");
node.addParent(parentNode.getChild());
} else {
- logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC ");
+ logger.debug("VNFC does not exist for VNFC type: " + parentType + ". Creating new VNFC");
parentNode = new Node<>(createVnfc(false, null, parentType));
node.addParent(parentNode.getChild());
- logger.debug("Adding VNFC to dependency model : " + parentNode);
+ logger.debug("Adding VNFC to dependency model: " + parentNode);
nodes.add(parentNode);
}
}
}
private String[] getDependencyArray(JsonNode node, JsonNode nodeTemplateNode)
- throws InvalidDependencyModelException {
+ throws InvalidDependencyModelException {
JsonNode requirementsNode = node.get("requirements");
Set<String> dependencyList = new HashSet<>();
if (requirementsNode != null) {
for (JsonNode internalNode : requirementsNode) {
- //TODO : In this release we are supporting both relationship = tosca.capabilities.Node and relationship =tosca.relationships.DependsOn we need to remove one of them in next release post confirming with SDC team
+ /* TODO: In this release we are supporting both relationship = tosca.capabilities.Node
+ and relationship = tosca.relationships.DependsOn
+ we need to remove one of them in next release post confirming with SDC team */
if (verifyNode(internalNode)) {
parseDependencyModel(node, nodeTemplateNode, dependencyList, internalNode);
}
}
private void parseDependencyModel(JsonNode node, JsonNode nodeTemplateNode, Set<String> dependencyList,
- JsonNode internalNode) throws InvalidDependencyModelException {
+ JsonNode internalNode) throws InvalidDependencyModelException {
if (internalNode.findValue("node") != null) {
String nodeName = internalNode.findValue("node").asText();
dependencyList.add(getQualifiedVnfcType(fullVnfcName));
} else {
throw new InvalidDependencyModelException(
- "Error parsing dependency model. " + "Dependent Node not found for " + node.get("type"));
+ "Error parsing dependency model. Dependent Node not found for " + node.get("type"));
}
}
private boolean verifyNode(JsonNode internalNode) {
- return nodeNullCheck(internalNode) &&
- "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText()) &&
- ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue(RELATIONSHIP).asText()) ||
- "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue(RELATIONSHIP).asText()));
+ return nodeNullCheck(internalNode)
+ && "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue("capability").asText())
+ && ("tosca.relationships.DependsOn".equalsIgnoreCase(internalNode.findValue(RELATIONSHIP).asText())
+ || "tosca.capabilities.Node".equalsIgnoreCase(internalNode.findValue(RELATIONSHIP).asText()));
}
private boolean nodeNullCheck(JsonNode internalNode) {
return internalNode.get("dependency") != null && internalNode.findValue("capability") != null
- && internalNode.findValue(RELATIONSHIP) != null;
+ && internalNode.findValue(RELATIONSHIP) != null;
}
protected Node<Vnfc> getNode(Set<Node<Vnfc>> nodes, String vnfcType) {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
MetadataCache<DependencyModelIdentifier,VnfcDependencyModel> cache;
- DependencyManagerImpl(){
+ DependencyManagerImpl() {
cache = MetadataCacheFactory.getInstance().getMetadataCache();
}
- public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,DependencyTypes dependencyType) throws InvalidDependencyModelException, DependencyModelNotFound {
+ public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier,
+ DependencyTypes dependencyType) throws InvalidDependencyModelException, DependencyModelNotFound {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier
+ logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = " + modelIdentifier
+ " , DependencyTypes = " + dependencyType);
}
VnfcDependencyModel dependencyModel = cache.getObject(modelIdentifier);
- if(dependencyModel == null){
+ if (dependencyModel == null) {
logger.debug("Dependency model not found in cache, creating strategy for reading it");
DependencyType strategy = getStrategy(dependencyType);
// Throw exception if strategy could not be created because it is required
dependencyModel = strategy.getVnfcDependencyModel(modelIdentifier);
}
if (logger.isTraceEnabled()) {
- logger.trace("Returning getVnfcDependencyModel with dependency model = "+ dependencyModel);
+ logger.trace("Returning getVnfcDependencyModel with dependency model = " + dependencyModel);
}
return dependencyModel;
}
private DependencyType getStrategy(DependencyTypes dependencyType) {
- switch (dependencyType){
+ switch (dependencyType) {
case RESOURCE:
return new ResourceDependency();
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import org.osgi.framework.ServiceReference;
-public class ResourceDependency implements DependencyType{
+public class ResourceDependency implements DependencyType {
private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourceDependency.class);
private MetadataService metadataService;
- public ResourceDependency(){
+ public ResourceDependency() {
getMetadataServiceRef();
}
this.metadataService = metadataService;
}
- public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier) throws InvalidDependencyModelException, DependencyModelNotFound {
+ public VnfcDependencyModel getVnfcDependencyModel(DependencyModelIdentifier modelIdentifier)
+ throws InvalidDependencyModelException, DependencyModelNotFound {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = "+ modelIdentifier);
+ logger.trace("Entering to getVnfcDependencyModel with DependencyModelIdentifier = " + modelIdentifier);
}
String vnfModel = metadataService.getVnfModel(modelIdentifier);
- if(vnfModel ==null){
+ if (vnfModel == null) {
logger.debug("Vnf model not found from metadata service");
throw new DependencyModelNotFound("Invalid or Empty VNF Model");
}
logger.trace("Building dependency model for Vnf Model : " + vnfModel);
}
DependencyModelParser modelParser = new DependencyModelParser();
- return modelParser.generateDependencyModel(vnfModel,modelIdentifier.getVnfType());
+ return modelParser.generateDependencyModel(vnfModel, modelIdentifier.getVnfType());
}
}
* ================================================================================
* Copyright (C) 2019 Ericsson
* =============================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
import org.onap.appc.dg.flowbuilder.exception.InvalidDependencyModelException;
import org.onap.appc.dg.objects.VnfcDependencyModel;
import org.onap.appc.dg.objects.Node;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
+@RunWith(MockitoJUnitRunner.class)
public class DependencyModelParserTest {
@Rule
}
@Test
- public void testGenerateDependencyModel() throws InvalidDependencyModelException, JsonProcessingException, IOException {
+ public void testGenerateDependencyModel()
+ throws InvalidDependencyModelException, JsonProcessingException, IOException {
ObjectNode topologyTemplate = new ObjectNode(JsonNodeFactory.instance);
topologyTemplate = (ObjectNode) new ObjectMapper().readTree(jsonString);
Mockito.doReturn(topologyTemplate).when(mockMapper).readTree("VNF_MODEL");
}
@Test
- public void testGenerateDependencyModelWithNode() throws InvalidDependencyModelException, JsonProcessingException, IOException {
+ public void testGenerateDependencyModelWithNode()
+ throws InvalidDependencyModelException, JsonProcessingException, IOException {
ObjectNode topologyTemplate = new ObjectNode(JsonNodeFactory.instance);
topologyTemplate = (ObjectNode) new ObjectMapper().readTree(jsonString);
Node<Vnfc> vnfc = new Node(new Vnfc());
@Test
public void testGenerateDependencyModelExceptionFlow() throws InvalidDependencyModelException {
expectedEx.expect(InvalidDependencyModelException.class);
- expectedEx.expectMessage("Dependency model is missing 'topology_template' or 'node_templates' elements");
+ expectedEx.expectMessage("Dependency model is missing 'topology_template' or 'node_templates' elements");
VnfcDependencyModel model = parser.generateDependencyModel("VNF_MODEL", "VNF_TYPE");
}
- private String jsonString = "{\"topology_template\": {" +
- " \"node_templates\": {" +
- " \"Property Definition_Template\": {" +
- " \"type\": \"org.onap.resource.vfc.vnf_type.abstract.nodes.property definition\"," +
- " \"properties\": {" +
- " \"mandatory\": \"true\"," +
- " \"high_availablity\": \"Active-Passive\"" +
- " },\"requirements\": [" +
- " {" +
- " \"dependency\": {" +
- " \"capability\": \"tosca.capabilities.Node\"," +
- " \"node\": \"tosca.nodes.Root\"," +
- " \"relationship\": \"tosca.relationships.DependsOn\"," +
- " \"occurrences\": [" +
- " 0," +
- " \"UNBOUNDED\"" +
- " ]" +
- " }" +
- " }" +
- " ]" +
- " },\"tosca.nodes.Root\": {\"type\": \"VNFC_NAME\"}" +
- " }" +
- " }" +
- "}";
+ private String jsonString =
+ "{\"topology_template\": {"
+ + " \"node_templates\": {"
+ + " \"Property Definition_Template\": {"
+ + " \"type\": \"org.onap.resource.vfc.vnf_type.abstract.nodes.property definition\","
+ + " \"properties\": {"
+ + " \"mandatory\": \"true\","
+ + " \"high_availability\": \"Active-Passive\""
+ + " },\"requirements\": ["
+ + " {"
+ + " \"dependency\": {"
+ + " \"capability\": \"tosca.capabilities.Node\","
+ + " \"node\": \"tosca.nodes.Root\","
+ + " \"relationship\": \"tosca.relationships.DependsOn\","
+ + " \"occurrences\": ["
+ + " 0,"
+ + " \"UNBOUNDED\""
+ + " ]"
+ + " }"
+ + " }"
+ + " ]"
+ + " },\"tosca.nodes.Root\": {\"type\": \"VNFC_NAME\"}"
+ + " }"
+ + " }"
+ + "}";
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD);
VnfcDependencyModel dependencyModel = readDependencyModel();
InventoryModel inventoryModel = readInventoryModel();
- VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel);
+ VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel, inventoryModel);
Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
List<Vnfc> list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("SMP","Active-Passive","SMP_Name")));
+ Assert.assertTrue(list.contains(createVnfc("SMP", "Active-Passive", "SMP_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("BE","Active-Active","BE_Name")));
+ Assert.assertTrue(list.contains(createVnfc("BE", "Active-Active", "BE_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("FE","Active-Active","FE_Name")));
+ Assert.assertTrue(list.contains(createVnfc("FE", "Active-Active", "FE_Name")));
}
- private Vnfc createVnfc(String vnfcType,String resilienceType,String vnfcName) {
+ private Vnfc createVnfc(String vnfcType, String resilienceType, String vnfcName) {
Vnfc vnfc = new Vnfc();
vnfc.setVnfcType(vnfcType);
vnfc.setVnfcName(vnfcName);
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE);
VnfcDependencyModel dependencyModel = readDependencyModel();
InventoryModel inventoryModel = readInventoryModel();
- VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel);
+ VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel, inventoryModel);
Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
List<Vnfc> list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("FE","Active-Active","FE_Name")));
+ Assert.assertTrue(list.contains(createVnfc("FE", "Active-Active", "FE_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("BE","Active-Active","BE_Name")));
+ Assert.assertTrue(list.contains(createVnfc("BE", "Active-Active", "BE_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("SMP","Active-Passive","SMP_Name")));
+ Assert.assertTrue(list.contains(createVnfc("SMP", "Active-Passive", "SMP_Name")));
Assert.assertThat(flowModel.toString(), CoreMatchers.containsString("Flow Model : Vnfc : vnfcType = FE"));
}
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD);
VnfcDependencyModel dependencyModel = readComplexDependencyModel();
InventoryModel inventoryModel = readComplexInventoryModel();
- VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel);
+ VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel, inventoryModel);
Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
- try{
+ try {
List<Vnfc> list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("A","Active-Active","A_Name")));
- Assert.assertTrue(list.contains(createVnfc("E","Active-Active","E_Name")));
+ Assert.assertTrue(list.contains(createVnfc("A", "Active-Active", "A_Name")));
+ Assert.assertTrue(list.contains(createVnfc("E", "Active-Active", "E_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("B","Active-Active","B_Name")));
- Assert.assertTrue(list.contains(createVnfc("C","Active-Active","C_Name")));
+ Assert.assertTrue(list.contains(createVnfc("B", "Active-Active", "B_Name")));
+ Assert.assertTrue(list.contains(createVnfc("C", "Active-Active", "C_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("D","Active-Active","D_Name")));
- Assert.assertTrue(list.contains(createVnfc("F","Active-Active","F_Name")));
+ Assert.assertTrue(list.contains(createVnfc("D", "Active-Active", "D_Name")));
+ Assert.assertTrue(list.contains(createVnfc("F", "Active-Active", "F_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("G","Active-Active","G_Name")));
- }
- catch (Exception e){
+ Assert.assertTrue(list.contains(createVnfc("G", "Active-Active", "G_Name")));
+ } catch (Exception e) {
e.printStackTrace();
}
}
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.REVERSE);
VnfcDependencyModel dependencyModel = readComplexDependencyModel();
InventoryModel inventoryModel = readComplexInventoryModel();
- VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel,inventoryModel);
+ VnfcFlowModel flowModel = builder.buildFlowModel(dependencyModel, inventoryModel);
Iterator<List<Vnfc>> itr = flowModel.getModelIterator();
List<Vnfc> list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("D","Active-Active","D_Name")));
+ Assert.assertTrue(list.contains(createVnfc("D", "Active-Active", "D_Name")));
- Assert.assertTrue(list.contains(createVnfc("G","Active-Active","G_Name")));
+ Assert.assertTrue(list.contains(createVnfc("G", "Active-Active", "G_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("B","Active-Active","B_Name")));
- Assert.assertTrue(list.contains(createVnfc("F","Active-Active","F_Name")));
+ Assert.assertTrue(list.contains(createVnfc("B", "Active-Active", "B_Name")));
+ Assert.assertTrue(list.contains(createVnfc("F", "Active-Active", "F_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("C","Active-Active","C_Name")));
+ Assert.assertTrue(list.contains(createVnfc("C", "Active-Active", "C_Name")));
list = itr.next();
- Assert.assertTrue(list.contains(createVnfc("E","Active-Active","E_Name")));
- Assert.assertTrue(list.contains(createVnfc("A","Active-Active","A_Name")));
+ Assert.assertTrue(list.contains(createVnfc("E", "Active-Active", "E_Name")));
+ Assert.assertTrue(list.contains(createVnfc("A", "Active-Active", "A_Name")));
}
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.findByString("FORWARD"));
VnfcDependencyModel dependencyModel = readCyclicDependencyModel();
InventoryModel inventoryModel = readInventoryModel();
- builder.buildFlowModel(dependencyModel,inventoryModel);
+ builder.buildFlowModel(dependencyModel, inventoryModel);
}
@Test(expected = InvalidDependencyModelException.class)
FlowBuilder builder = FlowBuilderFactory.getInstance().getFlowBuilder(FlowStrategies.FORWARD);
VnfcDependencyModel dependencyModel = readCyclicDependencyModelWithRootNode();
InventoryModel inventoryModel = readInventoryModel();
- builder.buildFlowModel(dependencyModel,inventoryModel);
+ builder.buildFlowModel(dependencyModel, inventoryModel);
}
-
+
@Test
- public void testInventoryModelToString(){
- Vnf vnf = createVnf("vnf_1","vABCD","1");
+ public void testInventoryModelToString() {
+ Vnf vnf = createVnf("vnf_1", "vABCD", "1");
InventoryModel inventoryModel = new InventoryModel(vnf);
Assert.assertEquals("InventoryModel = Vnf : vnfId = vnf_1 , vnfType = vABCD", inventoryModel.toString());
}
private VnfcDependencyModel readCyclicDependencyModelWithRootNode() {
- Vnfc a = createVnfc("A","Active-Passive",null);
- Vnfc b = createVnfc("B","Active-Active",null);
- Vnfc c = createVnfc("C","Active-Active",null);
+ Vnfc a = createVnfc("A", "Active-Passive", null);
+ Vnfc b = createVnfc("B", "Active-Active", null);
+ Vnfc c = createVnfc("C", "Active-Active", null);
Node aNode = new Node(a);
}
private InventoryModel readComplexInventoryModel() {
- Vnf vnf = createVnf("vnf_1","vABCD","1");
-
- Vnfc vnfcA = createVnfc("A","Active-Active","A_Name");
- Vnfc vnfcB = createVnfc("B","Active-Active","B_Name");
- Vnfc vnfcC = createVnfc("C","Active-Active","C_Name");
- Vnfc vnfcD = createVnfc("D","Active-Active","D_Name");
- Vnfc vnfcE = createVnfc("E","Active-Active","E_Name");
- Vnfc vnfcF = createVnfc("F","Active-Active","F_Name");
- Vnfc vnfcG = createVnfc("G","Active-Active","G_Name");
-
- vnf.addVserver(createVserver("VM_URL_A1",vnfcA));
- vnf.addVserver(createVserver("VM_URL_B1",vnfcB));
- vnf.addVserver(createVserver("VM_URL_C1",vnfcC));
- vnf.addVserver(createVserver("VM_URL_D1",vnfcD));
- vnf.addVserver(createVserver("VM_URL_E1",vnfcE));
- vnf.addVserver(createVserver("VM_URL_F1",vnfcF));
- vnf.addVserver(createVserver("VM_URL_G1",vnfcG));
+ Vnf vnf = createVnf("vnf_1", "vABCD", "1");
+
+ Vnfc vnfcA = createVnfc("A", "Active-Active", "A_Name");
+ Vnfc vnfcB = createVnfc("B", "Active-Active", "B_Name");
+ Vnfc vnfcC = createVnfc("C", "Active-Active", "C_Name");
+ Vnfc vnfcD = createVnfc("D", "Active-Active", "D_Name");
+ Vnfc vnfcE = createVnfc("E", "Active-Active", "E_Name");
+ Vnfc vnfcF = createVnfc("F", "Active-Active", "F_Name");
+ Vnfc vnfcG = createVnfc("G", "Active-Active", "G_Name");
+
+ vnf.addVserver(createVserver("VM_URL_A1", vnfcA));
+ vnf.addVserver(createVserver("VM_URL_B1", vnfcB));
+ vnf.addVserver(createVserver("VM_URL_C1", vnfcC));
+ vnf.addVserver(createVserver("VM_URL_D1", vnfcD));
+ vnf.addVserver(createVserver("VM_URL_E1", vnfcE));
+ vnf.addVserver(createVserver("VM_URL_F1", vnfcF));
+ vnf.addVserver(createVserver("VM_URL_G1", vnfcG));
return new InventoryModel(vnf);
}
- private Vnf createVnf(String vnfId,String vnfType,String vnfVersion) {
+ private Vnf createVnf(String vnfId, String vnfType, String vnfVersion) {
Vnf vnf = new Vnf();
vnf.setVnfId(vnfId);
vnf.setVnfType(vnfType);
}
private VnfcDependencyModel readComplexDependencyModel() {
- Vnfc a = createVnfc("A","Active-Active",null);
- Vnfc b = createVnfc("B","Active-Active",null);
- Vnfc c = createVnfc("C","Active-Active",null);
- Vnfc d = createVnfc("D","Active-Active",null);
- Vnfc e = createVnfc("E","Active-Active",null);
- Vnfc f = createVnfc("F","Active-Active",null);
- Vnfc g = createVnfc("G","Active-Active",null);
+ Vnfc a = createVnfc("A", "Active-Active", null);
+ Vnfc b = createVnfc("B", "Active-Active", null);
+ Vnfc c = createVnfc("C", "Active-Active", null);
+ Vnfc d = createVnfc("D", "Active-Active", null);
+ Vnfc e = createVnfc("E", "Active-Active", null);
+ Vnfc f = createVnfc("F", "Active-Active", null);
+ Vnfc g = createVnfc("G", "Active-Active", null);
Node aNode = new Node(a);
private VnfcDependencyModel readCyclicDependencyModel() {
- Vnfc a = createVnfc("A","Active-Passive",null);
- Vnfc b = createVnfc("B","Active-Active",null);
- Vnfc c = createVnfc("C","Active-Active",null);
- Vnfc d = createVnfc("D","Active-Active",null);
+ Vnfc a = createVnfc("A", "Active-Passive", null);
+ Vnfc b = createVnfc("B", "Active-Active", null);
+ Vnfc c = createVnfc("C", "Active-Active", null);
+ Vnfc d = createVnfc("D", "Active-Active", null);
Node aNode = new Node(a);
}
private InventoryModel readInventoryModel() {
- Vnf vnf = createVnf("vnf_1","vSCP","1");
+ Vnf vnf = createVnf("vnf_1", "vSCP", "1");
- Vnfc smp = createVnfc("SMP",null,"SMP_Name");
- Vserver smpVm1 = createVserver("SMP_URL1",smp);
- Vserver smpVm2 = createVserver("SMP_URL2",smp);
+ Vnfc smp = createVnfc("SMP", null, "SMP_Name");
+ Vserver smpVm1 = createVserver("SMP_URL1", smp);
+ Vserver smpVm2 = createVserver("SMP_URL2", smp);
vnf.addVserver(smpVm1);
vnf.addVserver(smpVm2);
- Vnfc be = createVnfc("BE",null,"BE_Name");
+ Vnfc be = createVnfc("BE", null, "BE_Name");
- Vserver beVm1 = createVserver("BE_URL1",be);
- Vserver beVm2 = createVserver("BE_URL2",be);
- Vserver beVm3 = createVserver("BE_URL3",be);
- Vserver beVm4 = createVserver("BE_URL4",be);
- Vserver beVm5 = createVserver("BE_URL5",be);
+ Vserver beVm1 = createVserver("BE_URL1", be);
+ Vserver beVm2 = createVserver("BE_URL2", be);
+ Vserver beVm3 = createVserver("BE_URL3", be);
+ Vserver beVm4 = createVserver("BE_URL4", be);
+ Vserver beVm5 = createVserver("BE_URL5", be);
vnf.addVserver(beVm1);
vnf.addVserver(beVm2);
vnf.addVserver(beVm4);
vnf.addVserver(beVm5);
- Vnfc fe = createVnfc("FE",null,"FE_Name");
+ Vnfc fe = createVnfc("FE", null, "FE_Name");
- Vserver feVm1 = createVserver("FE_URL1",fe);
- Vserver feVm2 = createVserver("FE_URL2",fe);
+ Vserver feVm1 = createVserver("FE_URL1", fe);
+ Vserver feVm2 = createVserver("FE_URL2", fe);
vnf.addVserver(feVm1);
vnf.addVserver(feVm2);
return new InventoryModel(vnf);
}
- private Vserver createVserver(String url,Vnfc vnfc) {
+ private Vserver createVserver(String url, Vnfc vnfc) {
Vserver vserver = new Vserver();
vserver.setUrl(url);
vserver.setVnfc(vnfc);
}
private VnfcDependencyModel readDependencyModel() {
- Vnfc smp = createVnfc("SMP","Active-Passive",null);
- Vnfc be = createVnfc("BE","Active-Active",null);
- Vnfc fe = createVnfc("FE","Active-Active",null);
+ Vnfc smp = createVnfc("SMP", "Active-Passive", null);
+ Vnfc be = createVnfc("BE", "Active-Active", null);
+ Vnfc fe = createVnfc("FE", "Active-Active", null);
Node smpNode = new Node(smp);
*=================================================================================
* Modifications Copyright 2018 IBM.
*=================================================================================
+* Modifications Copyright (C) 2019 AT&T Intellectual Property
+*=================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@Before
public void SetUp() {
- vnf=new Vnf();
+ vnf = new Vnf();
}
@Test
public void testGetVnfId() {
vnf.setVnfId("Z");
assertNotNull(vnf.getVnfId());
- assertEquals(vnf.getVnfId(),"Z");
+ assertEquals(vnf.getVnfId(), "Z");
}
@Test
public void testGetvnfType() {
vnf.setVnfType("A");
assertNotNull(vnf.getVnfType());
- assertEquals(vnf.getVnfType(),"A");
+ assertEquals(vnf.getVnfType(), "A");
}
@Test
public void testGetVnfVersion() {
vnf.setVnfVersion("1.0");
assertNotNull(vnf.getVnfVersion());
- assertEquals(vnf.getVnfVersion(),"1.0");
+ assertEquals(vnf.getVnfVersion(), "1.0");
}
@Test
List<Vserver> vservers = new LinkedList<>();
vnf.setVservers(vservers);
assertNotNull(vnf.getVservers());
- assertEquals(vnf.getVservers(),vservers);
-
+ assertEquals(vnf.getVservers(), vservers);
+
}
@Test
vnfc.setVnfcType("B");
vnfc.setResilienceType("RS1");
vnfc.setMandatory(true);
- List<Vserver> vserverList=new LinkedList<>();
+ List<Vserver> vserverList = new LinkedList<>();
Vserver vserver = new Vserver();
vserver.setId("V1");
vserver.setName("V1-Name");
vserverList.add(vserver);
vnfc.addVservers(vserverList);
vnf.setVservers(vserverList);
- assertTrue(vnf.getVnfcs()!=null);
+ assertTrue(vnf.getVnfcs() != null);
}
-
+
@Test
public void testGetSetIdentityUrl()
{
- vnf.setIdentityUrl("testIdentityUrl");
- assertEquals("testIdentityUrl", vnf.getIdentityUrl());
+ vnf.setIdentityUrl("testIdentityUrl");
+ assertEquals("testIdentityUrl", vnf.getIdentityUrl());
}
-
+
@Test
public void testAddVserver()
{
* ONAP : APPC
* ================================================================================
* Copyright (C) 2019 Ericsson
+ * ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public void testRetrieveLicenseModel() throws APPCException {
LicenseManagerPluginImpl lmImpl = new LicenseManagerPluginImpl();
lmImpl.setLicenseManager(licenseManagerMock);
- Mockito.doReturn(licenseModelMock).when(licenseManagerMock).retrieveLicenseModel(Mockito.anyString(), Mockito.anyString());
+ Mockito.doReturn(licenseModelMock).when(licenseManagerMock)
+ .retrieveLicenseModel(Mockito.anyString(), Mockito.anyString());
Map<String, String> params = new HashMap<>();
SvcLogicContext ctx = new SvcLogicContext();
lmImpl.retrieveLicenseModel(params, ctx);
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
@Override
public void storeYangModuleOnLeader(String yang, String moduleName) throws MDSALStoreException {
+ String msg;
try {
String leader = getLeaderNode();
- if (Constants.SELF.equals(leader)){
+ if (Constants.SELF.equals(leader)) {
logger.debug("Current node is a leader.");
- }else{
- logger.debug("Attempting to load yang module on Leader: " + leader );
+ } else {
+ logger.debug("Attempting to load yang module on Leader: " + leader);
String inputJson = createInputJson(yang, moduleName);
RestClientInvoker remoteClient = getRemoteClient(leader);
HttpResponse response = remoteClient.doPost(Constants.YANG_LOADER_PATH, inputJson);
}
}
} catch (APPCException e) {
- logger.error("Error loading Yang on Leader. Error message: " + e.getMessage());
- throw new MDSALStoreException("Error loading Yang on Leader. Error message: " + e.getMessage(), e);
+ msg = "Error loading Yang on Leader. Error message: " + e.getMessage();
+ logger.error(msg);
+ throw new MDSALStoreException(msg, e);
} catch (IOException e) {
- logger.error("Error reading response from remote client. Error message: " + e.getMessage());
- throw new MDSALStoreException("Error reading response from remote client. Error message: " + e.getMessage(), e);
+ msg = "Error reading response from remote client. Error message: " + e.getMessage();
+ logger.error(msg);
+ throw new MDSALStoreException(msg, e);
}
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(StoreYangInput.class, MixIn.class);
String inputJson = objectMapper.writer().withRootName("input").writeValueAsString(input);
- logger.debug("Input JSON :" + inputJson);
+ logger.debug("Input JSON: " + inputJson);
return inputJson;
} catch (JsonProcessingException e) {
- logger.error(String.format("Error creating JSON input using yang: %s. Error message: %s",yang ,e.getMessage()));
- throw new MDSALStoreException(String.format("Error creating JSON input using yang: %s. Error message: %s",yang ,e.getMessage()), e);
+ String msg = String.format("Error creating JSON input using yang: %s. Error message: %s",
+ yang, e.getMessage());
+ logger.error(msg);
+ throw new MDSALStoreException(msg, e);
}
}
if (remoteClientMap.containsKey(leader)) {
return remoteClientMap.get(leader);
} else {
+ String msg;
Configuration configuration = ConfigurationFactory.getConfiguration();
Properties properties = configuration.getProperties();
if (properties != null) {
try {
- URL configUrl = new URL(properties.getProperty(Constants.CONFIG_URL_PROPERTY, Constants.CONFIG_URL_DEFAULT));
+ URL configUrl =
+ new URL(properties.getProperty(Constants.CONFIG_URL_PROPERTY,
+ Constants.CONFIG_URL_DEFAULT));
String user = properties.getProperty(Constants.CONFIG_USER_PROPERTY);
String password = properties.getProperty(Constants.CONFIG_PASS_PROPERTY);
- RestClientInvoker remoteClient = getRestClientInvoker(new URL(configUrl.getProtocol(), leader, configUrl.getPort(), ""));
+ RestClientInvoker remoteClient =
+ getRestClientInvoker(new URL(configUrl.getProtocol(), leader, configUrl.getPort(), ""));
remoteClient.setAuthentication(user, password);
remoteClientMap.put(leader, remoteClient);
return remoteClient;
} catch (MalformedURLException e) {
- logger.error("Error initializing remote RestConf client: " + e.getMessage(), e);
- throw new MDSALStoreException("Error initializing Remote RestConf client: " + e.getMessage(), e);
+ msg = "Error initializing remote RestConf client: " + e.getMessage();
+ logger.error(msg, e);
+ throw new MDSALStoreException(msg, e);
}
} else {
- logger.error("Error initializing Remote RestConf client. Could not read appc properties");
- throw new MDSALStoreException("Error initializing Remote RestConf client. Could not read appc properties");
+ msg = "Error initializing remote RestConf client. Could not read appc properties";
+ logger.error(msg);
+ throw new MDSALStoreException(msg);
}
}
}
try {
String path = requestFormatter.buildPath(module, org.onap.appc.Constants.YANG_BASE_CONTAINER,
org.onap.appc.Constants.YANG_VNF_CONFIG_LIST, requestId, org.onap.appc.Constants.YANG_VNF_CONFIG);
- logger.debug("Configuration Path : " + path);
+ logger.debug("Configuration Path: " + path);
HttpResponse response = client.doPut(path, configJson);
int httpCode = response.getStatusLine().getStatusCode();
String respBody = IOUtils.toString(response.getEntity().getContent());
}
}
logger.error("Failed to load config JSON to MD SAL store. " + errorMessage.toString());
- throw new MDSALStoreException("Failed to load config JSON to MD SAL store. Error Message: " + errorMessage.toString());
+ throw new MDSALStoreException("Failed to load config JSON to MD SAL store. Error Message: "
+ + errorMessage.toString());
} catch (IOException e) {
logger.error("Failed to process error response from RestConf: " + e.getMessage());
throw new MDSALStoreException("Failed to process RestConf response. Error Message: " + e.toString(), e);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, Constants.MANIFEST_VALUE_VERSION);
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME), bundleInfo.getName());
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME), bundleInfo.getName());
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION), bundleInfo.getDescription());
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION), Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION);
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION), String.valueOf(bundleInfo.getVersion()));
- manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT), Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT);
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_NAME),
+ bundleInfo.getName());
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_SYMBOLIC_NAME),
+ bundleInfo.getName());
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_DESCRIPTION),
+ bundleInfo.getDescription());
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_MANIFEST_VERSION),
+ Constants.MANIFEST_VALUE_BUNDLE_MAN_VERSION);
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_VERSION),
+ String.valueOf(bundleInfo.getVersion()));
+ manifest.getMainAttributes().put(new Attributes.Name(Constants.MANIFEST_ATTR_BUNDLE_BLUEPRINT),
+ Constants.MANIFEST_VALUE_BUNDLE_BLUEPRINT);
byte[] retunValue;
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) {
+ JarOutputStream jarOutputStream = new JarOutputStream(outputStream, manifest)) {
jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/"));
jarOutputStream.putNextEntry(new JarEntry("META-INF/yang/" + bundleInfo.getName() + ".yang"));
jarOutputStream.write(yang.getBytes());
retunValue = outputStream.toByteArray();
} catch (Exception e) {
logger.error("Error creating bundle jar: " + bundleInfo.getName() + ". Error message: " + e.getMessage());
- throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(), e);
+ throw new MDSALStoreException("Error creating bundle jar: " + bundleInfo.getName() + " " + e.getMessage(),
+ e);
}
return retunValue;
}
int httpCode = response.getStatusLine().getStatusCode();
String respBody = IOUtils.toString(response.getEntity().getContent());
logger.debug(String.format("Get node status returned Code: %s. Response: %s ", httpCode, respBody));
- if (httpCode == 200 && mapper.readTree(respBody).get(Constants.JSON_RESPONSE_VALUE) !=null ) {
+ if (httpCode == 200 && mapper.readTree(respBody).get(Constants.JSON_RESPONSE_VALUE) != null) {
JsonNode responseValue = mapper.readTree(respBody).get(Constants.JSON_RESPONSE_VALUE);
String leaderShard = responseValue.get("Leader").asText();
if (shardName.equals(leaderShard)) {
String[] peers = responseValue.get("PeerAddresses").asText().split(",");
for (String peer : peers) {
if (peer.trim().startsWith(leaderShard)) {
- String leader = peer.substring(peer.indexOf('@') + 1, peer.indexOf(':', peer.indexOf('@')));
+ String leader =
+ peer.substring(peer.indexOf('@') + 1, peer.indexOf(':', peer.indexOf('@')));
logger.debug(String.format("Node %s is a leader", leader));
return leader;
}
throw new MDSALStoreException("Error while retrieving leader node.");
}
} catch (IOException | APPCException e) {
- logger.error(String.format("Error while retrieving leader Node. Error message : %s ", e.getMessage()), e);
+ logger.error(String.format("Error while retrieving leader Node. Error message: %s ", e.getMessage()), e);
throw new MDSALStoreException(e);
}
}
JsonNode responseValue = mapper.readTree(respBody).get(Constants.JSON_RESPONSE_VALUE);
if (responseValue != null && responseValue.get(Constants.JSON_RESPONSE_MEMBER_NAME) != null) {
String name = responseValue.get(Constants.JSON_RESPONSE_MEMBER_NAME).asText();
- logger.debug("Node name : " + name);
+ logger.debug("Node name: " + name);
return name;
- }else{
- logger.error(String.format("Error while retrieving node name from response. Response body: %s.", respBody));
- throw new MDSALStoreException(String.format("Error while retrieving node name from response. Response body: %s.", respBody));
+ } else {
+ String msg = String.format("Error while retrieving node name from response. Response body: %s.",
+ respBody);
+ logger.error(msg);
+ throw new MDSALStoreException(msg);
}
} else {
- logger.error(String.format("Error while retrieving node name. Error code: %s. Error response: %s.", httpCode, respBody));
- throw new MDSALStoreException(String.format("Error while retrieving node name. Error code: %s. Error response: %s.", httpCode, respBody));
+ String msg = String.format("Error while retrieving node name. Error code: %s. Error response: %s.",
+ httpCode, respBody);
+ logger.error(msg);
+ throw new MDSALStoreException(msg);
}
} catch (IOException | APPCException e) {
- logger.error("Error while getting node name " + e.getMessage(), e);
+ logger.error("Error while getting node name: " + e.getMessage(), e);
throw new MDSALStoreException(e);
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import org.onap.appc.mdsal.impl.Constants;
/**
- * Creates request url path for config actions based on parameter like module name , container-name and sub modules if any.
+ * Creates request url path for config actions based on parameter like module name, container name,
+ * and sub modules if any.
*/
public class ConfigOperationRequestFormatter {
* @param subModules - sub module /container names as string in varargs ( String ) format
* @return - resultant path in String format
*/
- public String buildPath(String module, String containerName , String... subModules ) {
-
- StringBuilder path = new StringBuilder( Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module + ":" + containerName + Constants.URL_BACKSLASH);
- if(subModules.length >0){
- for(String subModule : subModules){
+ public String buildPath(String module, String containerName, String... subModules) {
+ StringBuilder path =
+ new StringBuilder(Constants.CONFIG_PATH + Constants.URL_BACKSLASH + module
+ + ":" + containerName + Constants.URL_BACKSLASH);
+ if (subModules.length > 0) {
+ for (String subModule : subModules) {
path.append(subModule);
path.append("/");
}
}
- return path.toString();
+ return path.toString();
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
* MDSALStore Tests
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest({FrameworkUtil.class,BundleContext.class,ServiceReference.class,
- BundleReference.class,Bundle.class,Filter.class,BundleListener.class,InvalidSyntaxException.class,
- BundleException.class,FrameworkListener.class,ServiceRegistration.class,ServiceListener.class,
+@PrepareForTest({FrameworkUtil.class, BundleContext.class, ServiceReference.class,
+ BundleReference.class, Bundle.class, Filter.class, BundleListener.class, InvalidSyntaxException.class,
+ BundleException.class, FrameworkListener.class, ServiceRegistration.class, ServiceListener.class,
Version.class})
public class MDSALStoreTest {
* ONAP : APPC
* ================================================================================
* Copyright (C) 2019 Ericsson
+ * ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@PrepareForTest(FrameworkUtil.class)
public class MDSALStoreImplTest {
- private final BundleContext bundleContext= Mockito.mock(BundleContext.class);
- private final Bundle bundleService=Mockito.mock(Bundle.class);
+ private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
+ private final Bundle bundleService = Mockito.mock(Bundle.class);
private MDSALStoreImpl mdsalStore;
@Rule
}
@Test
- public void testStoreYangModuleOnLeader() throws MDSALStoreException, APPCException, IllegalStateException, IOException {
+ public void testStoreYangModuleOnLeader()
+ throws MDSALStoreException, APPCException, IllegalStateException, IOException {
RestClientInvoker mockInvoker = Mockito.mock(RestClientInvoker.class);
Whitebox.setInternalState(mdsalStore, "client", mockInvoker);
HttpResponse mockResponse = Mockito.mock(HttpResponse.class);
Mockito.doReturn(mockStatusLine).when(mockResponse).getStatusLine();
Mockito.doReturn(200).when(mockStatusLine).getStatusCode();
HttpResponse mockLeaderResponse = Mockito.mock(HttpResponse.class);
- Mockito.doReturn(mockLeaderResponse).when(mockInvoker).doGet(String.format(Constants.GET_NODE_STATUS_PATH_FORMAT, "NodeName-shard-default-config"));
+ Mockito.doReturn(mockLeaderResponse).when(mockInvoker)
+ .doGet(String.format(Constants.GET_NODE_STATUS_PATH_FORMAT, "NodeName-shard-default-config"));
String httpLeaderString = "{\"value\":{\"Leader\":\"NodeName-shard-default-config\"}}";
InputStream isLeader = new ByteArrayInputStream(httpLeaderString.getBytes(Charset.defaultCharset()));
HttpEntity mockLeaderEntity = Mockito.mock(HttpEntity.class);
mdsalStore.storeYangModuleOnLeader("", "");
Mockito.verify(mockLogger).debug("Current node is a leader.");
}
-
+
@Test
- public void testStoreYangModuleOnLeaderNotLeader() throws MDSALStoreException, APPCException, IllegalStateException, IOException {
+ public void testStoreYangModuleOnLeaderNotLeader()
+ throws MDSALStoreException, APPCException, IllegalStateException, IOException {
RestClientInvoker mockInvoker = Mockito.mock(RestClientInvoker.class);
Whitebox.setInternalState(mdsalStore, "client", mockInvoker);
HttpResponse mockResponse = Mockito.mock(HttpResponse.class);
Mockito.doReturn(mockStatusLine).when(mockResponse).getStatusLine();
Mockito.doReturn(200).when(mockStatusLine).getStatusCode();
HttpResponse mockLeaderResponse = Mockito.mock(HttpResponse.class);
- Mockito.doReturn(mockLeaderResponse).when(mockInvoker).doGet(String.format(Constants.GET_NODE_STATUS_PATH_FORMAT, "NodeName-shard-default-config"));
- String httpLeaderString = "{\"value\":{\"Leader\":\"OtherShardName\",\"PeerAddresses\":\"OtherShardName@adf:a\"}}";
+ Mockito.doReturn(mockLeaderResponse).when(mockInvoker)
+ .doGet(String.format(Constants.GET_NODE_STATUS_PATH_FORMAT, "NodeName-shard-default-config"));
+ String httpLeaderString =
+ "{\"value\":{\"Leader\":\"OtherShardName\",\"PeerAddresses\":\"OtherShardName@adf:a\"}}";
InputStream isLeader = new ByteArrayInputStream(httpLeaderString.getBytes(Charset.defaultCharset()));
HttpEntity mockLeaderEntity = Mockito.mock(HttpEntity.class);
Mockito.doReturn(isLeader).when(mockLeaderEntity).getContent();
}
@Test
- public void testStoreJsonRestconfResponse() throws MDSALStoreException, APPCException, IllegalStateException, IOException {
+ public void testStoreJsonRestconfResponse()
+ throws MDSALStoreException, APPCException, IllegalStateException, IOException {
RestClientInvoker mockInvoker = Mockito.mock(RestClientInvoker.class);
Whitebox.setInternalState(mdsalStore, "client", mockInvoker);
HttpResponse mockResponse = Mockito.mock(HttpResponse.class);
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public NetconfClientPluginImpl() {
BundleContext bctx = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
- ServiceReference<NetconfClientFactory> srefNetconfClientFactory = bctx
- .getServiceReference(NetconfClientFactory.class);
+ ServiceReference<NetconfClientFactory> srefNetconfClientFactory =
+ bctx.getServiceReference(NetconfClientFactory.class);
clientFactory = bctx.getService(srefNetconfClientFactory);
}
}
public void configure(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
-
try {
- // by default, it uses the jsch Netconf Adapter implementation by calling getNetconfClient(NetconfClientType.SSH).
+ // by default, it uses the jsch Netconf Adapter implementation by calling
+ // getNetconfClient(NetconfClientType.SSH).
NetconfClient client = clientFactory.getNetconfClient(NetconfClientType.SSH);
connect(params, client);
} catch (Exception e) {
private void connect(Map<String, String> params, NetconfClient client) throws APPCException {
try {
- NetconfConnectionDetails connectionDetails = mapper
- .readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
+ NetconfConnectionDetails connectionDetails =
+ mapper.readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
String netconfMessage = params.get("file-content");
client.connect(connectionDetails);
client.configure(netconfMessage);
public void operationStateValidation(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
if (logger.isTraceEnabled()) {
logger.trace("Entering to operationStateValidation with params = " + ObjectUtils.toString(params)
- + ", SvcLogicContext = " + ObjectUtils.toString(ctx));
+ + ", SvcLogicContext = " + ObjectUtils.toString(ctx));
}
try {
String paramName = Constants.VNF_TYPE_FIELD_NAME;
//get connectionDetails
String connectionDetailsStr = params.get(Constants.CONNECTION_DETAILS_FIELD_NAME);
NetconfConnectionDetails connectionDetails =
- resolveConnectionDetails(ctx, vnfType, vnfHostIpAddress, connectionDetailsStr);
+ resolveConnectionDetails(ctx, vnfType, vnfHostIpAddress, connectionDetailsStr);
if (connectionDetails == null) {
throw new IllegalStateException("missing connectionDetails for VnfType:" + vnfType.name());
}
//get operationsStateNetconfMessage
- OperationalStateValidator operationalStateValidator = OperationalStateValidatorFactory
- .getOperationalStateValidator(vnfType);
+ OperationalStateValidator operationalStateValidator =
+ OperationalStateValidatorFactory.getOperationalStateValidator(vnfType);
String configurationFileName = operationalStateValidator.getConfigurationFileName();
String operationsStateNetconfMessage = null;
if (!StringUtils.isEmpty(configurationFileName)) {
}
private NetconfConnectionDetails resolveConnectionDetails(SvcLogicContext ctx, VnfType vnfType,
- String vnfHostIpAddress, String connectionDetailsStr) throws APPCException, IOException {
-
+ String vnfHostIpAddress, String connectionDetailsStr) throws APPCException, IOException {
NetconfConnectionDetails connectionDetails;
if (StringUtils.isEmpty(connectionDetailsStr)) {
connectionDetails = retrieveConnectionDetails(vnfType);
@Override
public void backupConfiguration(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
-
NetconfClient client = null;
try {
logger.debug("Entered backup to DEVICE_INTERFACE_LOG");
client = clientFactory.getNetconfClient(NetconfClientType.SSH);
//get connection details
- NetconfConnectionDetails connectionDetails = mapper
- .readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
+ NetconfConnectionDetails connectionDetails =
+ mapper.readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
//connect the client and get configuration
client.connect(connectionDetails);
String configuration = client.getConfiguration();
NetconfClientFactory clientFact = (NetconfClientFactory) bctx.getService(sref);
client = clientFact.getNetconfClient(NetconfClientType.SSH);
//get connection details
- NetconfConnectionDetails connectionDetails = mapper
- .readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
+ NetconfConnectionDetails connectionDetails =
+ mapper.readValue(params.get(CONNECTION_DETAILS_PARAM), NetconfConnectionDetails.class);
//connect the client and get configuration
client.connect(connectionDetails);
String configuration = client.getConfiguration();
}
}
-
@Override
public void getRunningConfig(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
NetconfClient client = null;
connectionDetails.setUsername(params.get("user-name"));
connectionDetails.setPassword(params.get("password"));
connectionDetails.setPort(
- !("".equalsIgnoreCase(params.get("port-number"))) ? Integer.parseInt(params.get("port-number"))
- : NetconfConnectionDetails.DEFAULT_PORT);
+ !("".equalsIgnoreCase(params.get("port-number")))
+ ? Integer.parseInt(params.get("port-number"))
+ : NetconfConnectionDetails.DEFAULT_PORT);
//connect the client and get configuration
client.connect(connectionDetails);
String configuration = client.getConfiguration();
}
private String getCurrentDateTime() {
-
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
if (!dao.retrieveNetconfConnectionDetails(vnfType.getFamilyType().name(), connectionDetails)) {
logger.error("Missing configuration for " + vnfType.getFamilyType().name());
throw new APPCException("Missing configuration for " + vnfType.getFamilyType().name() + " in "
- + Constants.DEVICE_AUTHENTICATION_TABLE_NAME);
+ + Constants.DEVICE_AUTHENTICATION_TABLE_NAME);
}
return connectionDetails;
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
private final NetconfClientJschMock jschClient = new NetconfClientJschMock();
@Override
- public NetconfClient getNetconfClient(NetconfClientType type){
+ public NetconfClient getNetconfClient(NetconfClientType type) {
return jschClient;
}
}
-
-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import static org.powermock.api.mockito.PowerMockito.when;
-
@RunWith(PowerMockRunner.class)
@PrepareForTest({OperationalStateValidatorFactory.class, FrameworkUtil.class, ObjectMapper.class})
int port = 8080;
String username = "test";
String password = "test";
- String connectionDetails = "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}";
- String fileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "\t<get-config>\n" +
- "\t\t<source>\n" +
- "\t\t\t<running/>\n" +
- "\t\t </source>\n" +
- "\t</get-config>\n" +
- "</rpc>'";
- String operationalState = "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- " <get>\n" +
- " <filter>\n" +
- " <ManagedElement xmlns=\"urn:org:onap:appc:Test\">\n" +
- " <VnfFunction xmlns=\"urn:org:openecomop:appc:Test\">\n" +
- " <ProcessorManagement>\n" +
- " <MatedPair>\n" +
- " <operationalState/>\n" +
- " <PayloadProcessor>\n" +
- " <operationalState/>\n" +
- " </PayloadProcessor>\n" +
- " </MatedPair>\n" +
- " <SystemController>\n" +
- " <operationalState/>\n" +
- " </SystemController>\n" +
- " </ProcessorManagement>\n" +
- " </VnfFunction>\n" +
- " </ManagedElement>\n" +
- " </filter>\n" +
- " </get>\n" +
- "</rpc>\n";
+ String connectionDetails =
+ "{\"host\":\"" + host + "\",\"port\":" + port + ",\"username\":\"" + username
+ + "\",\"password\":\"" + password + "\",\"capabilities\":null,\"additionalProperties\":null}";
+ String fileContent =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ + "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "\t<get-config>\n"
+ + "\t\t<source>\n"
+ + "\t\t\t<running/>\n"
+ + "\t\t </source>\n"
+ + "\t</get-config>\n"
+ + "</rpc>'";
+ String operationalState =
+ "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + " <get>\n"
+ + " <filter>\n"
+ + " <ManagedElement xmlns=\"urn:org:onap:appc:Test\">\n"
+ + " <VnfFunction xmlns=\"urn:org:openecomop:appc:Test\">\n"
+ + " <ProcessorManagement>\n"
+ + " <MatedPair>\n"
+ + " <operationalState/>\n"
+ + " <PayloadProcessor>\n"
+ + " <operationalState/>\n"
+ + " </PayloadProcessor>\n"
+ + " </MatedPair>\n"
+ + " <SystemController>\n"
+ + " <operationalState/>\n"
+ + " </SystemController>\n"
+ + " </ProcessorManagement>\n"
+ + " </VnfFunction>\n"
+ + " </ManagedElement>\n"
+ + " </filter>\n"
+ + " </get>\n"
+ + "</rpc>\n";
@Before
Assert.assertEquals("wrong password", password, client.getLastConnectionDetails().getPassword());
Assert.assertFalse(client.isConnection());
} catch (Exception e) {
- Assert.fail("failed with because of " + e.getCause());
+ Assert.fail("failed because of " + e.getCause());
}
}
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
netconfClientPlugin.operationStateValidation(params, ctx);
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
substituteMapper(true);
try {
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
ObjectMapper mapper = PowerMockito.mock(ObjectMapper.class);
final NetconfConnectionDetails netconfConnectionDetails = null;
when(mapper.readValue(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(netconfConnectionDetails);
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
try {
netconfClientPlugin.operationStateValidation(params, ctx);
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
netconfClientPlugin.operationStateValidation(params, ctx);
validatorMock.setConfigurationFileName("VnfGetRunningConfig");
PowerMockito.mockStatic(OperationalStateValidatorFactory.class);
- when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class))).thenReturn(validatorMock);
+ when(OperationalStateValidatorFactory.getOperationalStateValidator(Matchers.any(VnfType.class)))
+ .thenReturn(validatorMock);
netconfClientPlugin.operationStateValidation(params, ctx);
Assert.assertEquals("wrong host", connectionDetails1.getHost(), connectionDetailsActual.getHost());
Assert.assertEquals("wrong password", connectionDetails1.getPassword(), connectionDetailsActual.getPassword());
Assert.assertEquals("wrong port", connectionDetails1.getPort(), connectionDetailsActual.getPort());
- Assert.assertEquals("wrong usename", connectionDetails1.getUsername(), connectionDetailsActual.getUsername());
+ Assert.assertEquals("wrong username", connectionDetails1.getUsername(), connectionDetailsActual.getUsername());
}
DAOServiceMock daoServiceMock = (DAOServiceMock) dao;
daoServiceMock.setConfigFile(fileContent);
- Assert.assertEquals("wrong config in a database", fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig"));
+ Assert.assertEquals("wrong config in a database",
+ fileContent, netconfClientPlugin.retrieveConfigurationFileContent("VnfGetRunningConfig"));
}
private ConnectionDetails getConnectionDetails() {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
int port = 8080;
String username = "test";
String password = "test";
- String configContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
- "\t<get-config>\n" +
- "\t\t<source>\n" +
- "\t\t\t<running/>\n" +
- "\t\t </source>\n" +
- "\t</get-config>\n" +
- "</rpc>'";
-
+ String configContent =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ + "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+ + "\t<get-config>\n"
+ + "\t\t<source>\n"
+ + "\t\t\t<running/>\n"
+ + "\t\t </source>\n"
+ + "\t</get-config>\n"
+ + "</rpc>'";
@Test
public void testRetrieveDSConfiguration() throws Exception {
SvcLogicContext ctx = new SvcLogicContext();
netconfDBPlugin.retrieveVMDSConfiguration(params, ctx);
- Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result", "success", ctx.getAttribute("retrieveVMDSConfiguration_Result"));
+ Assert.assertEquals("lack of success of retrieveVMDSConfiguration_Result",
+ "success", ctx.getAttribute("retrieveVMDSConfiguration_Result"));
Assert.assertEquals("wrong entity", "VNF", ctx.getAttribute("entity"));
assertConnectionDetails(ctx, host);
}
}
}
-
@Test
public void testRetrieveVMDSConfigurationNegativeJsonProcessingException() throws Exception {
}
}
-
@Test
public void testRetrieveConnectionDetailsNegativeMissingConfiguration() throws Exception {
init();
private void assertConnectionDetails(SvcLogicContext ctx, String host) throws IOException {
String sConnectionDetails = ctx.getAttribute("connection-details");
- NetconfConnectionDetails connectionDetails = new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class);
+ NetconfConnectionDetails connectionDetails =
+ new ObjectMapper().readValue(sConnectionDetails, NetconfConnectionDetails.class);
Assert.assertEquals(host, connectionDetails.getHost());
Assert.assertEquals(port, connectionDetails.getPort());
Assert.assertEquals(username, connectionDetails.getUsername());
daoMock = (DAOServiceMock) daoService;
daoMock.setConfigFile(configContent);
daoMock.setConnection(getConnectionDetails());
-
}
private ConnectionDetails getConnectionDetails() {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
- * ================================================================================
- * Modifications (C) 2019 Ericsson
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
private SshAdapter sshAdapter;
+ /**
+ * Set sshAdapter.
+ * <p>Used through blueprint.
+ * @param sshAdapter the SshAdapter
+ */
public void setSshAdapter(SshAdapter sshAdapter) {
this.sshAdapter = sshAdapter;
}
SshConnectionDetails connectionDetails = resolveConnectionDetails(params.get(PARAM_IN_connection_details));
String command = params.get(PARAM_IN_command);
logger.debug("=> Connecting to SSH server...");
- SshConnection sshConnection = sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(), connectionDetails.getUsername(), connectionDetails.getPassword());
+ SshConnection sshConnection =
+ sshAdapter.getConnection(connectionDetails.getHost(), connectionDetails.getPort(),
+ connectionDetails.getUsername(), connectionDetails.getPassword());
sshConnection.connect();
try {
logger.debug("=> Connected to SSH server...");
public void execWithStatusCheck(Map<String, String> params, SvcLogicContext ctx) throws APPCException {
exec(params, ctx);
int status = Integer.parseInt(ctx.getAttribute(PARAM_OUT_status));
- if(status != DEF_SUCCESS_STATUS) {
+ if (status != DEF_SUCCESS_STATUS) {
StringBuilder errmsg = new StringBuilder();
errmsg.append("SSH command returned error status [").append(status).append(']');
String stderr = ctx.getAttribute(PARAM_OUT_stderr);
- if((stderr != null) && !stderr.isEmpty()) {
+ if ((stderr != null) && !stderr.isEmpty()) {
errmsg.append(". Error: [").append(stderr).append(']');
}
throw new APPCException(errmsg.toString());
* ONAP : APPC
* ================================================================================
* Copyright (C) 2019 Ericsson
+ * ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
public void testRetrieveConnectionDetails() throws APPCException {
SshDBPluginImpl impl = new SshDBPluginImpl();
SshDataAccessService dataAccessServiceMock = Mockito.mock(SshDataAccessService.class);
- Mockito.doReturn(true).when(dataAccessServiceMock).retrieveConnectionDetails(Mockito.anyString(),
- Mockito.any(SshConnectionDetails.class));
+ Mockito.doReturn(true).when(dataAccessServiceMock)
+ .retrieveConnectionDetails(Mockito.anyString(), Mockito.any(SshConnectionDetails.class));
impl.setDataAccessService(dataAccessServiceMock);
Map<String, String> params = new HashMap<>();
SvcLogicContext ctx = new SvcLogicContext();
public void testRetrieveConnectionDetailsSshDataAccessException() throws APPCException {
SshDBPluginImpl impl = new SshDBPluginImpl();
SshDataAccessService dataAccessServiceMock = Mockito.mock(SshDataAccessService.class);
- Mockito.doThrow(new SshDataAccessException()).when(dataAccessServiceMock).retrieveConnectionDetails(Mockito.anyString(),
- Mockito.any(SshConnectionDetails.class));
+ Mockito.doThrow(new SshDataAccessException()).when(dataAccessServiceMock)
+ .retrieveConnectionDetails(Mockito.anyString(), Mockito.any(SshConnectionDetails.class));
impl.setDataAccessService(dataAccessServiceMock);
Map<String, String> params = new HashMap<>();
SvcLogicContext ctx = new SvcLogicContext();
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.apache.commons.lang.ObjectUtils;
+import org.onap.appc.domainmodel.lcm.CommonHeader;
import org.onap.appc.exceptions.APPCException;
import org.onap.appc.executionqueue.ExecutionQueueService;
import org.onap.appc.executor.CommandExecutor;
* <p>Used through blueprint.
*/
public void initialize() {
- logger.info("initialization started of CommandExecutorImpl");
+ logger.info("initialization of CommandExecutorImpl started");
}
public void setExecutionQueueService(ExecutionQueueService executionQueueService) {
*/
@Override
public void executeCommand (CommandExecutorInput commandExecutorInput) throws APPCException{
- logger.trace("Entering to executeCommand with CommandExecutorInput = "+ ObjectUtils.toString(commandExecutorInput));
+ logger.trace("Entering executeCommand with CommandExecutorInput = "
+ + ObjectUtils.toString(commandExecutorInput));
CommandTask commandTask;
try {
- commandTask= getCommandTask(requestHandler, workflowManager);
+ commandTask = getCommandTask(requestHandler, workflowManager);
commandTask.setCommandRequest(new CommandRequest(commandExecutorInput));
long remainingTTL = getRemainingTTL(commandTask.getCommandRequest());
- logger.trace("Queuing request with CommandRequest = "+ ObjectUtils.toString(commandTask.getCommandRequest()));
- executionQueueService.putMessage(commandTask,remainingTTL, TimeUnit.MILLISECONDS);
+ logger.trace("Queuing request with CommandRequest = "
+ + ObjectUtils.toString(commandTask.getCommandRequest()));
+ executionQueueService.putMessage(commandTask, remainingTTL, TimeUnit.MILLISECONDS);
} catch (Exception e) {
- logger.error("Exception: "+e.getMessage());
+ logger.error("Exception: " + e.getMessage());
throw new APPCException(e);
}
logger.trace("Exiting from executeCommand");
}
private long getRemainingTTL(CommandRequest request) {
- Date requestTimestamp = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getTimeStamp();
- int ttl = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getFlags().getTtl();
+ CommonHeader hdr = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader();
+ Date requestTimestamp = hdr.getTimeStamp();
+ int ttl = hdr.getFlags().getTtl();
return ttl*1000 + requestTimestamp.getTime() - System.currentTimeMillis();
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.att.eelf.configuration.EELFManager;
import java.net.InetAddress;
import java.util.UUID;
+import org.onap.appc.domainmodel.lcm.CommonHeader;
+import org.onap.appc.domainmodel.lcm.RequestContext;
+import org.onap.appc.domainmodel.lcm.ResponseContext;
+import org.onap.appc.domainmodel.lcm.RuntimeContext;
import org.onap.appc.domainmodel.lcm.Status;
import org.onap.appc.domainmodel.lcm.VNFOperation;
import org.onap.appc.executor.impl.objects.CommandRequest;
import org.onap.appc.logging.LoggingConstants;
import org.onap.appc.requesthandler.RequestHandler;
-import org.onap.appc.domainmodel.lcm.RuntimeContext;
import org.onap.appc.workflow.WorkFlowManager;
import org.onap.appc.workflow.objects.WorkflowRequest;
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
+import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.slf4j.MDC;
-
/**
* This abstract class is base class for all Command tasks. All command task must inherit this class.
*/
this.requestHandler = requestHandler;
}
- public CommandTask(RequestHandler requestHandler,
- WorkFlowManager workflowManager){
+ public CommandTask(RequestHandler requestHandler, WorkFlowManager workflowManager) {
this.requestHandler = requestHandler;
this.workflowManager = workflowManager;
getAAIservice();
@Override
public void run() {
- logger.debug("Starting execution of command :" + commandRequest);
+ logger.debug("Starting execution of command: " + commandRequest);
setInitialLogProperties(commandRequest);
final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
WorkflowRequest workflowRequest = new WorkflowRequest();
- workflowRequest.setRequestContext(runtimeContext.getRequestContext());
- workflowRequest.setResponseContext(runtimeContext.getResponseContext());
+ final RequestContext reqContext = runtimeContext.getRequestContext();
+ workflowRequest.setRequestContext(reqContext);
+ final ResponseContext respContext = runtimeContext.getResponseContext();
+ workflowRequest.setResponseContext(respContext);
workflowRequest.setVnfContext(runtimeContext.getVnfContext());
- logger.debug("Executing workflow :" + workflowRequest);
+ logger.debug("Executing workflow: " + workflowRequest);
workflowManager.executeWorkflow(workflowRequest);
- logger.debug("Completed execution workflow with response:"+ commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ logger.debug("Completed execution workflow with response: " + respContext);
try {
- if (VNFOperation.Terminate == commandRequest.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction())
+ if (VNFOperation.Terminate == reqContext.getAction())
updateAAIForTerminate(commandRequest);
} catch (AAIServiceException e) {
logger.error("Exception = " + e);
Status updatedStatus = new Status();
updatedStatus.setCode(401);
updatedStatus.setMessage("Failed to update VNF status in A&AI");
- commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(updatedStatus);
+ respContext.setStatus(updatedStatus);
throw new RuntimeException(e);
- }finally {
- requestHandler.onRequestExecutionEnd(commandRequest.getCommandExecutorInput().getRuntimeContext());
+ } finally {
+ requestHandler.onRequestExecutionEnd(runtimeContext);
clearRequestLogProperties();
}
}
private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
- final int statusCode = commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
+ final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
+ final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
- logger.debug("Workflow Execution Status = "+ statusCode);
+ logger.debug("Workflow Execution Status = " + statusCode);
if (statusCode == 100 || statusCode == 400) {
+ String id = runtimeContext.getVnfContext().getId();
SvcLogicContext ctx = new SvcLogicContext();
- ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
- deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(),
- ctx.getAttribute("vnf.resource-version"));
+ ctx = getVnfdata(id, "vnf", ctx);
+ deleteGenericVnfData(id, ctx.getAttribute("vnf.resource-version"));
}
}
- private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
- String key="generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
+ private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) {
+ String key = "generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
logger.debug("inside getVnfdata=== " + key);
try {
- SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
- if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
+ SvcLogicResource.QueryStatus response =
+ aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
+ if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
logger.warn("VNF " + vnf_id + " not found while updating A&AI");
throw new RuntimeException("VNF not found for vnf_id = " + vnf_id);
- }
- else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
+ } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
}
logger.info("AAIResponse: " + response.toString());
private void setInitialLogProperties(CommandRequest request) {
- String reqId = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId();
+ RequestContext reqContext = request.getCommandExecutorInput().getRuntimeContext().getRequestContext();
+ CommonHeader reqHdr = reqContext.getCommonHeader();
+ String reqId = reqHdr.getRequestId();
try {
MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
//reaching here without exception means existing RequestId is
- //valid UUID as per ECOMP logging standards
+ //valid UUID as per ONAP logging standards
} catch (Exception e) {
String reqIdUUID = UUID.randomUUID().toString();
MDC.put(Configuration.MDC_KEY_REQUEST_ID, reqIdUUID);
logger.info("Replaced invalid requestID of " + reqId + ". New value is " + reqIdUUID + ".");
}
- if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null) {
- MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
- MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
- MDC.put(Configuration.MDC_SERVICE_NAME,
- request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
+ String svcInstanceId = reqContext.getActionIdentifiers().getServiceInstanceId();
+ if (svcInstanceId != null) {
+ MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, svcInstanceId);
+ MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, reqHdr.getOriginatorId());
+ MDC.put(Configuration.MDC_SERVICE_NAME, reqContext.getAction().name());
}
try {
MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
- MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instance deploying
+ MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // confine instance_UUID generation to APPC-instance deployment
}
- private void clearRequestLogProperties()
- {
+ private void clearRequestLogProperties() {
try {
MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
MDC.remove(Configuration.MDC_SERVICE_INSTANCE_ID);
AAIRequest request = aaiService.getRequestFromResource("generic-vnf");
request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
response = aaiService.delete(request, resourceVersion);
- } catch(AAIServiceException aaiexc) {
+ } catch (AAIServiceException aaiexc) {
throw aaiexc;
} catch (Exception exc) {
logger.warn("deleteGenericVnfData", exc);
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
+ *
* ============LICENSE_END=========================================================
*/
package org.onap.appc.executor.impl;
-/**
- *
- */
-
import org.junit.Assert;
import org.junit.Before;
public class TestCommandExecutor {
- private static final String API_VERSION= "2.0.0";
- private static final String ORIGINATOR_ID= "1";
+ private static final String API_VERSION = "2.0.0";
+ private static final String ORIGINATOR_ID = "1";
private CommandExecutorImpl commandExecutor;
private Date timeStamp = new Date();
private String requestId = "1";
- private CommandExecutorInput commandExecutorInputConfigure = pouplateCommandExecutorInput("FIREWALL", 30000, "1.0",
- timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure,"15","") ;
- private CommandExecutorInput commandExecutorInputSync = pouplateCommandExecutorInput("FIREWALL", 30, "1.0",
- timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync,"15","") ;
+ private CommandExecutorInput commandExecutorInputConfigure = populateCommandExecutorInput("FIREWALL", 30000, "1.0",
+ timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Configure, "15", "");
+ private CommandExecutorInput commandExecutorInputSync = populateCommandExecutorInput("FIREWALL", 30, "1.0",
+ timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "2", VNFOperation.Sync, "15", "");
private CommandTask commandTask;
@Before
- public void init()throws Exception {
- requestHandler= Mockito.mock(RequestHandler.class);
- workflowManager= Mockito.mock(WorkFlowManager.class);
+ public void init() throws Exception {
+ requestHandler = Mockito.mock(RequestHandler.class);
+ workflowManager = Mockito.mock(WorkFlowManager.class);
executionQueueService = Mockito.mock(ExecutionQueueService.class);
commandExecutor.initialize();
commandTask = Mockito.mock(CommandTask.class);
Mockito.when(commandTask.getCommandRequest()).thenReturn(new CommandRequest(commandExecutorInputConfigure));
- PowerMockito.whenNew(CommandTask.class).withParameterTypes(RequestHandler.class,WorkFlowManager.class).withArguments(requestHandler,workflowManager).thenReturn(commandTask);
+ PowerMockito.whenNew(CommandTask.class)
+ .withParameterTypes(RequestHandler.class, WorkFlowManager.class)
+ .withArguments(requestHandler, workflowManager)
+ .thenReturn(commandTask);
}
@Test
}
@Test(expected = APPCException.class)
- public void testNegativeFlow_LCM() throws APPCException{
- Mockito.doThrow(new APPCException("Failed to enqueue request")).when(executionQueueService).putMessage((Runnable) Mockito.anyObject(),Mockito.anyLong(),(TimeUnit) Mockito.anyObject());
+ public void testNegativeFlow_LCM() throws APPCException {
+ Mockito.doThrow(new APPCException("Failed to enqueue request"))
+ .when(executionQueueService)
+ .putMessage((Runnable) Mockito.anyObject(), Mockito.anyLong(), (TimeUnit) Mockito.anyObject());
commandExecutor.executeCommand(commandExecutorInputSync);
}
- private CommandExecutorInput pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){
+ private CommandExecutorInput populateCommandExecutorInput(String vnfType, int ttl, String vnfVersion,
+ Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID,
+ VNFOperation action, String vnfId, String payload) {
CommandExecutorInput commandExecutorInput = createCommandExecutorInputWithSubObjects();
RuntimeContext runtimeContext = commandExecutorInput.getRuntimeContext();
RequestContext requestContext = runtimeContext.getRequestContext();
- requestContext.getCommonHeader().getFlags().setTtl(ttl);
- requestContext.getCommonHeader().setApiVer(apiVersion);
- requestContext.getCommonHeader().setTimestamp(timeStamp);
- requestContext.getCommonHeader().setRequestId(requestId);
- requestContext.getCommonHeader().setSubRequestId(subRequestID);
- requestContext.getCommonHeader().setOriginatorId(originatorID);
+ CommonHeader commonHeader = requestContext.getCommonHeader();
+ commonHeader.getFlags().setTtl(ttl);
+ commonHeader.setApiVer(apiVersion);
+ commonHeader.setTimestamp(timeStamp);
+ commonHeader.setRequestId(requestId);
+ commonHeader.setSubRequestId(subRequestID);
+ commonHeader.setOriginatorId(originatorID);
requestContext.setAction(action);
requestContext.setPayload(payload);
requestContext.getActionIdentifiers().setVnfId(vnfId);
return commandExecutorInput;
}
}
-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({FrameworkUtil.class, InetAddress.class})
public class TestCommandTask {
- CommandTask task ;
+ CommandTask task;
private RequestHandler requestHandler;
private WorkFlowManager workflowManager;
private AAIService aaiService;
private Bundle bundleService = Mockito.mock(Bundle.class);
private ServiceReference sref = Mockito.mock(ServiceReference.class);
- private static final String TTL_FLAG= "TTL";
- private static final String API_VERSION= "2.0.0";
- private static final String ORIGINATOR_ID= "1";
+ private static final String TTL_FLAG = "TTL";
+ private static final String API_VERSION = "2.0.0";
+ private static final String ORIGINATOR_ID = "1";
@Rule
public ExpectedException expectedEx = ExpectedException.none();
@Before
- public void init() throws UnknownHostException{
- aaiService = Mockito.mock(AAIService.class);
+ public void init() throws UnknownHostException {
+ aaiService = Mockito.mock(AAIService.class);
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref);
PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService);
- requestHandler = Mockito.mock(RequestHandler.class);
+ requestHandler = Mockito.mock(RequestHandler.class);
workflowManager = Mockito.mock(WorkFlowManager.class);
task = Mockito.spy(new CommandTask(requestHandler, workflowManager));
}
@Test
- public void testRunPositive(){
+ public void testRunPositive() {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "11", setTTLInFlags("30"), VNFOperation.Sync, "1", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "11", setTTLInFlags("30"),
+ VNFOperation.Sync, "1", "1.0"));
task.run();
- Assert.assertNotNull(task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ Assert.assertNotNull(
+ task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
}
@Test
- public void testRunPositiveTerminateFailed(){
+ public void testRunPositiveTerminateFailed() {
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(300, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
task.run();
- Assert.assertNotNull(task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
+ Assert.assertNotNull(
+ task.getCommandRequest().getCommandExecutorInput().getRuntimeContext().getResponseContext());
}
@Test
- public void testRunPositiveTerminateSucceeded() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateSucceeded() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
- Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class))).thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
+ Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class)))
+ .thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
Mockito.when(mockAai.getRequestFromResource("generic-vnf")).thenReturn(Mockito.mock(AAIRequest.class));
Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString())).thenReturn(true);
Whitebox.setInternalState(task, "aaiService", mockAai);
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
task.run();
}
@Test
- public void testRunPositiveTerminateNotFound() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateNotFound() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("VNF not found for vnf_id = ");
}
@Test
- public void testRunPositiveTerminateFailure() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveTerminateFailure() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectMessage("Error Querying AAI with vnfID = ");
}
@Test
- public void testRunPositiveAaiServiceException() throws SvcLogicException, AAIServiceException{
+ public void testRunPositiveAaiServiceException() throws SvcLogicException, AAIServiceException {
AAIService mockAai = Mockito.mock(AAIService.class);
Mockito.when(mockAai.query(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(SvcLogicContext.class)))
.thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
Mockito.when(mockAai.getRequestFromResource("generic-vnf")).thenReturn(Mockito.mock(AAIRequest.class));
- Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString())).thenThrow(new AAIServiceException("ERROR IN DELETE"));
+ Mockito.when(mockAai.delete(Mockito.any(AAIRequest.class), Mockito.anyString()))
+ .thenThrow(new AAIServiceException("ERROR IN DELETE"));
Whitebox.setInternalState(task, "aaiService", mockAai);
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectCause(allOf(isA(AAIServiceException.class),
Mockito.when(workflowManager.executeWorkflow(anyObject())).thenReturn(getWorkflowResponse());
task.setWorkflowManager(workflowManager);
task.setRequestHandler(requestHandler);
- task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12" , setTTLInFlags("30"), VNFOperation.Terminate, "2", "1.0"));
+ task.setCommandRequest(getCommandRequest("FIREWALL", 30, new Date(), "12", setTTLInFlags("30"),
+ VNFOperation.Terminate, "2", "1.0"));
setResponseContext(100, task.getCommandRequest().getCommandExecutorInput().getRuntimeContext());
expectedEx.expect(RuntimeException.class);
expectedEx.expectCause(isA(SvcLogicException.class));
task.run();
}
- private WorkflowResponse getWorkflowResponse (){
+ private WorkflowResponse getWorkflowResponse () {
WorkflowResponse wfResponse = new WorkflowResponse();
ResponseContext responseContext = createResponseContextWithObjects();
wfResponse.setResponseContext(responseContext);
return wfResponse;
}
- private ResponseContext createResponseContextWithObjects(){
+ private ResponseContext createResponseContextWithObjects() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
return responseContext;
}
- private void setResponseContext(int statusCode ,RuntimeContext runtimeContext ){
+ private void setResponseContext(int statusCode, RuntimeContext runtimeContext) {
ResponseContext responseContext = createResponseContextWithObjects();
responseContext.getStatus().setCode(statusCode);
runtimeContext.setResponseContext(responseContext);
}
private CommandRequest getCommandRequest(String vnfType, Integer ttl, Date timeStamp, String requestId,
- Map<String, Object> flags, VNFOperation command, String vnfId, String vnfVersion ){
+ Map<String, Object> flags, VNFOperation command, String vnfId, String vnfVersion) {
- CommandExecutorInput commandExecutorInput =
- pouplateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp, API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
+ CommandExecutorInput commandExecutorInput = populateCommandExecutorInput(vnfType, ttl, vnfVersion, timeStamp,
+ API_VERSION, requestId, ORIGINATOR_ID, "", command, vnfId, "");
CommandRequest request = new CommandRequest(commandExecutorInput);
request.setCommandExecutorInput(commandExecutorInput);
request.setCommandInTimeStamp(new Date());
return request;
}
- private CommandExecutorInput pouplateCommandExecutorInput(String vnfType, int ttl, String vnfVersion, Date timeStamp, String apiVersion,
- String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload){
+ private CommandExecutorInput populateCommandExecutorInput(String vnfType, int ttl, String vnfVersion,
+ Date timeStamp, String apiVersion, String requestId, String originatorID, String subRequestID,
+ VNFOperation action, String vnfId, String payload) {
CommandExecutorInput commandExecutorInput = createCommandExecutorInputWithSubObjects();
RuntimeContext runtimeContext = commandExecutorInput.getRuntimeContext();
RequestContext requestContext = runtimeContext.getRequestContext();
+ CommonHeader commonHeader = requestContext.getCommonHeader();
ResponseContext responseContext = createResponseContextWithSuObjects();
runtimeContext.setResponseContext(responseContext);
- requestContext.getCommonHeader().getFlags().setTtl(ttl);
- requestContext.getCommonHeader().setApiVer(apiVersion);
- requestContext.getCommonHeader().setTimestamp(timeStamp);
- requestContext.getCommonHeader().setRequestId(requestId);
- requestContext.getCommonHeader().setSubRequestId(subRequestID);
- requestContext.getCommonHeader().setOriginatorId(originatorID);
+ commonHeader.getFlags().setTtl(ttl);
+ commonHeader.setApiVer(apiVersion);
+ commonHeader.setTimestamp(timeStamp);
+ commonHeader.setRequestId(requestId);
+ commonHeader.setSubRequestId(subRequestID);
+ commonHeader.setOriginatorId(originatorID);
requestContext.setAction(action);
requestContext.setPayload(payload);
- requestContext.getActionIdentifiers().setVnfId(vnfId);
- requestContext.getActionIdentifiers().setServiceInstanceId("test");
+ ActionIdentifiers actionIdentifiers = requestContext.getActionIdentifiers();
+ actionIdentifiers.setVnfId(vnfId);
+ actionIdentifiers.setServiceInstanceId("test");
VNFContext vnfContext = runtimeContext.getVnfContext();
vnfContext.setType(vnfType);
vnfContext.setId(vnfId);
return commandExecutorInput;
}
- private ResponseContext createResponseContextWithSuObjects(){
+ private ResponseContext createResponseContextWithSuObjects() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
return runtimeContext;
}
- private Map<String,Object> setTTLInFlags( String value){
- Map<String,Object> flags = new HashMap<String,Object>();
- if( value != null || !("".equalsIgnoreCase(value))){
+ private Map<String, Object> setTTLInFlags(String value) {
+ Map<String, Object> flags = new HashMap<String, Object>();
+ if (value != null || !("".equalsIgnoreCase(value))) {
flags.put(TTL_FLAG, value);
}
return flags;
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* 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 class implements
*
* @see org.onap.appc.dao.util.dbcp.DBConnectionPool
- * that provides concrete implemenation of accessing appc database which basic setup
- * data would be got from global configuration.
+ * that provides a concrete implementation of appc database access
+ * with basic setup data extracted from the global configuration.
* @see org.onap.appc.configuration.Configuration
* <p>
* The singleton instance of this class has been instantiated by blueprint.
try {
connection = dbConnectionPool.getConnection();
} catch (DBConnectionPoolException e) {
- logger.error("DB connection pool is created failed." +
- "Please make sure the provided information is correct.");
+ logger.error("DB connection pool creation failed."
+ + " Please make sure the provided information is correct.");
}
if (connection != null) {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
* <blockquote><pre>
* {@code
* private AppcDatabaseConnectionPool pool;
- * public void setAppcDatabaseConnectionPool(AppcDatabaseConnectionPool pool){
+ * public void setAppcDatabaseConnectionPool(AppcDatabaseConnectionPool pool) {
* this.pool = pool;
* }
- * public queryAppcDatabase(AppcDatabaseConnectionPool pool){
+ * public queryAppcDatabase(AppcDatabaseConnectionPool pool) {
* Connection connection = null;
* try {
* connection = pool.getConnection();
* System.out.println("# of entries in db:");
* int numcols = rs.getMetaData().getColumnCount();
* System.out.println(pool.getDataSourceStatus());
- * }catch (SQLException e) {
+ * } catch (SQLException e) {
* e.printStackTrace();
* } finally {
* try {
- * pool.close(rs, stmt, conn);
+ * pool.close(rs, stmt, conn);
* } catch (DataAccessException e) {
* e.printStackTrace();
* }
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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(connectURI, username, password, driverClass, null, null, null, null, null);
}
- public DBConnectionPool(String connectURI, String username, String password,
- String driverClass, Integer initialSize, Integer maxActive,
- Integer maxIdle, Integer maxWait, Integer minIdle) {
+ public DBConnectionPool(String connectURI, String username, String password, String driverClass,
+ Integer initialSize, Integer maxActive, Integer maxIdle, Integer maxWait, Integer minIdle) {
this.dataSource = getBasicDataSource(connectURI, username, password, driverClass,
- initialSize, maxActive, maxIdle, maxWait, minIdle);
+ initialSize, maxActive, maxIdle, maxWait, minIdle);
}
/**
throw new DBConnectionPoolException(e);
}
- if(connection == null){
- //
+ if (connection == null) {
+ // Don't necessarily know why, but can report. . . .
throw new DBConnectionPoolException("Connection was not created");
}
}
protected BasicDataSource getBasicDataSource(String connectURI, String username, String password,
- String driverClass, Integer initialSize, Integer maxtotal,
- Integer maxIdle, Integer maxWaitMillis, Integer minIdle) {
+ String driverClass, Integer initialSize, Integer maxTotal, Integer maxIdle, Integer maxWaitMillis,
+ Integer minIdle) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUsername(username);
if (initialSize != null) {
dataSource.setInitialSize(initialSize);
}
- if (maxtotal != null) {
- dataSource.setMaxTotal(maxtotal);
+ if (maxTotal != null) {
+ dataSource.setMaxTotal(maxTotal);
}
if (maxIdle != null) {
dataSource.setMaxIdle(maxIdle);
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* 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=========================================================
*/
@Test
public void testArgumentConstructor() {
- AppcDatabaseConnectionPool appcDatabaseConnectionPool = new AppcDatabaseConnectionPool(dbUrl, username,
- password, driver);
+ AppcDatabaseConnectionPool appcDatabaseConnectionPool =
+ new AppcDatabaseConnectionPool(dbUrl, username, password, driver);
Object dbConnectionPool = Whitebox.getInternalState(appcDatabaseConnectionPool, "dbConnectionPool");
Assert.assertNotNull(dbConnectionPool);
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import java.sql.SQLException;
import java.util.Map;
-
public class DBConnectionPoolTest {
private final String connectURI = "jdbc:h2:mem:~/test;MODE=MYSQL;DB_CLOSE_DELAY=-1";
private final String username = "sa";
@Test
public void testShutdownException() throws SQLException {
- DBConnectionPool dbcpSpy = Mockito.spy(new DBConnectionPool(connectURI, username, password, driverClass,
- 0, 0, 0, 0, 0));
+ DBConnectionPool dbcpSpy =
+ Mockito.spy(new DBConnectionPool(connectURI, username, password, driverClass, 0, 0, 0, 0, 0));
BasicDataSource mockDataSource = Mockito.mock(BasicDataSource.class);
Mockito.doThrow(new SQLException()).when(mockDataSource).close();
Whitebox.setInternalState(dbcpSpy, "dataSource", mockDataSource);
*=================================================================================
* Modifications Copyright 2018 IBM.
*=================================================================================
+* Modifications Copyright 2019 AT&T Intellectual Property
+*=================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@Test
public void testGetActionLevel_ValidEnumConstant() {
requestContext.setActionLevel(ActionLevel.VM);
- Assert.assertNotNull(requestContext. getActionLevel());
- Assert.assertEquals(requestContext. getActionLevel(),ActionLevel.VM);
+ Assert.assertNotNull(requestContext.getActionLevel());
+ Assert.assertEquals(requestContext.getActionLevel(), ActionLevel.VM);
}
@Test
public void testgetAdditionalContext() {
- testadditionalContext=new HashMap<String, String>();
+ testadditionalContext = new HashMap<String, String>();
testadditionalContext.put("A", "a");
requestContext.setAdditionalContext(testadditionalContext);
Assert.assertNotNull(requestContext.getAdditionalContext());
Assert.assertTrue(requestContext.getAdditionalContext().containsKey("A"));
Assert.assertTrue(requestContext.getAdditionalContext().containsValue("a"));
}
-
+
@Test
public void testAddKeyValueToAdditionalContext() {
- String key="key1";
- String value="value1";
+ String key = "key1";
+ String value = "value1";
requestContext.addKeyValueToAdditionalContext(key, value);
- Map<String, String> additionalContext= requestContext.getAdditionalContext();
+ Map<String, String> additionalContext = requestContext.getAdditionalContext();
Assert.assertEquals("value1", additionalContext.get("key1"));
}
public void testToString_ContainsString() {
assertTrue(requestContext.toString().contains("RequestContext{commonHeader"));
}
-
+
@Test
- public void testGetSetCommonHeader()
- {
+ public void testGetSetCommonHeader() {
CommonHeader commonHeader = new CommonHeader();
requestContext.setCommonHeader(commonHeader);
assertEquals(commonHeader, requestContext.getCommonHeader());
}
-
+
@Test
- public void testGetSetActionIdentifiers()
- {
- ActionIdentifiers actionIdentifiers= new ActionIdentifiers();
+ public void testGetSetActionIdentifiers() {
+ ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
requestContext.setActionIdentifiers(actionIdentifiers);
assertEquals(actionIdentifiers, requestContext.getActionIdentifiers());
}
-
+
@Test
- public void testGetSetAction()
- {
- VNFOperation action= VNFOperation.ActionStatus;
+ public void testGetSetAction() {
+ VNFOperation action = VNFOperation.ActionStatus;
requestContext.setAction(action);
assertEquals(action, requestContext.getAction());
}
* 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=========================================================
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.sql.rowset.CachedRowSet;
import java.sql.SQLException;
+import javax.sql.rowset.CachedRowSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.time.temporal.ChronoUnit;
import static org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES.*;
import static org.onap.appc.transactionrecorder.objects.TransactionConstants.*;
*/
@Override
public void store(TransactionRecord record) throws APPCException {
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction data insertion into DB");
- }
- final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA +
- ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA +
- REQUEST_ID.getColumnName() + TransactionConstants.COMMA +
- SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA +
- ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA +
- START_TIME.getColumnName() + TransactionConstants.COMMA +
- END_TIME.getColumnName() + TransactionConstants.COMMA +
- TARGET_ID.getColumnName() + TransactionConstants.COMMA +
- TARGET_TYPE.getColumnName() + TransactionConstants.COMMA +
- OPERATION.getColumnName() + TransactionConstants.COMMA +
- RESULT_CODE.getColumnName() + TransactionConstants.COMMA +
- DESCRIPTION.getColumnName() + TransactionConstants.COMMA +
- STATE.getColumnName() + TransactionConstants.COMMA +
- SERVICE_INSTANCE_ID + TransactionConstants.COMMA +
- VNFC_NAME + TransactionConstants.COMMA +
- VSERVER_ID + TransactionConstants.COMMA +
- VF_MODULE_ID + TransactionConstants.COMMA +
- MODE + ") " +
- "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ logger.trace("Transaction data insertion into DB");
+ final String STORE_DATE_QUERY =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + "(" + TRANSACTION_ID.getColumnName() + TransactionConstants.COMMA
+ + ORIGIN_TIMESTAMP.getColumnName() + TransactionConstants.COMMA
+ + REQUEST_ID.getColumnName() + TransactionConstants.COMMA
+ + SUBREQUEST_ID.getColumnName() + TransactionConstants.COMMA
+ + ORIGINATOR_ID.getColumnName() + TransactionConstants.COMMA
+ + START_TIME.getColumnName() + TransactionConstants.COMMA
+ + END_TIME.getColumnName() + TransactionConstants.COMMA
+ + TARGET_ID.getColumnName() + TransactionConstants.COMMA
+ + TARGET_TYPE.getColumnName() + TransactionConstants.COMMA
+ + OPERATION.getColumnName() + TransactionConstants.COMMA
+ + RESULT_CODE.getColumnName() + TransactionConstants.COMMA
+ + DESCRIPTION.getColumnName() + TransactionConstants.COMMA
+ + STATE.getColumnName() + TransactionConstants.COMMA
+ + SERVICE_INSTANCE_ID + TransactionConstants.COMMA
+ + VNFC_NAME + TransactionConstants.COMMA
+ + VSERVER_ID + TransactionConstants.COMMA
+ + VF_MODULE_ID + TransactionConstants.COMMA
+ + MODE + ") "
+ + "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
dbLibService.writeData(STORE_DATE_QUERY, prepareArguments(record), SCHEMA);
} catch (SQLException e) {
logger.error("Error on storing record " + record.toString(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction Data Inserted Successfully into DB");
- }
+ logger.trace("Transaction Data Inserted Successfully into DB");
}
@Override
public void update(String key,
- String requestId,
- Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
+ String requestId,
+ Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
logger.debug("Inside update in TransactionRecorderImpl");
if (appcInstanceId != null && checkIfNullInstanceEntryExist(key, requestId)) {
logger.error("Error in updating records in updateTransactionEntry " + e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("Transaction data updated successfully");
- }
-
+ logger.trace("Transaction data updated successfully");
}
private void updateNullInstanceEntry(String key,
- String requestId,
- Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
+ String requestId,
+ Map<TRANSACTION_ATTRIBUTES, String> updateColumns) throws APPCException {
logger.debug("Inside updateNullInstanceEntry");
ArrayList<String> values = new ArrayList<>();
if (logger.isDebugEnabled()) {
logger.debug("Before updating Transaction table the Query is: " + query);
for (String value : values) {
- logger.debug("Value for Transaction table: " + value);
+ logger.debug("Value for Transaction table: " + value);
}
}
Boolean result = dbLibService.writeData(query, values, SCHEMA);
private boolean checkIfNullInstanceEntryExist(String key, String requestId) throws APPCException {
logger.debug("Entered checkIfNullInstanceEntryExist");
- String nullInstanceCheckQuery = new String("SELECT COUNT(*) as ROWCOUNT FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TRANSACTION_ID.getColumnName() + " = ? AND " +
- REQUEST_ID.getColumnName() + " = ? ");
+ String nullInstanceCheckQuery = new String(
+ "SELECT COUNT(*) as ROWCOUNT FROM "
+ + TransactionConstants.TRANSACTIONS + WHERE
+ + TRANSACTION_ID.getColumnName() + " = ? AND "
+ + REQUEST_ID.getColumnName() + " = ? ");
ArrayList<String> nullInstanceCheckParams = new ArrayList<>();
nullInstanceCheckParams.add(null + "~" + key);
nullInstanceCheckParams.add(requestId);
- try{
- CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA);
+ try (CachedRowSet rowSet = dbLibService.getData(nullInstanceCheckQuery, nullInstanceCheckParams, SCHEMA)) {
int noRows = 0;
if (rowSet != null && rowSet.first()) {
noRows = rowSet.getInt("ROWCOUNT");
- logger.info("No of Rows in Transactions Table with TRANSACTION_ID: " +
- null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows);
+ logger.info("No of Rows in Transactions Table with TRANSACTION_ID: "
+ + null + "~" + key + " and REQUEST_ID " + requestId + " is: " + noRows);
}
- if(noRows > 0)
+ if (noRows > 0)
return true;
} catch (SQLException e) {
logger.error("Error in checkIfNullInstanceEntryExist in the transaction table", e);
@Override
public void markTransactionsAborted(String appcInstanceId) {
- if (logger.isTraceEnabled()) {
- logger.trace("marking in progress transactions to aborted");
- }
+ logger.trace("marking in progress transactions to aborted");
final String updateQuery =
- "UPDATE " + TransactionConstants.TRANSACTIONS +
- " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "',"
- + END_TIME.getColumnName() + " = ? " +
- WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND "
+ "UPDATE " + TransactionConstants.TRANSACTIONS
+ + " SET " + STATE.getColumnName() + " = '" + RequestStatus.ABORTED.name() + "',"
+ + END_TIME.getColumnName() + " = ? "
+ + WHERE + TRANSACTION_ID.getColumnName() + " LIKE '" + appcInstanceId + "%' AND "
+ STATE.getColumnName() + " in (?,?)";
if (logger.isDebugEnabled()) {
logger.error(message);
throw new RuntimeException(message, e);
}
- if (logger.isTraceEnabled()) {
- logger.trace("In progress transactions marked aborted");
- }
+ logger.trace("In progress transactions marked aborted");
}
@Override
public List<TransactionRecord> getInProgressRequests(TransactionRecord record, int interval) throws APPCException {
- String IN_PROGRESS_REQUESTS_QUERY = "SELECT * FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TARGET_ID + " = ? AND " +
- STATE.getColumnName() + " IN (?,?) AND " +
- START_TIME.getColumnName() + " < ?";
+ String IN_PROGRESS_REQUESTS_QUERY =
+ "SELECT * FROM "
+ + TransactionConstants.TRANSACTIONS + WHERE
+ + TARGET_ID + " = ? AND "
+ + STATE.getColumnName() + " IN (?,?) AND "
+ + START_TIME.getColumnName() + " < ?";
ArrayList<String> inProgressQueryParams = new ArrayList<>();
Instant window = record.getStartTime().minus(interval, ChronoUnit.HOURS);
inProgressQueryParams.add(dateToStringConverterMillis(window));
}
- try (CachedRowSet rowSet = dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(IN_PROGRESS_REQUESTS_QUERY, inProgressQueryParams, SCHEMA)) {
List<TransactionRecord> inProgressRecords = new ArrayList<>();
TransactionRecord transaction;
- while (rowSet.next()) {
- transaction = new TransactionRecord();
- transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName()));
- transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName()));
- transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName()));
- transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName()));
- transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName())));
- transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName()));
- transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName()));
- transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName())));
- transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName())));
- transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName()));
- transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName()));
- transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName()));
- transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName()));
- transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName())));
- inProgressRecords.add(transaction);
- }
- if (logger.isTraceEnabled()) {
- logger.trace("In progress transaction records fetched from database successfully.");
+ int count = 0;
+ if (rowSet != null) {
+ for (; rowSet.next(); ++count) {
+ transaction = new TransactionRecord();
+ transaction.setTransactionId(rowSet.getString(TRANSACTION_ID.getColumnName()));
+ transaction.setRequestId(rowSet.getString(REQUEST_ID.getColumnName()));
+ transaction.setSubRequestId(rowSet.getString(SUBREQUEST_ID.getColumnName()));
+ transaction.setOriginatorId(rowSet.getString(ORIGINATOR_ID.getColumnName()));
+ transaction.setStartTime(stringToDateConverterMillis(rowSet.getString(START_TIME.getColumnName())));
+ transaction.setTargetId(rowSet.getString(TARGET_ID.getColumnName()));
+ transaction.setTargetType(rowSet.getString(TARGET_TYPE.getColumnName()));
+ transaction.setOperation(VNFOperation.valueOf(rowSet.getString(OPERATION.getColumnName())));
+ transaction.setRequestState(RequestStatus.valueOf(rowSet.getString(STATE.getColumnName())));
+ transaction.setVnfcName(rowSet.getString(VNFC_NAME.getColumnName()));
+ transaction.setVserverId(rowSet.getString(VSERVER_ID.getColumnName()));
+ transaction.setVfModuleId(rowSet.getString(VF_MODULE_ID.getColumnName()));
+ transaction.setServiceInstanceId(rowSet.getString(SERVICE_INSTANCE_ID.getColumnName()));
+ transaction.setMode(Flags.Mode.valueOf(rowSet.getString(MODE.getColumnName())));
+ inProgressRecords.add(transaction);
+ }
}
+ logger.trace(String.valueOf(count)
+ + " in progress transaction records fetched from database successfully.");
return inProgressRecords;
} catch (ParseException e) {
logger.error("Error parsing start date during fetching in progress records ", e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
} catch (SQLException e) {
- logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~" + record
- .getTransactionId(), e);
+ logger.error("Error fetching in progress records for Transaction ID = " + appcInstanceId + "~"
+ + record.getTransactionId(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
}
@Override
public Boolean isTransactionDuplicate(TransactionRecord record) throws APPCException {
- StringBuilder duplicateRequestCheckQuery = new StringBuilder("SELECT " +
- TRANSACTION_ID.getColumnName() + " FROM " +
- TransactionConstants.TRANSACTIONS + WHERE +
- TRANSACTION_ID.getColumnName() + " <> ? AND " +
- REQUEST_ID.getColumnName() + " = ? AND " +
- STATE.getColumnName() + " IN(?,?) ");
+ StringBuilder duplicateRequestCheckQuery = new StringBuilder()
+ .append("SELECT ").append(TRANSACTION_ID.getColumnName()).append(" FROM ")
+ .append(TransactionConstants.TRANSACTIONS).append(WHERE)
+ .append(TRANSACTION_ID.getColumnName()).append(" <> ? AND ")
+ .append(REQUEST_ID.getColumnName()).append(" = ? AND ")
+ .append(STATE.getColumnName()).append(" IN(?,?) ");
ArrayList<String> duplicateCheckParams = new ArrayList<>();
duplicateCheckParams.add(appcInstanceId + "~" + record.getTransactionId());
if (logger.isDebugEnabled()) {
logger.debug(duplicateRequestCheckQuery.toString());
}
- try (CachedRowSet rowSet = dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams,
- SCHEMA)) {
- if (rowSet.first()) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(duplicateRequestCheckQuery.toString(), duplicateCheckParams, SCHEMA)) {
+ if (rowSet != null && rowSet.first()) {
String transactionId = rowSet.getString(TRANSACTION_ID.getColumnName());
if (logger.isErrorEnabled()) {
- logger.error("Duplicate request found. Transaction ID " + transactionId + " is currently in " +
- "progress.");
+ logger.error("Duplicate request found. Transaction ID " + transactionId
+ + " is currently in progress.");
}
return true;
}
return false;
} catch (SQLException e) {
- logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~" + record
- .getTransactionId(), e);
+ logger.error("Error checking duplicate records for Transaction ID = " + appcInstanceId + "~"
+ + record.getTransactionId(), e);
throw new APPCException(ERROR_ACCESSING_DATABASE, e);
}
}
@Override
public Integer getInProgressRequestsCount() throws APPCException {
- final String inProgressRequestCountQuery = "SELECT COUNT(*) as VALUE FROM "
- + TransactionConstants.TRANSACTIONS
- + WHERE + STATE.getColumnName() + " IN (?,?) ";
+ final String inProgressRequestCountQuery =
+ "SELECT COUNT(*) as VALUE FROM "
+ + TransactionConstants.TRANSACTIONS
+ + WHERE + STATE.getColumnName() + " IN (?,?) ";
ArrayList<String> checkInProgressParams = new ArrayList<>();
checkInProgressParams.add(RequestStatus.RECEIVED.name());
checkInProgressParams.add(RequestStatus.ACCEPTED.name());
- try(CachedRowSet rowSet=dbLibService.getData(inProgressRequestCountQuery,checkInProgressParams,SCHEMA)){
- if (rowSet.first()) {
+ try (CachedRowSet rowSet =
+ dbLibService.getData(inProgressRequestCountQuery, checkInProgressParams, SCHEMA)) {
+ if (rowSet != null && rowSet.first()) {
int count = rowSet.getInt("VALUE");
logger.info("In progress request count fetched from database successfully.");
return count;
public List<RequestStatus> getRecords(String requestId, String subrequestId, String originatorId, String vnfId)
throws APPCException {
StringBuilder queryString = (new StringBuilder(1024))
- .append("SELECT " + TRANSACTION_ATTRIBUTES.STATE.getColumnName())
- .append(" FROM " + TRANSACTIONS)
- .append(" WHERE " + TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName() + " = ? AND " +
- TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName() + " = ?");
-
+ .append("SELECT ").append(TRANSACTION_ID.getColumnName())
+ .append(",")
+ .append(STATE.getColumnName())
+ .append(" FROM ").append(TRANSACTIONS)
+ .append(" WHERE ").append(TRANSACTION_ATTRIBUTES.REQUEST_ID.getColumnName()).append(" = ? AND ")
+ .append(TRANSACTION_ATTRIBUTES.TARGET_ID.getColumnName()).append(" = ?");
ArrayList<String> argList = new ArrayList<>();
argList.add(requestId);
argList.add(vnfId);
if (subrequestId != null) {
- queryString.append(" AND " + TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName() + " = ?");
+ queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.SUBREQUEST_ID.getColumnName()).append(" = ?");
argList.add(subrequestId);
}
if (originatorId != null) {
- queryString.append(" AND " + TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName() + " = ?");
+ queryString.append(" AND ").append(TRANSACTION_ATTRIBUTES.ORIGINATOR_ID.getColumnName()).append(" = ?");
argList.add(originatorId);
}
List<RequestStatus> requestStatusList = new ArrayList<>();
- try {
- CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA);
- while (resultSet.next()) {
- String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName());
- RequestStatus requestStatus = null;
- try {
- requestStatus = RequestStatus.valueOf(name);
- } catch (IllegalArgumentException e) {
- logger.error(String.format("Invalid request status (%s) using (%s) :", name, RequestStatus
- .UNKNOWN), e);
- requestStatus = RequestStatus.UNKNOWN;
+ try (CachedRowSet resultSet = dbLibService.getData(queryString.toString(), argList, SCHEMA)) {
+ if (resultSet == null) {
+ logger.error(String.format(
+ "No results returned when retrieving record for requestID %s and vnfId %s %s",
+ requestId, vnfId, "from the transactions table"));
+ } else {
+ while (resultSet.next()) {
+ String name = resultSet.getString(TRANSACTION_ATTRIBUTES.STATE.getColumnName());
+ RequestStatus requestStatus = null;
+ try {
+ requestStatus = RequestStatus.valueOf(name);
+ } catch (IllegalArgumentException e) {
+ logger.error(String.format(
+ "Invalid request status (%s) using (%s):", name, RequestStatus.UNKNOWN), e);
+ requestStatus = RequestStatus.UNKNOWN;
+ }
+ requestStatusList.add(requestStatus);
+ logger.debug(String.format("Request Status obtained (%s).", requestStatus));
}
- requestStatusList.add(requestStatus);
- logger.debug(String.format("Request Status obtained (%s).", requestStatus));
}
} catch (SQLException e) {
logger.error("Error Accessing Database ", e);
- throw new APPCException(String.format("Error retrieving record for requestID %s and vnfId %s " +
- "from the transactions table", requestId, vnfId), e);
+ throw new APPCException(String.format(
+ "Error retrieving record for requestID %s and vnfId %s from the transactions table",
+ requestId, vnfId), e);
}
return requestStatusList;
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
* ============LICENSE_END=========================================================
*/
package org.onap.appc.transactionrecorder.impl;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.anyString;
-import static org.hamcrest.CoreMatchers.isA;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.text.ParseException;
-import java.time.Instant;
-import java.time.ZoneOffset;
-import java.time.format.DateTimeFormatter;
-import java.time.temporal.ChronoUnit;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import javax.sql.rowset.CachedRowSet;
+import com.sun.rowset.CachedRowSetImpl;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
+
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.hamcrest.CoreMatchers.isA;
+
import org.onap.appc.dao.util.dbcp.DBConnectionPool;
import org.onap.appc.dao.util.helper.DBHelper;
import org.onap.appc.domainmodel.lcm.Flags;
import org.onap.appc.transactionrecorder.objects.TransactionConstants;
import org.onap.appc.transactionrecorder.objects.TransactionConstants.TRANSACTION_ATTRIBUTES;
import org.onap.ccsdk.sli.core.dblib.DbLibService;
-import com.sun.rowset.CachedRowSetImpl;
+
+import javax.sql.rowset.CachedRowSet;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
/**
* Test class for TransactionRecorder
* <p>
* Please ensure this table create script is identical to the source script used in a deployment.
*/
- private String TRANSACTION_CREATE_TABLE = "CREATE TABLE TRANSACTIONS (" +
- " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY," +
- " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL," +
- " REQUEST_ID VARCHAR(256) NOT NULL," +
- " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL," +
- " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL," +
- " START_TIME DATETIME(3) NOT NULL," +
- " END_TIME DATETIME(3) DEFAULT NULL," +
- " TARGET_ID VARCHAR(256) NOT NULL," +
- " TARGET_TYPE VARCHAR(256) DEFAULT NULL," +
- " OPERATION VARCHAR(256) NOT NULL," +
- " RESULT_CODE INT(11) DEFAULT NULL," +
- " DESCRIPTION TEXT," +
- " STATE VARCHAR(50) NOT NULL," +
- " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL," +
- " VNFC_NAME VARCHAR(256) DEFAULT NULL," +
- " VSERVER_ID VARCHAR(256) DEFAULT NULL," +
- " VF_MODULE_ID VARCHAR(256) DEFAULT NULL," +
- " MODE VARCHAR(50) NOT NULL," +
- ")";
+ private String TRANSACTION_CREATE_TABLE =
+ "CREATE TABLE TRANSACTIONS ("
+ + " TRANSACTION_ID VARCHAR(75) NOT NULL PRIMARY KEY,"
+ + " ORIGIN_TIMESTAMP DATETIME(3) NOT NULL,"
+ + " REQUEST_ID VARCHAR(256) NOT NULL,"
+ + " SUBREQUEST_ID VARCHAR(256) DEFAULT NULL,"
+ + " ORIGINATOR_ID VARCHAR(256) DEFAULT NULL,"
+ + " START_TIME DATETIME(3) NOT NULL,"
+ + " END_TIME DATETIME(3) DEFAULT NULL,"
+ + " TARGET_ID VARCHAR(256) NOT NULL,"
+ + " TARGET_TYPE VARCHAR(256) DEFAULT NULL,"
+ + " OPERATION VARCHAR(256) NOT NULL,"
+ + " RESULT_CODE INT(11) DEFAULT NULL,"
+ + " DESCRIPTION TEXT,"
+ + " STATE VARCHAR(50) NOT NULL,"
+ + " SERVICE_INSTANCE_ID VARCHAR(256) DEFAULT NULL,"
+ + " VNFC_NAME VARCHAR(256) DEFAULT NULL,"
+ + " VSERVER_ID VARCHAR(256) DEFAULT NULL,"
+ + " VF_MODULE_ID VARCHAR(256) DEFAULT NULL,"
+ + " MODE VARCHAR(50) NOT NULL,"
+ + ")";
private String TRANSACTION_DROP_TABLE = "DROP TABLE IF EXISTS TRANSACTIONS";
@Rule
public void testStore() throws Exception {
TransactionRecord input = prepareTransactionsInput();
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testStoreInMemory(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testStoreInMemory(invocation.getArguments()));
transactionRecorderImpl.store(input);
}
insertRecord(record1);
TransactionRecord input = prepareTransactionsInput();
input.setStartTime(Instant.now());
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 0).size());
}
@Test
public void testGetInProgressRequestsWithinTimeInterval() throws SQLException, APPCException {
TransactionRecord record1 = prepareTransactionsInput();
- record1.setStartTime(Instant.now().minus(4,ChronoUnit.HOURS));
+ record1.setStartTime(Instant.now().minus(4, ChronoUnit.HOURS));
insertRecord(record1);
TransactionRecord input = prepareTransactionsInput();
input.setStartTime(Instant.now());
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
- List<TransactionRecord> aList= transactionRecorderImpl.getInProgressRequests(input,12);
- Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input,12).size());
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
+ List<TransactionRecord> aList = transactionRecorderImpl.getInProgressRequests(input, 12);
+ Assert.assertEquals(1, transactionRecorderImpl.getInProgressRequests(input, 12).size());
}
@Test
public void testIsTransactionDuplicate() throws SQLException, APPCException {
TransactionRecord input = prepareTransactionsInput();
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- inMemoryExecutionWithResultSet(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> inMemoryExecutionWithResultSet(invocation.getArguments()));
Assert.assertFalse(transactionRecorderImpl.isTransactionDuplicate(input));
}
insertRecord(input);
Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>();
updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall");
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- returnResult(invocation.getArguments()));
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testUpdateInMemory(invocation.getArguments()));
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> returnResult(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments()));
transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns);
Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString());
Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString());
TransactionRecord input = prepareTransactionsInput();
Map<TransactionConstants.TRANSACTION_ATTRIBUTES, String> updateColumns = new HashMap<>();
updateColumns.put(TransactionConstants.TRANSACTION_ATTRIBUTES.TARGET_TYPE, "Firewall");
- Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- returnPositiveResult(invocation.getArguments()));
- Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString())).thenAnswer(invocation ->
- testUpdateInMemory(invocation.getArguments()));
-
+ Mockito.when(dbLibService.getData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> returnPositiveResult(invocation.getArguments()));
+ Mockito.when(dbLibService.writeData(anyString(), anyObject(), anyString()))
+ .thenAnswer(invocation -> testUpdateInMemory(invocation.getArguments()));
transactionRecorderImpl.update(input.getTransactionId(), input.getRequestId(), updateColumns);
Mockito.verify(dbLibService).getData(anyString(), anyObject(), anyString());
Mockito.verify(dbLibService).writeData(anyString(), anyObject(), anyString());
insertNullInstanceData(args.get(0));
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps_second = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps_second = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps_second.setString(i, args.get(i - 1));
}
}
private void insertNullInstanceData(String transactionId) throws Exception {
- final String nullInstanceQuery = (TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
+ final String nullInstanceQuery =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(nullInstanceQuery)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(nullInstanceQuery)
+ ) {
ArrayList<String> input = new ArrayList<String>();
input.add(transactionId);
input.add(dateToStringConverterMillis(Instant.parse("2017-09-12T00:00:01.00Z")));
ArrayList<String> args = (ArrayList<String>) obj[1];
System.out.println("Query: " + query + "\nArgs: " + args);
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
ArrayList<String> args = (ArrayList<String>) obj[1];
// System.out.println("Query: " + query + "\nArgs: " + args);
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
private boolean isTransactionAborted() throws Exception {
String query = "SELECT COUNT(*) FROM TRANSACTIONS WHERE STATE = ?";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
ps.setString(1, RequestStatus.ABORTED.toString());
try (
- ResultSet rs = ps.executeQuery()
- ) {
+ ResultSet rs = ps.executeQuery()
+ ) {
while (rs.next()) {
int value = rs.getInt(1);
if (value == 1) {
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
System.out.println("Value at " + i + ": " + args.get(i - 1));
ps.setString(i, args.get(i - 1));
String query = (String) obj[0];
ArrayList<String> args = (ArrayList<String>) obj[1];
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(query)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(query)
+ ) {
for (int i = 1; i <= args.size(); i++) {
ps.setString(i, args.get(i - 1));
}
}
private void insertRecord(TransactionRecord input) throws SQLException {
- final String STORE_DATE_QUERY = TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS +
- " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+ final String STORE_DATE_QUERY =
+ TransactionConstants.INSERT_INTO + TransactionConstants.TRANSACTIONS
+ + " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY)
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(STORE_DATE_QUERY)
+ ) {
ArrayList<String> args = prepareArguments(input);
args.remove(0);
args.add(0, "123~" + input.getTransactionId());
private String checkIfValueIsUpdated(String key) throws Exception {
try (
- Connection con = dbConnectionPool.getConnection();
- PreparedStatement ps = con.prepareStatement("SELECT TARGET_TYPE,TRANSACTION_ID FROM TRANSACTIONS" +
- " WHERE TRANSACTION_ID = ?")
- ) {
+ Connection con = dbConnectionPool.getConnection();
+ PreparedStatement ps = con.prepareStatement(
+ "SELECT TARGET_TYPE, TRANSACTION_ID FROM TRANSACTIONS"
+ + " WHERE TRANSACTION_ID = ?")
+ ) {
ps.setString(1, key);
try (
- ResultSet rs = ps.executeQuery()
- ) {
- while (rs.next()) {
- String value = rs.getString("TARGET_TYPE");
- String transactionId = rs.getString("TRANSACTION_ID");
- System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value);
- return value;
- }
- throw new Exception("Value not found");
+ ResultSet rs = ps.executeQuery()
+ ) {
+ while (rs.next()) {
+ String value = rs.getString("TARGET_TYPE");
+ String transactionId = rs.getString("TRANSACTION_ID");
+ System.out.println("Updated data: TRANSACTION_ID: " + transactionId + " TARGET_TYPE: " + value);
+ return value;
+ }
+ throw new Exception("Value not found");
}
}
}
* ================================================================================
* Modifications Copyright (C) 2018 Nokia
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
public void retrieveLicenseModel_shouldThrowException_whenRetrieveLicenseModelDataIsEmpty() {
// GIVEN
- String expectedMessage = String
- .format("License model not found for vnfType='%s' and vnfVersion='%s'", VNF_TYPE, VNF_VERSION);
+ String expectedMessage =
+ String.format("License model not found for vnfType='%s' and vnfVersion='%s'", VNF_TYPE, VNF_VERSION);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(Collections.emptyMap());
+ .willReturn(Collections.emptyMap());
// WHEN THEN
assertThatExceptionOfType(DataAccessException.class)
- .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION))
- .withMessage(expectedMessage);
+ .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION))
+ .withMessage(expectedMessage);
}
@Test
Map<String, String> licenseModelData = new HashMap<>();
licenseModelData.put(ARTIFACT_CONTENT.name(), malformedXml);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(licenseModelData);
+ .willReturn(licenseModelData);
// WHEN THEN
assertThatExceptionOfType(DataAccessException.class)
- .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION));
+ .isThrownBy(() -> licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION));
}
@Test
Map<String, String> licenseModelData = new HashMap<>();
licenseModelData.put(ARTIFACT_CONTENT.name(), correctlyFormedXml);
given(licenseDataAccessService.retrieveLicenseModelData(VNF_TYPE, VNF_VERSION))
- .willReturn(licenseModelData);
+ .willReturn(licenseModelData);
// WHEN
LicenseModel licenseModel = licenseManager.retrieveLicenseModel(VNF_TYPE, VNF_VERSION);
assertEquals(expectedEntitlementPool, licenseModel.getEntitlementPoolUuid());
assertEquals(expectedKeyGroup, licenseModel.getLicenseKeyGroupUuid());
}
-}
\ No newline at end of file
+}
* ================================================================================
* Copyright (C) 2018 Nokia
* =============================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
// WHEN
converter.convert((a, b) -> {
- }, anyString(), null);
+ }, anyString(), null);
// THEN
then(xmlStreamReader).should().close();
// WHEN THEN
assertThatExceptionOfType(XMLStreamException.class)
- .isThrownBy(() -> converter.convert((a, b) -> {
- throw new XMLStreamException();
- }, anyString(), null));
+ .isThrownBy(() -> converter.convert((a, b) -> {
+ throw new XMLStreamException();
+ }, anyString(), null));
then(xmlStreamReader).should().close();
}
-}
\ No newline at end of file
+}
</license-key-group-list>
</feature-group>
</feature-group-list>
-</vf-license-model>
\ No newline at end of file
+</vf-license-model>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class MessageAdapterImpl implements MessageAdapter{
private MessagingConnector messageService;
- private String partition ;
+ private String partition;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapterImpl.class);
* Initialize producer client to post messages using configuration properties
*/
@Override
- public void init(){
- logger.debug("MessageAdapterImpl - init");
+ public void init() {
+ logger.debug("MessageAdapterImpl - init");
this.messageService = new MessagingConnector();
}
-
+
public void init(MessagingConnector connector) {
logger.debug("MessageAdapterImpl - init");
this.messageService = connector;
}
/**
- * Posts message to DMaaP. As DMaaP accepts only json messages this method first convert dmaapMessage to json format and post it to DMaaP.
- * @param asyncResponse response data that based on it a message will be send to DMaaP (the format of the message that will be sent to DMaaP based on the action and its YANG domainmodel).
- * @return True if message is postes successfully else False
+ * Posts message to DMaaP. As DMaaP accepts only json messages this method first converts dmaapMessage
+ * to json format and posts it to DMaaP.
+ * @param asyncResponse response data on which to base a message that will be sent to DMaaP
+ * (the format of the message that will be sent to DMaaP is based on the action and its YANG domainmodel).
+ * @return True if message is posted successfully, else False
*/
@Override
- public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse){
+ public boolean post(VNFOperation operation, String rpcName, ResponseContext asyncResponse) {
boolean success;
if (logger.isTraceEnabled()) {
logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(asyncResponse));
logger.debug("Entered MessageAdapterImpl.post()");
String jsonMessage;
try {
- logger.debug("Before converting Async Response");
- jsonMessage = Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse);
+ logger.debug("Before converting Async Response");
+ jsonMessage =
+ Converter.convAsyncResponseToDmaapOutgoingMessageJsonString(operation, rpcName, asyncResponse);
if (logger.isDebugEnabled()) {
logger.debug("DMaaP Response = " + jsonMessage);
}
- logger.debug("Before Invoking producer.post(): jsonMessage is::" + jsonMessage);
+ logger.debug("Before Invoking messageService.publishMessage(): jsonMessage is::" + jsonMessage);
success = messageService.publishMessage("appc.LCM", this.partition, jsonMessage);
- logger.debug("After Invoking producer.post()");
+ logger.debug("After Invoking messageService.publishMessage()");
} catch (JsonProcessingException e1) {
logger.error("Error generating Json from DMaaP message " + e1.getMessage());
success = false;
- }catch (Exception e){
+ } catch (Exception e) {
logger.error("Error sending message to DMaaP " + e.getMessage());
success = false;
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
isoFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
}
- public static Builder<?> convAsyncResponseToBuilder(VNFOperation vnfOperation, String rpcName, ResponseContext response) {
+ public static Builder<?> convAsyncResponseToBuilder(
+ VNFOperation vnfOperation, String rpcName, ResponseContext response) {
Builder<?> outObj = null;
if (response == null) {
throw new IllegalArgumentException("empty asyncResponse");
throw new IllegalArgumentException("empty asyncResponse.action");
}
logger.debug("Entered Converter.convAsyncResponseToBuilder(): Operation Name " + vnfOperation.name());
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action action = org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action.valueOf(vnfOperation.name());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action action =
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.Action.valueOf(vnfOperation.name());
logger.debug("After resolving action");
CommonHeader commonHeader = convAsyncResponseTorev160108CommonHeader(response);
Status status = convAsyncResponseTorev160108Status(response);
((SnapshotOutputBuilder)outObj).setStatus(status);
try {
((SnapshotOutputBuilder) outObj)
- .setSnapshotId(response.getAdditionalContext().get("output.snapshot-id"));
+ .setSnapshotId(response.getAdditionalContext().get("output.snapshot-id"));
} catch (NullPointerException ignored) {
- // in case of negative response, snapshotID does not populated, so just ignore NPL
+ // in case of negative response, snapshotID is not populated, so just ignore NPL
}
return outObj;
case Audit:
outObj = new AttachVolumeOutputBuilder();
((AttachVolumeOutputBuilder)outObj).setCommonHeader(commonHeader);
((AttachVolumeOutputBuilder)outObj).setStatus(status);
- return outObj;
+ return outObj;
case DetachVolume:
outObj = new DetachVolumeOutputBuilder();
((DetachVolumeOutputBuilder)outObj).setCommonHeader(commonHeader);
return outObj;
case DistributeTrafficCheck:
outObj = new DistributeTrafficCheckOutputBuilder();
- ((DistributeTrafficCheckOutputBuilder) outObj).setCommonHeader(commonHeader);
+ ((DistributeTrafficCheckOutputBuilder)outObj).setCommonHeader(commonHeader);
((DistributeTrafficCheckOutputBuilder)outObj).setStatus(status);
return outObj;
case PreConfigure:
outObj = new PreConfigureOutputBuilder();
((PreConfigureOutputBuilder)outObj).setCommonHeader(commonHeader);
((PreConfigureOutputBuilder)outObj).setStatus(status);
- ((PreConfigureOutputBuilder)outObj).setPayload(payload);
+ ((PreConfigureOutputBuilder)outObj).setPayload(payload);
return outObj;
case GetConfig:
outObj = new GetConfigOutputBuilder();
((StopTrafficOutputBuilder)outObj).setPayload(payload);
return outObj;
case LicenseManagement:
- outObj = new LicenseManagementOutputBuilder();
+ outObj = new LicenseManagementOutputBuilder();
((LicenseManagementOutputBuilder)outObj).setCommonHeader(commonHeader);
((LicenseManagementOutputBuilder)outObj).setStatus(status);
((LicenseManagementOutputBuilder)outObj).setPayload(payload);
}
}
- public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) {
- logger.debug("Entering convAsyncResponseTorev160108Payload");
+ public static Payload convAsyncResponseTorev160108Payload(ResponseContext inObj) {
+ logger.debug("Entering convAsyncResponseTorev160108Payload");
Payload payload = null;
if (inObj.getPayload() != null) {
payload = new Payload(inObj.getPayload());
String payloadAsString = null;
if (inObj != null) {
- if (inObj instanceof String) {
- payloadAsString = (String)inObj;
- } else {
- try {
- ObjectMapper objectMapper = new ObjectMapper();
- payloadAsString = objectMapper.writeValueAsString(inObj);
- } catch (JsonProcessingException e) {
- String errMsg = "Error serialize payload json to string";
- throw new ParseException(errMsg + "-" + e.toString(), 0);
- }
+ if (inObj instanceof String) {
+ payloadAsString = (String)inObj;
+ } else {
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ payloadAsString = objectMapper.writeValueAsString(inObj);
+ } catch (JsonProcessingException e) {
+ String errMsg = "Error serialize payload json to string";
+ throw new ParseException(errMsg + "-" + e.toString(), 0);
}
+ }
}
return payloadAsString;
}
public static Status convAsyncResponseTorev160108Status(ResponseContext inObj) {
- logger.debug("Entering convAsyncResponseTorev160108Status");
+ logger.debug("Entering convAsyncResponseTorev160108Status");
StatusBuilder statusBuilder = new StatusBuilder();
statusBuilder.setCode(inObj.getStatus().getCode());
statusBuilder.setMessage(inObj.getStatus().getMessage());
}
public static CommonHeader convAsyncResponseTorev160108CommonHeader(ResponseContext inObj) {
- logger.debug("Entered into convAsyncResponseTorev160108CommonHeader");
+ logger.debug("Entered into convAsyncResponseTorev160108CommonHeader");
CommonHeader outObj = null;
if (inObj == null) {
throw new IllegalArgumentException("empty asyncResponse");
commonHeaderBuilder.setTimestamp(zuluTimestamp);
}
outObj = commonHeaderBuilder.build();
- logger.debug("Exiting from convAsyncResponseTorev160108CommonHeader: Returning outObj::"+ outObj.toString());
+ logger.debug("Exiting from convAsyncResponseTorev160108CommonHeader: Returning outObj: " + outObj.toString());
return outObj;
}
}
public static org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags
- convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) {
+ convFlagsMapTorev160108Flags(org.onap.appc.domainmodel.lcm.Flags flags) {
Flags rev160108flags;
boolean anyFlag = false;
FlagsBuilder flagsBuilder = new FlagsBuilder();
/*
- * TODO: The below flags are related to APP-C request and should not be sent back - uncomment when response flags are introduced.
+ * TODO: The below flags are related to APP-C request and should not be sent back -
+ * uncomment when response flags are introduced.
*/
/*
- if(flags.containsKey(FORCE_FLAG)){
+ if (flags.containsKey(FORCE_FLAG)) {
org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force force =
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Force.valueOf(flags.get(FORCE_FLAG).toString());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header
+ .Flags.Force.valueOf(flags.get(FORCE_FLAG).toString());
flagsBuilder.setForce(force);
anyFlag = true;
}
- if(flags.containsKey(MODE_FLAG)){
+ if (flags.containsKey(MODE_FLAG)) {
org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode mode =
- org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header.Flags.Mode.valueOf(flags.get(MODE_FLAG).toString());
+ org.opendaylight.yang.gen.v1.org.onap.appc.lcm.rev160108.common.header.common.header
+ .Flags.Mode.valueOf(flags.get(MODE_FLAG).toString());
flagsBuilder.setMode(mode);
anyFlag = true;
}
- if(flags.containsKey(TTL_FLAG)){
+ if (flags.containsKey(TTL_FLAG)) {
flagsBuilder.setTtl(Integer.valueOf(flags.get(TTL_FLAG).toString()));
anyFlag = true;
}
- if(anyFlag){
+ if (anyFlag) {
rev160108flags = flagsBuilder.build();
}
*/
objectMapper.addMixIn(Payload.class, MixIn.class);
objectMapper.addMixIn(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
ObjectWriter writer = objectMapper
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
throws JsonProcessingException {
logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessageJsonString()");
- DmaapOutgoingMessage dmaapOutgoingMessage =
- convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse);
+ DmaapOutgoingMessage dmaapOutgoingMessage =
+ convAsyncResponseToDmaapOutgoingMessage(vnfOperation, rpcName, asyncResponse);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(dmaapOutgoingMessage.getBody().getOutput().getClass(), MixInFlagsMessage.class);
objectMapper.addMixIn(CommonHeader.class, MixInCommonHeader.class);
objectMapper.addMixIn(Payload.class, MixIn.class);
objectMapper.addMixIn(ZULU.class, MixIn.class);
-// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY,true)
+// .configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true)
ObjectWriter writer = objectMapper
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
}
public static DmaapOutgoingMessage convAsyncResponseToDmaapOutgoingMessage(
- VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
+ VNFOperation vnfOperation, String rpcName, ResponseContext asyncResponse)
throws JsonProcessingException {
- logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessage()");
- DmaapOutgoingMessage outObj = new DmaapOutgoingMessage();
+ logger.debug("Entered Converter.convAsyncResponseToDmaapOutgoingMessage()");
+ DmaapOutgoingMessage outObj = new DmaapOutgoingMessage();
String correlationID = getCorrelationID(asyncResponse);
outObj.setCorrelationID(correlationID);
outObj.setType("response");
Object messageBody = builder.build();
DmaapOutgoingMessage.Body body = new DmaapOutgoingMessage.Body(messageBody);
outObj.setBody(body);
- logger.debug("Exiting Converter.convAsyncResponseToDmaapOutgoingMessage(): messageBody is:" + body.toString());
+ logger.debug("Exiting Converter.convAsyncResponseToDmaapOutgoingMessage(): messageBody is: " + body.toString());
return outObj;
}
}
abstract class MixInFlagsMessage extends MixIn {
@JsonProperty("common-header")
- abstract CommonHeader getCommonHeader();
+ abstract CommonHeader getCommonHeader();
}
}
* 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=========================================================
*/
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import java.util.UUID;
import java.util.TimeZone;
+import java.util.UUID;
+
import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
* 3. For the given VNF type and Operation, there exists work-flow definition in the APPC database
* If any of the validation fails, it returns appropriate response *
*
- * @param input RequestHandlerInput object which contains request header and other request parameters like
- * command , target Id , payload etc.
+ * @param input RequestHandlerInput object which contains request header and other request parameters like
+ * command, target Id, payload etc.
* @return response for request as enum with Return code and message.
*/
@Override
storeErrorMessageToLog(runtimeContext, e.getTargetEntity(), e.getTargetService(), e.getLogMessage());
output = buildRequestHandlerOutput(e.getLcmCommandStatus(), e.getParams());
} catch (InvalidInputException e) {
- logger.error("InvalidInputException : " + e.getMessage(), e);
+ logger.error("InvalidInputException: " + e.getMessage(), e);
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
- output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER, new Params().addParam
- ("errorMsg", errorMessage));
+ output = buildRequestHandlerOutput(LCMCommandStatus.INVALID_INPUT_PARAMETER,
+ new Params().addParam("errorMsg", errorMessage));
} catch (LockException e) {
- logger.error("LockException : " + e.getMessage(), e);
+ logger.error("LockException: " + e.getMessage(), e);
Params params = new Params().addParam("errorMsg", e.getMessage());
fillStatus(runtimeContext, LCMCommandStatus.LOCKED_VNF_ID, params);
output = buildRequestHandlerOutput(LCMCommandStatus.LOCKED_VNF_ID, params);
} catch (Exception e) {
- logger.error("Exception : " + e.getMessage(), e);
+ logger.error("Exception: " + e.getMessage(), e);
storeErrorMessageToLog(runtimeContext, "", "", "Exception = " + e.getMessage());
errorMessage = e.getMessage() != null ? e.getMessage() : e.toString();
Params params = new Params().addParam("errorMsg", errorMessage);
if (isMetricEnabled)
((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementAcceptedRequest();
} else {
- requestStatus = (statusCode == LCMCommandStatus.EXPIRED_REQUEST.getResponseCode()) ? RequestStatus
- .TIMEOUT : RequestStatus.REJECTED;
+ requestStatus = (statusCode == LCMCommandStatus.EXPIRED_REQUEST.getResponseCode()) ?
+ RequestStatus.TIMEOUT : RequestStatus.REJECTED;
if (isMetricEnabled)
((DispatchingFuntionMetric) metricRegistry.metric("DISPATCH_FUNCTION")).incrementRejectedRequest();
}
try {
- if (errorMessage != null && logger.isDebugEnabled())
- logger.debug("error occurred in handleRequest " + errorMessage);
- logger.debug("output.getResponseContext().getStatus().getCode(): " + statusCode);
+ if (logger.isDebugEnabled()) {
+ if (errorMessage != null)
+ logger.debug("error occurred in handleRequest: " + errorMessage);
+ logger.debug("output.getResponseContext().getStatus().getCode(): " + statusCode);
+ }
runtimeContext.setResponseContext(output.getResponseContext());
} finally {
runtimeContext.getTransactionRecord().setRequestState(requestStatus);
}
}
if (logger.isTraceEnabled()) {
- logger.trace("Exiting from handleRequest with (RequestHandlerOutput = " +
- ObjectUtils.toString(output.getResponseContext()) + ")");
+ logger.trace("Exiting from handleRequest with (RequestHandlerOutput = "
+ + ObjectUtils.toString(output.getResponseContext()) + ")");
}
return output;
}
String additionalMessage) {
LoggingUtils.logErrorMessage(runtimeContext.getResponseContext().getStatus() != null ?
String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()) : "",
- runtimeContext.getResponseContext().getStatus() != null ?
+ runtimeContext.getResponseContext().getStatus() != null ?
String.valueOf(runtimeContext.getResponseContext().getStatus().getMessage()) : "",
- targetEntity,
- targetServiceName,
- additionalMessage,
- this.getClass().getCanonicalName());
+ targetEntity,
+ targetServiceName,
+ additionalMessage,
+ this.getClass().getCanonicalName());
}
protected abstract void handleRequest(RuntimeContext runtimeContext);
MDC.put(MDC_SERVICE_NAME, requestContext.getAction().name());
MDC.put(LoggingConstants.MDCKeys.TARGET_VIRTUAL_ENTITY, requestContext.getActionIdentifiers().getVnfId());
} catch (UnknownHostException e) {
- logger.error("Error occured while setting initial log properties", e);
+ logger.error("Error occurred while setting initial log properties", e);
}
}
}
/**
- * This method perform following operations required after execution of workflow.
+ * This method performs following operations required after execution of workflow.
* It posts asynchronous response to message bus (DMaaP).
- * Unlock VNF Id
+ * Unlocks VNF Id.
* Removes request from request registry.
- * Generate audit logs.
+ * Generates audit logs.
* Adds transaction record to database id if transaction logging is enabled.
*/
@Override
public void onRequestExecutionEnd(RuntimeContext runtimeContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to onRequestExecutionEnd with runtimeContext = " +
- ObjectUtils.toString(runtimeContext));
+ logger.trace("Entering to onRequestExecutionEnd with runtimeContext = "
+ + ObjectUtils.toString(runtimeContext));
}
postMessageToDMaaP(runtimeContext.getRequestContext().getAction(), runtimeContext.getRpcName(),
- runtimeContext.getResponseContext());
+ runtimeContext.getResponseContext());
final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
RequestStatus requestStatus =
- (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) ?
+ (statusCode == LCMCommandStatus.SUCCESS.getResponseCode()) ?
RequestStatus.SUCCESSFUL : RequestStatus.FAILED;
runtimeContext.getTransactionRecord().setRequestState(requestStatus);
runtimeContext.getTransactionRecord().setResultCode(runtimeContext.getResponseContext().getStatus().getCode());
private void storeAuditLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logAuditMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
private void storeMetricLogRecord(RuntimeContext runtimeContext) {
LoggingUtils.logMetricsMessage(runtimeContext.getTimeStart(),
- Instant.now(),
- LoggingConstants.TargetNames.APPC,
- runtimeContext.getRequestContext().getAction().name(),
- runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()
- ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
- String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
- runtimeContext.getResponseContext().getStatus().getMessage(),
- this.getClass().getCanonicalName());
+ Instant.now(),
+ LoggingConstants.TargetNames.APPC,
+ runtimeContext.getRequestContext().getAction().name(),
+ runtimeContext.getResponseContext().getStatus().getCode() == LCMCommandStatus.ACCEPTED.getResponseCode()
+ ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR,
+ String.valueOf(runtimeContext.getResponseContext().getStatus().getCode()),
+ runtimeContext.getResponseContext().getStatus().getMessage(),
+ this.getClass().getCanonicalName());
}
private void postMessageToDMaaP(VNFOperation operation, String rpcName, ResponseContext responseContext) {
if (logger.isTraceEnabled()) {
- logger.trace("Entering to postMessageToDMaaP with AsyncResponse = " +
- ObjectUtils.toString(responseContext));
+ logger.trace("Entering to postMessageToDMaaP with AsyncResponse = "
+ + ObjectUtils.toString(responseContext));
}
logger.debug("In postMessageToDMaap before invoking post()");
boolean callbackResponse = messageAdapter.post(operation, rpcName, responseContext);
logger.error("DMaaP posting status: false", "dmaapMessage: " + responseContext);
}
if (logger.isTraceEnabled())
- logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = " +
- ObjectUtils.toString(callbackResponse) + ")");
+ logger.trace("Exiting from postMessageToDMaaP with (callbackResponse = "
+ + ObjectUtils.toString(callbackResponse) + ")");
}
private void initMetric() {
- if (logger.isDebugEnabled())
- logger.debug("Metric getting initialized");
+ logger.debug("Metric getting initialized");
MetricService metricService = getMetricservice();
// Check for the metric service created before trying to create registry using
// the metricService object
if (metricService == null) {
// Cannot find service reference for org.onap.appc.metricservice.MetricService
- throw new NullPointerException("org.onap.appc.metricservice.MetricService is null. " +
- "Failed to init Metric");
+ throw new NullPointerException("org.onap.appc.metricservice.MetricService is null. "
+ + "Failed to init Metric");
}
metricRegistry = metricService.createRegistry("APPC");
- DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory().
- dispatchingFunctionCounterBuilder().
- withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER).
- withAcceptRequestValue(0)
- .withRejectRequestValue(0)
- .build();
+ DispatchingFuntionMetric dispatchingFuntionMetric = metricRegistry.metricBuilderFactory()
+ .dispatchingFunctionCounterBuilder()
+ .withName("DISPATCH_FUNCTION").withType(MetricType.COUNTER)
+ .withAcceptRequestValue(0)
+ .withRejectRequestValue(0)
+ .build();
if (metricRegistry.register(dispatchingFuntionMetric)) {
Metric[] metrics = new Metric[]{dispatchingFuntionMetric};
LogPublisher logPublisher = new LogPublisher(metricRegistry, metrics);
LogPublisher[] logPublishers = new LogPublisher[1];
logPublishers[0] = logPublisher;
PublishingPolicy manuallyScheduledPublishingPolicy = metricRegistry.policyBuilderFactory()
- .scheduledPolicyBuilder()
- .withPublishers(logPublishers)
- .withMetrics(metrics)
- .build();
+ .scheduledPolicyBuilder()
+ .withPublishers(logPublishers)
+ .withMetrics(metrics)
+ .build();
- if (logger.isDebugEnabled())
- logger.debug("Policy getting initialized");
+ logger.debug("Policy getting initialized");
manuallyScheduledPublishingPolicy.init();
- if (logger.isDebugEnabled())
- logger.debug("Metric initialized");
+ logger.debug("Metric initialized");
}
}
/**
* This method returns the count of in progress requests
- * * @return in progress requests count
+ * @return in progress requests count
*/
@Override
public int getInprogressRequestCount() throws APPCException {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to getInprogressRequestCount");
- }
+ logger.trace("Entering to getInprogressRequestCount");
return transactionRecorder.getInProgressRequestsCount();
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
* ============LICENSE_END=========================================================
*/
package org.onap.appc.requesthandler.impl;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-import java.util.stream.Collectors;
+import com.att.eelf.i18n.EELFResourceManager;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.onap.appc.workflow.WorkFlowManager;
import org.onap.appc.workflow.objects.WorkflowExistsOutput;
import org.onap.appc.workflow.objects.WorkflowRequest;
-import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
+import org.onap.ccsdk.sli.adaptors.aai.AAIService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
-import com.att.eelf.i18n.EELFResourceManager;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import java.util.stream.Collectors;
public class RequestValidatorImpl extends AbstractRequestValidatorImpl {
String user = null;
String pass = null;
String transactionWindow = null;
-
Properties properties = configuration.getProperties();
if (properties != null) {
endpoint = properties.getProperty(SCOPE_OVERLAP_ENDPOINT);
}
List<TransactionRecord> inProgressTransactionsAll = transactionRecorder
- .getInProgressRequests(runtimeContext.getTransactionRecord(),0);
+ .getInProgressRequests(runtimeContext.getTransactionRecord(), 0);
List<TransactionRecord> inProgressTransactions = transactionRecorder
- .getInProgressRequests(runtimeContext.getTransactionRecord(),transactionWindowInterval);
-
- long inProgressTransactionsAllCount = inProgressTransactionsAll.size();
- long inProgressTransactionsRelevant = inProgressTransactions.size();
+ .getInProgressRequests(runtimeContext.getTransactionRecord(), transactionWindowInterval);
+ long inProgressTransactionsAllCount = inProgressTransactionsAll == null ? 0 : inProgressTransactionsAll.size();
+ long inProgressTransactionsRelevant = inProgressTransactions == null ? 0 : inProgressTransactions.size();
logger.debug("In progress requests " + inProgressTransactions.toString());
- if ( inProgressTransactions.isEmpty()){ //No need to check for scope overlap
+ if (inProgressTransactionsRelevant == 0) { //No need for further checks
return;
}
- logInProgressTransactions(inProgressTransactions,inProgressTransactionsAllCount,
- inProgressTransactionsRelevant );
+ if (logger.isInfoEnabled()) {
+ logger.info(logInProgressTransactions(inProgressTransactions, inProgressTransactionsAllCount,
+ inProgressTransactionsRelevant));
+ }
Long exclusiveRequestCount = inProgressTransactions.stream()
.filter(record -> record.getMode().equals(Flags.Mode.EXCLUSIVE.name())).count();
this.getClass().getCanonicalName());
throw new WorkflowNotFoundException(
"Workflow mapping not found for vnfType = " + vnfContext.getType() + ", command = "
- + requestContext.getAction().name(),
+ + requestContext.getAction().name(),
vnfContext.getType(), requestContext.getAction().name());
}
if (!workflowExistsOutput.isDgExist()) {
this.getClass().getCanonicalName());
throw new DGWorkflowNotFoundException(
"Workflow not found for vnfType = " + vnfContext.getType() + ", command = "
- + requestContext.getAction().name(),
+ + requestContext.getAction().name(),
workflowExistsOutput.getWorkflowModule(), workflowExistsOutput.getWorkflowName(),
workflowExistsOutput.getWorkflowVersion(), vnfContext.getType(), requestContext.getAction().name());
}
public String logInProgressTransactions(List<TransactionRecord> inProgressTransactions,
long inProgressTransactionsAllCount, long inProgressTransactionsRelevant) {
- if (inProgressTransactionsAllCount > inProgressTransactionsRelevant) {
- logger.info("Found Stale Transactions! Ignoring Stale Transactions for target, only considering "
+ if (inProgressTransactionsAllCount > inProgressTransactionsRelevant) {
+ logger.info("Found Stale Transactions! Ignoring Stale Transactions for target, only considering "
+ "transactions within the last " + transactionWindowInterval + " hours as transactions in-progress");
- }
- String logMsg="";
- for (TransactionRecord tr: inProgressTransactions) {
- logMsg = ("In Progress transaction for Target ID - "+ tr.getTargetId()
- + " in state " + tr.getRequestState()
- + " with Start time " + tr.getStartTime().toString()
- + " for more than configurable time period " + transactionWindowInterval
- + " hours [transaction details - Request ID - " + tr.getTransactionId()
- + ", Service Instance Id -" + tr.getServiceInstanceId()
- + ", Vserver_id - " + tr.getVserverId()
- + ", VNFC_name - "+ tr.getVnfcName()
- + ", VF module Id - " + tr.getVfModuleId()
- + " Start time " + tr.getStartTime().toString()
- + "]" );
- }
- return logMsg;
-
+ }
+ String logMsg = "";
+ for (TransactionRecord tr: inProgressTransactions) {
+ logMsg = ("In Progress transaction for Target ID - " + tr.getTargetId()
+ + " in state " + tr.getRequestState()
+ + " with Start time " + tr.getStartTime().toString()
+ + " for more than configurable time period " + transactionWindowInterval
+ + " hours [transaction details - Request ID - " + tr.getTransactionId()
+ + ", Service Instance Id - " + tr.getServiceInstanceId()
+ + ", Vserver_id - " + tr.getVserverId()
+ + ", VNFC_name - " + tr.getVnfcName()
+ + ", VF module Id - " + tr.getVfModuleId()
+ + " Start time " + tr.getStartTime().toString()
+ + "]");
+ }
+ return logMsg;
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import org.onap.ccsdk.sli.core.dblib.DbLibService;
import javax.sql.rowset.CachedRowSet;
-import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
this.dbLibService = dbLibService;
}
- public void initialize(){
+ public void initialize() {
try {
String jsonContent = getPolicyJson();
if (jsonContent == null) return;
policyList.stream()
.filter(policy -> PolicyNames.ActionInProgress.name().equals(policy.getPolicyName()))
.forEach(policy -> {
- Rule[] ruleDTOs = policy.getRules();
- Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
- for(Rule ruleDTO : ruleDTOs) {
- String action = ruleDTO.getActionReceived();
- String validationRule = ruleDTO.getValidationRule();
- Set<VNFOperation> inclusionSet = null;
- Set<VNFOperation> exclusionSet = null;
- if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
- inclusionSet = ruleDTO.getInclusionList().stream()
- .map(VNFOperation::findByString).filter(operation -> operation != null)
- .collect(Collectors.toSet());
- }
- if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
- exclusionSet = ruleDTO.getExclusionList().stream()
- .map(VNFOperation::findByString).filter(operation -> operation != null)
- .collect(Collectors.toSet());
- }
- org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
- .createRule(validationRule, inclusionSet, exclusionSet);
- rules.put(action, rule);
- }
- actionInProgressRuleExecutor = new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
- });
+ Rule[] ruleDTOs = policy.getRules();
+ Map<String, org.onap.appc.validationpolicy.rules.Rule> rules = new HashMap<>();
+ for (Rule ruleDTO : ruleDTOs) {
+ String action = ruleDTO.getActionReceived();
+ String validationRule = ruleDTO.getValidationRule();
+ Set<VNFOperation> inclusionSet = null;
+ Set<VNFOperation> exclusionSet = null;
+ if (ruleDTO.getInclusionList() != null && !ruleDTO.getInclusionList().isEmpty()) {
+ inclusionSet = ruleDTO.getInclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation != null)
+ .collect(Collectors.toSet());
+ }
+ if (ruleDTO.getExclusionList() != null && !ruleDTO.getExclusionList().isEmpty()) {
+ exclusionSet = ruleDTO.getExclusionList().stream()
+ .map(VNFOperation::findByString).filter(operation -> operation != null)
+ .collect(Collectors.toSet());
+ }
+ org.onap.appc.validationpolicy.rules.Rule rule = RuleFactory
+ .createRule(validationRule, inclusionSet, exclusionSet);
+ rules.put(action, rule);
+ }
+ actionInProgressRuleExecutor =
+ new ActionInProgressRuleExecutor(Collections.unmodifiableMap(rules));
+ });
} catch (Exception e) {
logger.error("Error reading request validation policies", e);
}
protected String getPolicyJson() {
String schema = "sdnctl";
- String query = "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT " +
- "FROM ASDC_ARTIFACTS " +
- "WHERE ARTIFACT_NAME = ? " +
- "GROUP BY ARTIFACT_NAME";
+ String query =
+ "SELECT MAX(INTERNAL_VERSION),ARTIFACT_CONTENT "
+ + "FROM ASDC_ARTIFACTS "
+ + "WHERE ARTIFACT_NAME = ? "
+ + "GROUP BY ARTIFACT_NAME";
ArrayList<String> arguments = new ArrayList<>();
arguments.add("request_validation_policy");
String jsonContent = null;
- try{
+ try {
CachedRowSet rowSet = dbLibService.getData(query, arguments, schema);
- if(rowSet.next()){
+ if (rowSet != null && rowSet.next()) {
jsonContent = rowSet.getString("ARTIFACT_CONTENT");
}
- if(logger.isDebugEnabled()){
+ if (logger.isDebugEnabled()) {
logger.debug("request validation policy = " + jsonContent);
}
- if(StringUtils.isBlank(jsonContent)){
+ if (StringUtils.isBlank(jsonContent)) {
logger.warn("request validation policy not found in app-c database");
}
- }
- catch(SQLException e){
+ } catch(Exception e) {
+ logger.debug("Error while accessing database: " + e.getMessage());
+ logger.info("Error connecting to database: " + e.getMessage());
logger.error("Error accessing database", e);
throw new RuntimeException(e);
}
+ logger.info("Got Policy Json");
return jsonContent;
}
- public RuleExecutor getInProgressRuleExecutor(){
- if(actionInProgressRuleExecutor == null){
+ public RuleExecutor getInProgressRuleExecutor() {
+ if (actionInProgressRuleExecutor == null) {
throw new RuntimeException("Rule executor not available, initialization of RequestValidationPolicy failed");
}
return actionInProgressRuleExecutor;
* ============LICENSE_START=======================================================
* Copyright (C) 2018-2019 Ericsson. All rights reserved.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
recorder = mock(TransactionRecorder.class);
requestHandler.setTransactionRecorder(recorder);
List<RequestStatus> result = Arrays.asList(RequestStatus.ACCEPTED);
- PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
+ PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(result);
final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
logger.setLevel(Level.TRACE);
Whitebox.setInternalState(requestHandler, "logger", logger);
PowerMockito.when(bundleContext.getService(sref)).thenReturn(metricService);
MetricRegistry metricRegistry = Mockito.mock(MetricRegistry.class);
DispatchingFuntionMetric dispatchingFunctionMetric = Mockito.mock(DispatchingFuntionMetric.class);
- DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder = Mockito.mock(DispatchingFunctionCounterBuilder.class);
+ DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder =
+ Mockito.mock(DispatchingFunctionCounterBuilder.class);
MetricBuilderFactory metricBuilderFactory = Mockito.mock(MetricBuilderFactory.class);
- Mockito.when(dispatchingFunctionCounterBuilder.withName("DISPATCH_FUNCTION")).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withType(MetricType.COUNTER)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withAcceptRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.withRejectRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
- Mockito.when(dispatchingFunctionCounterBuilder.build()).thenReturn(dispatchingFunctionMetric);
- Mockito.when(metricBuilderFactory.dispatchingFunctionCounterBuilder()).thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withName("DISPATCH_FUNCTION"))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withType(MetricType.COUNTER))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withAcceptRequestValue(0))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.withRejectRequestValue(0))
+ .thenReturn(dispatchingFunctionCounterBuilder);
+ Mockito.when(dispatchingFunctionCounterBuilder.build()).
+ thenReturn(dispatchingFunctionMetric);
+ Mockito.when(metricBuilderFactory.dispatchingFunctionCounterBuilder())
+ .thenReturn(dispatchingFunctionCounterBuilder);
Mockito.when(metricRegistry.metricBuilderFactory()).thenReturn(metricBuilderFactory);
Mockito.when(metricService.createRegistry("APPC")).thenReturn(metricRegistry);
Mockito.when(metricRegistry.register(dispatchingFunctionMetric)).thenReturn(true);
@Test
public void testMetricNullMetricService() throws Exception {
expectedEx.expect(NullPointerException.class);
- expectedEx.expectMessage("org.onap.appc.metricservice.MetricService is null. " +
- "Failed to init Metric");
+ expectedEx.expectMessage("org.onap.appc.metricservice.MetricService is null. "
+ + "Failed to init Metric");
Whitebox.invokeMethod(requestHandler, "initMetric");
}
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
* ================================================================================
+ * Modifications Copyright (C) 2019 AT&T Intellectual Property
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at
*
lockManager = mock(LockManager.class);
requestHandler.setLockManager(lockManager);
List<RequestStatus> result = Arrays.asList(RequestStatus.ACCEPTED);
- PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
+ PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(result);
final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class);
logger.setLevel(Level.TRACE);
Whitebox.setInternalState(requestHandler, "logger", logger);
doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class),
Mockito.any(LCMCommandStatus.class), Mockito.any());
doThrow(new APPCException("TEST_APPC_EXCEPTION")).when(commandExecutor)
- .executeCommand(Mockito.any(CommandExecutorInput.class));
+ .executeCommand(Mockito.any(CommandExecutorInput.class));
doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(),
Mockito.anyString(), Mockito.anyString());
requestHandler.handleRequest(runtimeContext);
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* 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=========================================================
*/
AAIService aaiService = Mockito.mock(AAIService.class);
PowerMockito.when(aaiService.query(
anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
- @Override
- public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
- Object[] args = invocation.getArguments();
- SvcLogicContext ctx = (SvcLogicContext) args[6];
- String prefix = (String) args[4];
- String key = (String) args[3];
- if (key.contains("'28'")) {
- return SvcLogicResource.QueryStatus.FAILURE;
- } else if (key.contains("'8'")) {
- return SvcLogicResource.QueryStatus.NOT_FOUND;
- } else {
- ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
- ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
+ .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
+ @Override
+ public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
+ Object[] args = invocation.getArguments();
+ SvcLogicContext ctx = (SvcLogicContext) args[6];
+ String prefix = (String) args[4];
+ String key = (String) args[3];
+ if (key.contains("'28'")) {
+ return SvcLogicResource.QueryStatus.FAILURE;
+ } else if (key.contains("'8'")) {
+ return SvcLogicResource.QueryStatus.NOT_FOUND;
+ } else {
+ ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
+ ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
+ }
+ return SvcLogicResource.QueryStatus.SUCCESS;
}
- return SvcLogicResource.QueryStatus.SUCCESS;
- }
- });
+ });
PowerMockito.mockStatic(FrameworkUtil.class);
PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
transactionRecord.setRequestState(RequestStatus.ACCEPTED);
runtimeContext.setTransactionRecord(transactionRecord);
transactionRecordList.add(transactionRecord);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
- .thenReturn(transactionRecordList);
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
+ .thenReturn(transactionRecordList);
impl.setTransactionRecorder(transactionRecorder);
WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
- Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))).thenReturn(workflowExistsOutput);
+ Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
- Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))).thenReturn(ruleResult);
+ Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
inProgressTransaction.setStartTime(Instant.now().minus(5, ChronoUnit.HOURS));
inProgressTransaction.setRequestState(RequestStatus.ACCEPTED);
transactionRecordList.add(inProgressTransaction);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
.thenReturn(transactionRecordList);
runtimeContext.setTransactionRecord(inProgressTransaction);
impl.setTransactionRecorder(transactionRecorder);
WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
inProgressTransaction.setRequestState(RequestStatus.ACCEPTED);
inProgressTransaction.setStartTime(Instant.now().minus(48, ChronoUnit.HOURS));
transactionRecordList.add(inProgressTransaction);
- Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),Mockito.any(int.class)))
- .thenReturn(transactionRecordList);
+ Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class),
+ Mockito.any(int.class)))
+ .thenReturn(transactionRecordList);
Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
impl.setTransactionRecorder(transactionRecorder);
runtimeContext.setTransactionRecord(inProgressTransaction);
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
RuleResult ruleResult = RuleResult.ACCEPT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
RequestContext requestContext = new RequestContext();
ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
Mockito.when(workflowExistsOutput.isMappingExist()).thenReturn(false);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");;
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
- .thenReturn(workflowExistsOutput);
+ .thenReturn(workflowExistsOutput);
Mockito.when(workflowExistsOutput.isDgExist()).thenReturn(false);
impl.setWorkflowManager(workflowManager);
ResponseContext responseContext = runtimeContext.getResponseContext();
returnResponseContextCommonHeader(responseContext);
RestClientInvoker client = mock(RestClientInvoker.class);
- HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
+ HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), 200, "ACCEPTED");
httpResponse.setEntity(getHttpEntity());
Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
impl.setClient(client);
RuleResult ruleResult = RuleResult.REJECT;
Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
- .thenReturn(ruleResult);
+ .thenReturn(ruleResult);
impl.setRequestValidationPolicy(requestValidationPolicy);
impl.validateRequest(runtimeContext);
}
private BasicHttpEntity getHttpEntity() {
BasicHttpEntity httpEntity = new BasicHttpEntity();
InputStream inputStream = new ByteArrayInputStream(
- "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}".getBytes());
+ "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}"
+ .getBytes());
httpEntity.setContent(inputStream);
return httpEntity;
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
- * ================================================================================
- * Modifications (C) 2019 Ericsson
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
* ============LICENSE_END=========================================================
*/
package org.onap.appc.workflow.impl;
import org.apache.commons.lang.ObjectUtils;
+import org.apache.commons.lang3.StringUtils;
import org.onap.appc.common.constant.Constants;
import org.onap.appc.configuration.Configuration;
import org.onap.appc.configuration.ConfigurationFactory;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
import org.onap.ccsdk.sli.core.sli.provider.SvcLogicService;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.ServiceReference;
+import java.util.ArrayList;
+import java.util.List;
+import org.onap.ccsdk.sli.core.dblib.DbLibService;
+import org.onap.ccsdk.sli.core.sli.SvcLogicGraph;
+import javax.sql.rowset.CachedRowSet;
+import java.sql.SQLException;
+import java.sql.Blob;
+import java.io.ObjectInputStream;
+import java.io.IOException;
+import org.slf4j.MDC;
+
+
+
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Enumeration;
public class WorkFlowManagerImpl implements WorkFlowManager{
+ private static final String DRIVER_ERROR = "DriverLoadError";
private SvcLogicService svcLogic = null;
private final EELFLogger logger = EELFManager.getInstance().getLogger(WorkFlowManagerImpl.class);
private final Configuration configuration = ConfigurationFactory.getConfiguration();
/**
* Execute workflow and return response.
* This method execute workflow with following steps.
- * Retrieve workflow(DG) details - module, version and mode from database based on command and vnf Type from incoming request.
+ * Retrieve workflow(DG) details - module, version and mode from database
+ * based on command and vnf Type from incoming request.
* Execute workflow (DG) using SVC Logic Service reference
* Return response of workflow (DG) to caller.
*
- * @param workflowRequest workflow execution request which contains vnfType, command, requestId, targetId, payload and (optional) confID;
+ * @param workflowRequest workflow execution request which contains vnfType,
+ * command, requestId, targetId, payload and (optional) confID;
* @return Workflow Response which contains execution status and payload from DG if any
*/
@Override
public WorkflowResponse executeWorkflow(WorkflowRequest workflowRequest) {
- if (logger.isTraceEnabled()) {
- logger.trace("Entering to executeWorkflow with WorkflowRequest = " + ObjectUtils.toString(workflowRequest.toString()));
- }
+ logger.trace("Entering to executeWorkflow with WorkflowRequest = "
+ + ObjectUtils.toString(workflowRequest.toString()));
WorkflowResponse workflowResponse = new WorkflowResponse();
workflowResponse.setResponseContext(workflowRequest.getResponseContext());
try {
- WorkflowKey workflowKey = workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(), workflowRequest.getVnfContext().getType(), null,workflowRequest.getRequestContext().getCommonHeader().getApiVer());
+ WorkflowKey workflowKey =
+ workflowResolver.resolve(workflowRequest.getRequestContext().getAction().name(),
+ workflowRequest.getVnfContext().getType(), null,
+ workflowRequest.getRequestContext().getCommonHeader().getApiVer());
Properties workflowParams = new Properties();
String actionProperty;
String requestIdProperty;
String vfIdProperty;
- if(!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){
+ if (!workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")) {
/*
The following method call (populateDGContext) populates DG context with the
request parameters to maintain backward compatibility with old DGs,
we are not altering the old way of passing (org.onap.appc.vnfId and so on..)
This is still a temporary solution, the end solution should be agreed with
all stakeholders and implemented.
- */
+ */
populateDGContext(workflowParams, workflowRequest);
} else {
- actionProperty = configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION));
- requestIdProperty = configuration.getProperty("org.onap.appc.workflow.request.id", String.valueOf(Constants.REQUEST_ID));
- vfIdProperty = configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID));
- String vfTypeProperty = configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE));
- String apiVerProperty = configuration.getProperty("org.onap.appc.workflow.apiVersion", String.valueOf(Constants.API_VERSION));
- String originatorIdProperty = configuration.getProperty("org.onap.appc.workflow.originatorId", Constants.ORIGINATOR_ID);
- String subRequestId = configuration.getProperty("org.onap.appc.workflow.subRequestId", Constants.SUB_REQUEST_ID);
+ actionProperty =
+ configuration.getProperty("org.onap.appc.workflow.action", String.valueOf(Constants.ACTION));
+ requestIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.request.id",
+ String.valueOf(Constants.REQUEST_ID));
+ vfIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.vfid", String.valueOf(Constants.VF_ID));
+ String vfTypeProperty =
+ configuration.getProperty("org.onap.appc.workflow.vftype", String.valueOf(Constants.VF_TYPE));
+ String apiVerProperty =
+ configuration.getProperty("org.onap.appc.workflow.apiVersion",
+ String.valueOf(Constants.API_VERSION));
+ String originatorIdProperty =
+ configuration.getProperty("org.onap.appc.workflow.originatorId", Constants.ORIGINATOR_ID);
+ String subRequestId =
+ configuration.getProperty("org.onap.appc.workflow.subRequestId", Constants.SUB_REQUEST_ID);
workflowParams.put(actionProperty, workflowRequest.getRequestContext().getAction().name());
- workflowParams.put(requestIdProperty, workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ workflowParams.put(requestIdProperty,
+ workflowRequest.getRequestContext().getCommonHeader().getRequestId());
workflowParams.put(vfIdProperty, workflowRequest.getVnfContext().getId());
workflowParams.put(vfTypeProperty, workflowRequest.getVnfContext().getType());
workflowParams.put(apiVerProperty, workflowRequest.getRequestContext().getCommonHeader().getApiVer());
- workflowParams.put(originatorIdProperty, workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
- workflowParams.put(subRequestId, workflowRequest.getRequestContext().getCommonHeader().getSubRequestId());
+ workflowParams.put(originatorIdProperty,
+ workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
+ workflowParams.put(subRequestId,
+ workflowRequest.getRequestContext().getCommonHeader().getSubRequestId());
Object payloadJson = workflowRequest.getRequestContext().getPayload();
- if(payloadJson != null) {
+ if (payloadJson != null) {
try {
Map<String, String> payloadProperties = ObjectMapper.map(payloadJson);
workflowParams.putAll(payloadProperties);
logger.error("Error parsing payload json string", e);
Properties workflowPrp = new Properties();
workflowPrp.setProperty("error-message", "Error parsing payload json string");
- fillStatus(501, "Error parsing payload json string: " + e.getMessage(), workflowRequest.getResponseContext());
- logger.trace("Exiting from executeWorkflow with (workflowResponse = " + ObjectUtils.toString(workflowResponse) + ")");
+ fillStatus(501, "Error parsing payload json string: " + e.getMessage(),
+ workflowRequest.getResponseContext());
+ logger.trace("Exiting from executeWorkflow with (workflowResponse = "
+ + ObjectUtils.toString(workflowResponse) + ")");
return workflowResponse;
}
}
- logger.debug("DG parameters "+ actionProperty +":"+ workflowRequest.getRequestContext().getAction().name() + ", "+
- requestIdProperty +":"+ workflowRequest.getRequestContext().getCommonHeader().getRequestId() + ", " +
- vfIdProperty + ":" + workflowRequest.getVnfContext().getId());
-
- logger.debug("Starting DG Execution for request "+workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ logger.debug("DG parameters " + actionProperty + ":"
+ + workflowRequest.getRequestContext().getAction().name() + ", "
+ + requestIdProperty + ":"
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + ", "
+ + vfIdProperty + ":" + workflowRequest.getVnfContext().getId());
+
+ logger.debug("Starting DG Execution for request "
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId());
}
- if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")){
+ if (workflowRequest.getRequestContext().getCommonHeader().getApiVer().startsWith("1.")) {
workflowParams.put("isBwcMode", "true");
} else {
workflowParams.put("isBwcMode", "false");
}
- SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams , workflowResponse);
- logger.trace("Completed DG Execution for Request id: " + workflowRequest.getRequestContext().getCommonHeader().getRequestId()
- + "with response code: " + workflowResponse.getResponseContext().getStatus().getCode());
- }catch (Exception e){
+ SVCLogicServiceExecute(workflowKey, workflowRequest.getRequestContext(), workflowParams,
+ workflowResponse);
+ logger.trace("Completed DG Execution for Request id: "
+ + workflowRequest.getRequestContext().getCommonHeader().getRequestId() + " with response code: "
+ + workflowResponse.getResponseContext().getStatus().getCode());
+ } catch (Exception e) {
logger.error("Error Executing DG " + e.getMessage(), e);
- fillStatus(501, "Error Executing DG "+ e.getMessage(), workflowRequest.getResponseContext());
+ fillStatus(501, "Error Executing DG " + e.getMessage(), workflowRequest.getResponseContext());
}
- logger.trace("Exiting from executeWorkflow with (workflowResponse = " +
- ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage()) + ")");
+ logger.trace("Exiting from executeWorkflow with (workflowResponse = "
+ + ObjectUtils.toString(workflowResponse.getResponseContext().getStatus().getMessage()) + ")");
return workflowResponse;
}
private void populateDGContext(Properties workflowParams, WorkflowRequest workflowRequest) {
- workflowParams.put("input.common-header.timestamp", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()));
- workflowParams.put("input.common-header.api-ver", workflowRequest.getRequestContext().getCommonHeader().getApiVer());
- workflowParams.put("input.common-header.request-id", workflowRequest.getRequestContext().getCommonHeader().getRequestId());
- workflowParams.put("input.common-header.originator-id", workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
- workflowParams.put("input.common-header.sub-request-id", workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() != null ?
+ workflowParams.put("input.common-header.timestamp",
+ new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
+ .format(workflowRequest.getRequestContext().getCommonHeader().getTimeStamp()));
+ workflowParams.put("input.common-header.api-ver",
+ workflowRequest.getRequestContext().getCommonHeader().getApiVer());
+ workflowParams.put("input.common-header.request-id",
+ workflowRequest.getRequestContext().getCommonHeader().getRequestId());
+ workflowParams.put("input.common-header.originator-id",
+ workflowRequest.getRequestContext().getCommonHeader().getOriginatorId());
+ workflowParams.put("input.common-header.sub-request-id",
+ workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() != null ?
workflowRequest.getRequestContext().getCommonHeader().getSubRequestId() : "");
workflowParams.put("input.action", workflowRequest.getRequestContext().getAction().toString());
- workflowParams.put("input.payload", null != workflowRequest.getRequestContext().getPayload() ?
+ workflowParams.put("input.payload",
+ null != workflowRequest.getRequestContext().getPayload() ?
workflowRequest.getRequestContext().getPayload() : "");
workflowParams.put("input.action-identifiers.vnf-id", workflowRequest.getVnfContext().getId());
- workflowParams.put("input.action-identifiers.vnfc-name", workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() != null ?
+ workflowParams.put("input.action-identifiers.vnfc-name",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVnfcName() : "");
- workflowParams.put("input.action-identifiers.service-instance-id", workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() !=null ?
+ workflowParams.put("input.action-identifiers.service-instance-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getServiceInstanceId() : "");
- workflowParams.put("input.action-identifiers.vserver-id", workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() !=null ?
+ workflowParams.put("input.action-identifiers.vserver-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVserverId() : "");
- workflowParams.put("input.action-identifiers.vf-module-id",workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() !=null ?
+ workflowParams.put("input.action-identifiers.vf-module-id",
+ workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() != null ?
workflowRequest.getRequestContext().getActionIdentifiers().getVfModuleId() : "");
final Map<String, String> additionalContext;
if ((additionalContext = workflowRequest.getRequestContext().getAdditionalContext()) != null) {
*/
@Override
public WorkflowExistsOutput workflowExists(WorkflowRequest workflowQueryParams) {
- WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false,false);
- logger.trace("Entering to workflowExists with WorkflowRequest = " + ObjectUtils.toString(workflowQueryParams.toString()));
+ WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(false, false);
+ logger.trace("Entering to workflowExists with WorkflowRequest = "
+ + ObjectUtils.toString(workflowQueryParams.toString()));
try {
WorkflowKey workflowKey = workflowResolver.resolve(
workflowExistsOutput.setWorkflowVersion(workflowKey.version());
if (isDGExists(workflowKey)) {
workflowExistsOutput.setDgExist(true);
- }else{
+ } else {
logger.warn(
- String.format("SLI doesn't have DG for resolved mapping entry: DG module - '%s', DG name - '%s', DG version - '%s'",
- workflowKey.module(), workflowKey.name(), workflowKey.version()));
+ String.format("SLI doesn't have DG for resolved mapping entry: "
+ + "DG module - '%s', DG name - '%s', DG version - '%s'",
+ workflowKey.module(), workflowKey.name(), workflowKey.version()));
}
- }else{
+ } else {
logger.warn(
- String.format("Unable to resolve recipe matching action '%s', VNF type '%s' and VNF version '%s'",
- workflowQueryParams.getRequestContext().getAction().name(), workflowQueryParams.getVnfContext().getType(), null));
+ String.format("Unable to resolve recipe matching action '%s', VNF type '%s'"
+ + " and VNF version '%s'",
+ workflowQueryParams.getRequestContext().getAction().name(),
+ workflowQueryParams.getVnfContext().getType(), null));
}
} catch (RuntimeException e) {
- logger.error("Error querying workflow from database"+e.getMessage());
+ logger.error("Error querying workflow from database" + e.getMessage());
throw e;
- }catch (SvcLogicException e) {
- logger.error("Error querying workflow from database"+e.getMessage());
+ } catch (SvcLogicException e) {
+ logger.error("Error querying workflow from database" + e.getMessage());
throw new RuntimeException(e);
}
logger.trace("Exiting workflowExists");
return svcLogic.hasGraph(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync");
}
- private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext, Properties workflowParams, WorkflowResponse workflowResponse) {
+
+ private void restartDbLibProvider() {
+
+ Bundle bundle = FrameworkUtil.getBundle(org.onap.ccsdk.sli.core.dblib.DbLibService.class);
+ try {
+ bundle.stop();
+ bundle.start();
+ //Thread.sleep(5000);
+ } catch (org.osgi.framework.BundleException be) {
+ logger.error("Error restarting db lib" + be.toString());
+ } /*catch (InterruptedException e) {
+ }*/
+ }
+
+ private SvcLogicGraph fetchGraph(String module, String rpc, String version, String mode, StringBuilder sbError)
+ {
+ DbLibService dbLibSvc = null;
+
+ ServiceReference sref = null;
+ BundleContext bctx = null;
+
+ Bundle bundle = FrameworkUtil.getBundle(WorkFlowManagerImpl.class);
+
+ if (bundle != null) {
+ bctx = bundle.getBundleContext();
+
+ if (bctx != null) {
+ sref = bctx.getServiceReference("org.onap.ccsdk.sli.core.dblib.DbLibService");
+ }
+
+ if (sref == null) {
+ logger.warn("Could not find service reference for DBLIB service");
+ } else {
+ dbLibSvc = (DbLibService) bctx.getService(sref);
+ if (dbLibSvc == null) {
+ logger.warn("Could not find service reference for DBLIB service");
+ }
+ }
+ }
+ if (dbLibSvc == null)
+ return null;
+ else
+ logger.info("Retrieving graph(new)");
+
+ SvcLogicGraph retval = null;
+ CachedRowSet results = null;
+
+ String fetchVersionGraphSql = "SELECT graph FROM SVC_LOGIC"
+ + " WHERE module = ? AND rpc = ? AND mode = ? AND version = ?";
+
+ String fetchActiveGraphSql = "SELECT graph FROM SVC_LOGIC"
+ + " WHERE module = ? AND rpc = ? AND mode = ? AND active = 'Y'";
+
+
+ String fetchGraphStmt;
+
+ ArrayList<String> params = new ArrayList<>();
+ params.add(module);
+ params.add(rpc);
+ params.add(mode);
+
+ if (version == null) {
+ fetchGraphStmt = fetchActiveGraphSql;
+ } else {
+ params.add(version);
+ fetchGraphStmt = fetchVersionGraphSql;
+ }
+
+ StringBuilder sqlBuilder = new StringBuilder(fetchGraphStmt);
+ try {
+ results = dbLibSvc.getData(sqlBuilder.toString(), new ArrayList(params), "sdnctl");
+
+ if (results.next()) {
+
+ ObjectInputStream gStream = new ObjectInputStream(results.getBinaryStream("graph"));
+
+ Object graphObj = gStream.readObject();
+ gStream.close();
+
+ if (graphObj instanceof SvcLogicGraph) {
+ retval = (SvcLogicGraph) graphObj;
+ } else {
+ logger.error("invalid type for graph " + graphObj.getClass().getName());
+ return null;
+ }
+
+ } else {
+ return null;
+ }
+ } catch (SQLException e) {
+ logger.error("query " + sqlBuilder + " :: " + e.getMessage() + " Will retry");
+ //sbError.append(DRIVER_ERROR);
+ return null;
+ } catch (IOException e) {
+ logger.error("IOException " + " :: " + e.getMessage() + " Will retry");
+ //sbError.append(DRIVER_ERROR);
+ return null;
+ } catch (Exception e) {
+ logger.error("Exception " + " :: " + e.getMessage() + " Will retry");
+ sbError.append(DRIVER_ERROR);
+ return null;
+ }
+
+
+ return retval;
+ }
+
+ protected Properties workflowExecute(String module, String rpc, String version, String mode, Properties props)
+ throws SvcLogicException {
+ logger.info("Fetching service logic from data store");
+ //logger.info("Trial Restart ");
+ //restartDbLibProvider();
+ //logger.info("Trial Restart End");
+
+ StringBuilder sbError = new StringBuilder();
+ SvcLogicGraph graph = fetchGraph(module, rpc, version, mode, sbError);
+ if (sbError.toString().equals(DRIVER_ERROR))
+ {
+ restartDbLibProvider();
+ sbError = new StringBuilder();
+ graph = fetchGraph(module, rpc, version, mode, sbError);
+ }
+ if (graph == null) {
+ Properties retProps = new Properties();
+ retProps.setProperty("error-code", "401");
+ retProps.setProperty("error-message",
+ "No service logic found for [" + module + "," + rpc + "," + version + "," + mode + "]");
+ return (retProps);
+ }
+
+ SvcLogicContext ctx = new SvcLogicContext(props);
+ ctx.setAttribute("currentGraph", graph.toString());
+ ctx.setAttribute("X-ONAP-RequestID", MDC.get("X-ONAP-RequestID"));
+ svcLogic.execute(graph, ctx);
+ return (ctx.toProperties());
+ }
+
+ private void SVCLogicServiceExecute(WorkflowKey workflowKey, RequestContext requestContext,
+ Properties workflowParams, WorkflowResponse workflowResponse) {
logger.trace("Entering SVCLogicServiceExecute");
Properties respProps = null;
try {
- respProps = svcLogic.execute(workflowKey.module(), workflowKey.name(), workflowKey.version(), "sync", workflowParams);
+ respProps = workflowExecute(workflowKey.module(), workflowKey.name(), workflowKey.version(),
+ "sync", workflowParams);
} catch (Exception e) {
- setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure", "Unexpected SLI Adapter failure", 200);
+ setWorkFlowResponseStatus(workflowResponse.getResponseContext(), "failure",
+ "Unexpected SLI Adapter failure", 200);
+
+ String stk = "";
if (logger.isDebugEnabled()) {
- logger.debug("Error while executing DG " + e.getMessage() + e.getStackTrace());
- logger.error("Error in DG", e.getMessage() + Arrays.toString(e.getStackTrace()), e);
+ stk = Arrays.toString(e.getStackTrace());
+ logger.debug("Error while executing DG " + e.getMessage() + stk);
}
+ logger.error("Error in DG", e.getMessage() + stk, e);
}
if (respProps != null) {
specificStatusCode = Integer.parseInt(dgOutputStatusCode);
}
- setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage, specificStatusCode);
+ setWorkFlowResponseStatus(workflowResponse.getResponseContext(), commonStatus, specificStatusMessage,
+ specificStatusCode);
logger.debug("DG Execution Status: " + commonStatus);
}
* @param responseContext response context which you need to fill
* @param respProps DG context in a properties format
*/
- private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext, Properties respProps) {
+ private void fillResponseContextByOutputFieldsFromDgContext(ResponseContext responseContext,
+ Properties respProps) {
Enumeration<?> e = respProps.propertyNames();
- while (e.hasMoreElements()){
+ while (e.hasMoreElements()) {
String key = (String) e.nextElement();
- if (key.startsWith("output.")){
- if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")){
+ if (key.startsWith("output.")) {
+ if (!key.startsWith("output.common-header.") && !key.startsWith("output.status.")) {
- if (key.equalsIgnoreCase("output.payload")){
+ if (key.equalsIgnoreCase("output.payload")) {
responseContext.setPayload(respProps.getProperty(key));
} else {
responseContext.addKeyValueToAdditionalContext(key, respProps.getProperty(key));
- }
+ }
}
}
}
}
/**
- * Filling responceContext status code amd message according to responce messages and codes from DG.
+ * Filling responseContext status code and message according to response messages and codes from DG.
*
* @param responseContext response cotext
* @param commonStatus common status message from DG ("success" or "failure")
* @param specificStatusMessage specific status message from specific DG node
* @param specificStatusCode specific status code from specific DG node
*/
- private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus, String specificStatusMessage, int specificStatusCode) {
+ private void setWorkFlowResponseStatus(ResponseContext responseContext, String commonStatus,
+ String specificStatusMessage, int specificStatusCode) {
if (null == specificStatusMessage) { specificStatusMessage = ""; }
- if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)){
- if (specificStatusCode != 0 ){
+ if (commonStatus.equalsIgnoreCase(Constants.DG_STATUS_SUCCESS)) {
+ if (specificStatusCode != 0) {
fillStatus(specificStatusCode, specificStatusMessage, responseContext);
} else {
fillStatus(400, commonStatus, responseContext);
}
} else {
- if (specificStatusCode != 0){
+ if (specificStatusCode != 0) {
fillStatus(specificStatusCode, specificStatusMessage, responseContext);
} else {
fillStatus(401, specificStatusMessage, responseContext);
*
* @param code 3-digit status code
* @param message explanation of a status code
- * @param responceContext response context which will be store status code and status message
+ * @param responseContext response context which will be store status code and status message
*/
- private void fillStatus(int code, String message, ResponseContext responceContext) {
- responceContext.getStatus().setCode(code);
- responceContext.getStatus().setMessage(message);
+ private void fillStatus(int code, String message, ResponseContext responseContext) {
+ responseContext.getStatus().setCode(code);
+ responseContext.getStatus().setMessage(message);
}
+
+
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import java.util.Date;
import java.util.Properties;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({ConfigurationFactory.class, DBUtils.class, ObjectMapper.class})
+@PrepareForTest({ConfigurationFactory.class, DBUtils.class, ObjectMapper.class, WorkFlowManagerImpl.class})
public class TestWorkFlowManager {
@Rule
public ExpectedException expectedEx = ExpectedException.none();
-
+
public TestWorkFlowManager() {
}
public SvcLogicService svcLogicService;
@Before
- public void init(){
+ public void init() {
PowerMockito.mockStatic(ConfigurationFactory.class);
Configuration mockConfiguration = Mockito.mock(Configuration.class);
PowerMockito.when(ConfigurationFactory.getConfiguration()).thenReturn(mockConfiguration);
this.svcLogicService = Mockito.mock(SvcLogicService.class);
workflowManger.setWorkflowResolver(workflowResolver);
workflowManger.setSvcLogicServiceRef(svcLogicService);
-
}
+
@Test
- public void testExecuteWorkFlow() throws SvcLogicException{
+ public void testExecuteWorkFlow() throws SvcLogicException, Exception {
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowResponse response = workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("success"));
}
@Test
- public void testExecuteWorkFlowFalse() throws SvcLogicException{
+ public void testExecuteWorkFlowFalse() throws SvcLogicException, Exception {
+
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteFailureResponse());
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteFailureResponse());
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteFailureResponse());
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("failure"));
}
@Test
- public void testExecuteWorkFlowAPIVersionStartWithOne() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
+ public void testExecuteWorkFlowAPIVersionStartWithOne() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertTrue(response.getResponseContext().getStatus().getMessage().equals("success"));
}
@Test
- public void testExecuteWorkFlowException() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
-
- WorkflowRequest workflowRequest = Mockito.spy(getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD));
+ public void testExecuteWorkFlowException() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowRequest workflowRequest =
+ Mockito.spy(getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD));
Mockito.when(workflowRequest.getRequestContext()).thenThrow(new RuntimeException());
- WorkflowResponse response = workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Mockito.verify(workflowRequest, Mockito.times(2)).getResponseContext();
}
@Test
- public void testExecuteWorkAPIVersion1Exception() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
- .thenReturn(createSvcExexuteSuccessResponse());
-
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ public void testExecuteWorkAPIVersion1Exception() throws SvcLogicException, Exception {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ // Mockito.when(svcLogicService.execute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ // .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "1.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
PowerMockito.mockStatic(ObjectMapper.class);
PowerMockito.when(ObjectMapper.map(Mockito.any())).thenThrow(new RuntimeException());
- WorkflowResponse response=workflowManger.executeWorkflow(workflowRequest);
+ WorkFlowManagerImpl mockManager = Mockito.spy(workflowManger);
+ Mockito.when(mockManager.workflowExecute(anyString(), anyString(), anyString(), anyString(), anyObject()))
+ .thenReturn(createSvcExexuteSuccessResponse());
+
+ WorkflowResponse response = mockManager.executeWorkflow(workflowRequest);
Assert.assertEquals(501, response.getResponseContext().getStatus().getCode());
}
@Test
- public void testWorkFlowExist() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
+ public void testWorkFlowExist() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(true);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
}
@Test
- public void testWorkFlowNotExist() throws SvcLogicException {
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(getWorkFlowKey());
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(false);
+ public void testWorkFlowNotExist() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(getWorkFlowKey());
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(false);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
}
@Test
- public void testWorkFlowExistNullKey() throws SvcLogicException{
- Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString())).thenReturn(null);
- Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
- WorkflowRequest workflowRequest = getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
- VNFOperation.Lock, "mj13", Constants.PAYLOAD);
+ public void testWorkFlowExistNullKey() throws SvcLogicException {
+ Mockito.when(workflowResolver.resolve(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(null);
+ Mockito.when(svcLogicService.hasGraph(anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(true);
+ WorkflowRequest workflowRequest =
+ getWorkflowRequest("vSCP", 300, new Date(), "2.00", "ST_249", "O1652", "uid34",
+ VNFOperation.Lock, "mj13", Constants.PAYLOAD);
WorkflowExistsOutput response = workflowManger.workflowExists(workflowRequest);
Assert.assertFalse(response.isMappingExist());
}
workflowResolver.resolve("ACTION", "VNF_TYPE", "VNF_VERSION", "API_VERSION");
}
- private WorkflowRequest getWorkflowRequest(String vnfType, int ttl, Date timeStamp, String apiVersion, String requestId,
- String originatorID, String subRequestID, VNFOperation action, String vnfId , String payload) {
+ private WorkflowRequest getWorkflowRequest(String vnfType, int ttl, Date timeStamp, String apiVersion,
+ String requestId, String originatorID, String subRequestID, VNFOperation action, String vnfId,
+ String payload) {
WorkflowRequest workflowRequest = new WorkflowRequest();
RuntimeContext runtimeContext = createRuntimeContext();
workflowRequest.setResponseContext(runtimeContext.getResponseContext());
workflowRequest.setVnfContext(runtimeContext.getVnfContext());
- return workflowRequest;
+ return workflowRequest;
}
- private RequestContext creatRequestContext(){
+ private RequestContext creatRequestContext() {
RequestContext requestContext = new RequestContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
requestContext.setCommonHeader(commonHeader);
requestContext.setActionIdentifiers(actionIdentifiers);
- return requestContext;
+ return requestContext;
}
- private ResponseContext createResponseContext(){
+ private ResponseContext createResponseContext() {
ResponseContext responseContext = new ResponseContext();
CommonHeader commonHeader = new CommonHeader();
Flags flags = new Flags();
responseContext.setStatus(status);
commonHeader.setFlags(flags);
- return responseContext;
+ return responseContext;
}
- private RuntimeContext createRuntimeContext(){
+ private RuntimeContext createRuntimeContext() {
RuntimeContext runtimeContext = new RuntimeContext();
RequestContext requestContext = creatRequestContext();
ResponseContext responseContext = createResponseContext();
return runtimeContext;
}
- public WorkflowKey getWorkFlowKey(){
+ public WorkflowKey getWorkFlowKey() {
WorkflowKey workflowKey = new WorkflowKey("APPCDG", "2.0.0.0", "dgModule");
return workflowKey;
}
- private Properties createSvcExexuteSuccessResponse(){
+ private Properties createSvcExexuteSuccessResponse() {
Properties properties = new Properties();
properties.setProperty("output.payload", "success");
properties.setProperty(Constants.DG_ATTRIBUTE_STATUS, "success");
return properties;
}
- private Properties createSvcExexuteFailureResponse(){
+ private Properties createSvcExexuteFailureResponse() {
Properties properties = new Properties();
properties.setProperty("output.payload", "failure");
properties.setProperty(Constants.DG_ATTRIBUTE_STATUS, "failure");
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_ID;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_INFORMATION;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME;
+import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_NAME;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_TYPE;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_UUID;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_VERSION;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.URL;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.OPENSTACK;
import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ANSIBLE;
-
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.io.ByteArrayOutputStream;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
+import org.json.JSONException;
import org.json.JSONObject;
import org.onap.appc.artifact.handler.dbservices.DBException;
import org.onap.appc.artifact.handler.dbservices.DBService;
import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
import org.onap.sdnc.config.params.transformer.tosca.ArtifactProcessorImpl;
import org.onap.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException;
-
-import org.json.JSONException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
private static final String CONFIG_SCALE_OUT_PARAM = "ConfigScaleOut";
private static final String CONFIG_MODIFY_PARAM = "ConfigModify";
private static final String GET_CONFIG = "GetConfig";
- private static final String POST_EVACUATE= "PostEvacuate";
+ private static final String POST_EVACUATE = "PostEvacuate";
private static final String PRE_EVACUATE = "PreEvacuate";
private static final String POST_MIGRATE = "PostMigrate";
private static final String PRE_MIGRATE = "PreMigrate";
private static final String PRE_REBUILD = "PreRebuild";
private static final String POST_REBUILD = "PostRebuild";
private static final String STOP_TRAFFIC = "StopTraffic";
+
public void processArtifact(Map<String, String> inParams, SvcLogicContext ctx) throws ArtifactProcessorException {
if (inParams == null || inParams.isEmpty()) {
return;
}
String postData = inParams.get("postData");
- if ( StringUtils.isBlank(postData)) {
+ if (StringUtils.isBlank(postData)) {
return;
}
try {
}
private boolean storeUpdateSdcArtifacts(JSONObject postDataJson) throws ArtifactHandlerInternalException {
- log.info("Starting processing of SDC Artifacs into Handler with Data : " + postDataJson.toString());
+ log.info("Starting processing of SDC Artifacts into Handler with Data: " + postDataJson.toString());
try {
JSONObject requestInfo = (JSONObject) postDataJson.get(REQUEST_INFORMATION);
JSONObject documentInfo = (JSONObject) postDataJson.get(DOCUMENT_PARAMETERS);
String artifactName = documentInfo.getString(ARTIFACT_NAME);
- if (StringUtils.isBlank(artifactName))
- throw new ArtifactHandlerInternalException("Missing Artifact Name ");
+ if (StringUtils.isBlank(artifactName)) {
+ throw new ArtifactHandlerInternalException("Missing Artifact Name");
+ }
if (artifactName.toLowerCase().startsWith(ANSIBLE)) {
validateAnsibleAdminArtifact(documentInfo);
+ ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID), e);
throw new ArtifactHandlerInternalException("Error while processing request with id: "
+ ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID)
- + ", Exception Message : " + e.getMessage(), e);
+ + ", Exception Message: " + e.getMessage(), e);
}
return false;
}
String fn = "ArtifactHandlerNode.validateAnsibleAdminArtifact";
String artifactName = documentInfo.getString(ARTIFACT_NAME);
- log.info(fn + ": Received Admin File Name: " + artifactName + " ArtifactCotent : "
- + documentInfo.getString(ARTIFACT_CONTENTS));
+ log.info(fn + ": Received Admin File Name: " + artifactName
+ + ", ArtifactContent: " + documentInfo.getString(ARTIFACT_CONTENTS));
try {
ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
JSONObject artifact = new JSONObject(contentString);
JSONArray fqdnList = artifact.getJSONArray("fqdn-list");
Map<String, List<String>> artifactMap = new HashMap<>();
-
-
+
for (int i = 0; i < fqdnList.length(); i++) {
JSONObject fqdn = fqdnList.getJSONObject(i);
List<String> valuesforFQDN = populateValueForFQDN(fqdn);
validateKeyValue(artifactMap);
} catch (JSONException je) {
- log.error(
- fn + " ansible_admin artifact content may not be a valid JSON, error message : " + je.getMessage());
+ log.error(fn + " ansible admin artifact content may not be a valid JSON, error message: "
+ + je.getMessage());
throw new ArtifactHandlerInternalException(
- "JSON Exception:ansible admin artifact content may not be a valid JSON, error message : " + je.getMessage(), je);
+ "JSON Exception:ansible admin artifact content may not be a valid JSON, error message: "
+ + je.getMessage(),
+ je);
} catch (ArtifactHandlerInternalException ae) {
- throw ae;
+ throw ae;
} catch (Exception e) {
-
log.error(fn + "Error while creating Admin data records", e);
- throw new ArtifactHandlerInternalException("Error while processing ansible admin artifact" + e.getMessage(), e);
+ throw new ArtifactHandlerInternalException(
+ "Error while processing ansible admin artifact: " + e.getMessage(), e);
}
}
+
private void validateKeyValue(Map<String, List<String>> artifactMap) throws ArtifactHandlerInternalException {
- for (Map.Entry<String,List<String>> entry1:artifactMap.entrySet()) {
- for (String value : entry1.getValue()) {
- for(Map.Entry<String,List<String>> entry2:artifactMap.entrySet() ) {
- if (!entry1.getKey().equals(entry2.getKey()) && entry2.getValue().contains(value)) {
- log.info("Validation Failure, error message : Ansible Admin artifact has CloudOwner-RegionId-Tenant : " + value
- + " mapped to multiple FQDN :" + entry1.getKey() + " & " + entry2.getKey());
- throw new ArtifactHandlerInternalException(
- "Validation Failure, error message : Ansible Admin artifact has CloudOwner-RegionId-Tenant : " + value
- + " mapped to multiple FQDN :" + entry1.getKey() + " & " + entry2.getKey());
- }
+ for (String fqdn1 : artifactMap.keySet()) {
+
+ for (String value : artifactMap.get(fqdn1)) {
+ for (String fqdn2 : artifactMap.keySet()) {
+
+ if (!fqdn1.equals(fqdn2) && artifactMap.get(fqdn2).contains(value)) {
+ String msg = "Validation Failure: Ansible Admin artifact has CloudOwner-RegionId-Tenant: "
+ + value + " mapped to multiple FQDN: " + fqdn1 + " & " + fqdn2;
+ log.info(msg);
+ throw new ArtifactHandlerInternalException(msg);
+ }
}
}
+
+ }
+
}
-}
private List<String> populateValueForFQDN(JSONObject fqdn) {
- log.info("Inside populateValueForFQDN :" + fqdn.getString("vnf-management-server-fqdn"));
+ log.info("Inside populateValueForFQDN: " + fqdn.getString("vnf-management-server-fqdn"));
List<String> valuesforFQDN = new ArrayList<>();
JSONArray cloudJsonList = fqdn.getJSONArray("cloud-owner-list");
for (int j = 0; j < cloudJsonList.length(); j++) {
String cloudOwner = cloudJsonList.getJSONObject(j).getString("cloud-owner");
JSONArray regionList = cloudJsonList.getJSONObject(j).getJSONArray("region-id-list");
+
for (int i = 0; i < regionList.length(); i++) {
+
String region = regionList.getJSONObject(i).getString("region-id");
+
JSONArray tenantList = regionList.getJSONObject(i).getJSONArray("tenant-id-list");
for (int k = 0; k < tenantList.length(); k++) {
- String tenant = tenantList.getString(k);
+ String tenant = tenantList.getString(k);
String valueforFQDN = cloudOwner + "-" + region + "-" + tenant;
- log.info("valueforFQDN for i " + i + " & j " + j + " :" + valueforFQDN);
+ log.info("valueforFQDN for i " + i + " & j " + j + ": " + valueforFQDN);
valuesforFQDN.add(valueforFQDN);
}
}
}
+
return valuesforFQDN;
}
String fn = "ArtifactHandlerNode.createReferenceDataForPD";
String artifactName = documentInfo.getString(ARTIFACT_NAME);
- log.info(fn + "Received PD File Name: " + artifactName + " and suffix length " + PD.length());
+ log.info(fn + " Received PD File Name: " + artifactName + " and suffix length " + PD.length());
try {
String suffix = artifactName.substring(PD.length());
throws ArtifactHandlerInternalException {
try {
- log.info("Creating Tosca Records and storing into SDC Artifacs");
+ log.info("Creating Tosca Records and storing into SDC Artifacts");
String[] docs = { TOSCA_PARAM, YANG_PARAM };
ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
String pdFileContents = documentInfo.getString(ARTIFACT_CONTENTS);
ArtifactProcessorImpl toscaGenerator = getArtifactProcessorImpl();
toscaGenerator.generateArtifact(pdFileContents, toscaStream);
toscaContents = toscaStream.toString();
- log.info("Generated Tosca File : " + toscaContents);
+ log.info("Generated Tosca File: " + toscaContents);
String yangContents = "YANG generation is in Progress";
String yangName = null;
return dbservice.getArtifactID(context, yangName);
}
- protected boolean updateStoreArtifacts(JSONObject requestInfo, JSONObject documentInfo) throws SvcLogicException {
- log.info("UpdateStoreArtifactsStarted storing of SDC Artifacs ");
+ protected boolean updateStoreArtifacts(JSONObject requestInfo, JSONObject documentInfo)
+ throws SvcLogicException, SQLException {
+ log.info("updateStoreArtifacts started storing of SDC Artifacts");
+
SvcLogicContext context = new SvcLogicContext();
DBService dbservice = DBService.initialise();
ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
int intversion = 0;
context.setAttribute("artifact_name", documentInfo.getString(ARTIFACT_NAME));
- String internalVersion = dbservice.getInternalVersionNumber(context, documentInfo.getString(ARTIFACT_NAME),
- null);
- log.info("Internal Version number received from Database : " + internalVersion);
+ String internalVersion =
+ dbservice.getInternalVersionNumber(context, documentInfo.getString(ARTIFACT_NAME), null);
+ log.info("Internal Version number received from Database: " + internalVersion);
if (internalVersion != null) {
intversion = Integer.parseInt(internalVersion);
intversion++;
setAttribute(context, documentInfo::getString, RESOURCE_UUID);
setAttribute(context, documentInfo::getString, RESOURCE_INSTANCE_NAME);
setAttribute(context, documentInfo::getString, RESOURCE_VERSION);
+ setAttribute(context, documentInfo::getString, RESOURCE_NAME);
setAttribute(context, documentInfo::getString, RESOURCE_TYPE);
setAttribute(context, documentInfo::getString, ARTIFACT_UUID);
setAttribute(context, documentInfo::getString, ARTIFACT_TYPE);
public boolean storeReferenceData(JSONObject requestInfo, JSONObject documentInfo)
throws ArtifactHandlerInternalException {
-
- log.info("Started storing of SDC Artifacs into Handler");
+ log.info("Started storing of SDC Artifacts into Handler");
try {
DBService dbservice = DBService.initialise();
ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
String artifactName = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_NAME));
- String capabilityArtifactName = StringUtils.replace(artifactName, ARTIFACT_NAME_REFERENCE,
- ARTIFACT_NAME_CAPABILITY);
+ String capabilityArtifactName =
+ StringUtils.replace(artifactName, ARTIFACT_NAME_REFERENCE, ARTIFACT_NAME_CAPABILITY);
JSONObject capabilities = new JSONObject();
JSONArray vnfActionList = new JSONArray();
JSONArray vfModuleActionList = new JSONArray();
JSONObject contentObject = new JSONObject(contentString);
JSONArray contentArray = contentObject.getJSONArray("reference_data");
boolean storeCapabilityArtifact = true;
+
for (int a = 0; a < contentArray.length(); a++) {
- JSONObject content = (JSONObject) contentArray.get(a);
- log.info("contentString =" + content.toString());
+ JSONObject content = contentArray.getJSONObject(a);
+ log.info("contentString = " + content.toString());
JSONObject scope = content.getJSONObject("scope");
- log.info("scope :" + scope);
+ log.info("scope: " + scope);
SvcLogicContext context = new SvcLogicContext();
vnfType = scope.getString(VNF_TYPE);
setAttribute(context, scope::getString, VNF_TYPE);
vmActionVnfcFunctionCodesList);
JSONArray vnfcTypeList = setVnfcTypeInformation(scope, context);
storeCapabilityArtifact = isCapabilityArtifactNeeded(context);
+
if (content.has(DEVICE_PROTOCOL)) {
setAttribute(context, content::getString, DEVICE_PROTOCOL);
}
if (!StringUtils.equalsIgnoreCase(actionProtocol, OPENSTACK)) {
populateProtocolReference(dbservice, content);
}
-
context.setAttribute(VNFC_TYPE, null);
-
if (content.has(VM) && content.get(VM) instanceof JSONArray) {
processVmList(content, context, dbservice);
}
String vnfcTypeScope = scope.getString(VNFC_TYPE);
if (StringUtils.isNotBlank(vnfcTypeScope)) {
setAttribute(context, scope::getString, VNFC_TYPE);
- log.info("VNFC Type has been set for this reference artifact!!" + vnfcTypeScope);
+ log.info("VNFC type has been set for this reference artifact!! " + vnfcTypeScope);
} else {
context.setAttribute(VNFC_TYPE, null);
}
vnfActionList.put(content.getString(ACTION));
}
if (validateActionLevel(actionLevel, ACTION_LEVEL_VM)) {
- if (content.has(VNFC_FUNCTION_CODE_LIST) && !content.isNull(VNFC_FUNCTION_CODE_LIST)
+ if (content.has(VNFC_FUNCTION_CODE_LIST)
+ && !content.isNull(VNFC_FUNCTION_CODE_LIST)
&& content.get(VNFC_FUNCTION_CODE_LIST) instanceof JSONArray) {
log.info("Found vnfc-function-code-list!!");
JSONArray vnfcList = content.getJSONArray(VNFC_FUNCTION_CODE_LIST);
}
public void processArtifactList(JSONObject content, DBService dbservice, SvcLogicContext context,
- JSONArray vnfcTypeList) throws ArtifactHandlerInternalException {
+ JSONArray vnfcTypeList)
+ throws ArtifactHandlerInternalException {
try {
if (content.has(ARTIFACT_LIST_PARAM) && content.get(ARTIFACT_LIST_PARAM) instanceof JSONArray) {
templateIdList = content.getJSONArray("template-id-list");
}
doProcessArtifactList(dbservice, context, artifactLists, templateIdList, vnfcTypeList);
-
}
} catch (Exception e) {
log.error("An error occurred when processing artifact list", e);
JSONArray templateIdList, JSONArray vnfcTypeList)
throws SvcLogicException, SQLException, ConfigurationException, DBException {
boolean pdFile = false;
- int modelInd = 0, vnfcRefInd = 0;
+ int modelInd = 0;
+ int vnfcRefInd = 0;
+
for (int i = 0; i < artifactLists.length(); i++) {
String suffix = null;
String model = null;
log.info("artifact is " + artifact);
// Get Model details
- if (null != templateIdList && i > 0 && i % 2 == 0) {// Should this be changed to 3 to account for 3
- // artifacts
- modelInd++;
+ if (null != templateIdList && i > 0 && i % 2 == 0) { // Should this be changed to 3
+ modelInd++; // to account for 3 artifacts
}
if (null != vnfcTypeList && i > 0 && i % 3 == 0) {
// TDP 517180 - CD tool has made changes to send 3 artifacts instead of 2
if (null != templateIdList && modelInd < templateIdList.length()) {
model = templateIdList.getString(modelInd);
- log.info("Model is ::: " + model + " ,modelInd = " + modelInd);
+ log.info("Model is ::: " + model + ", modelInd = " + modelInd);
}
if (null != vnfcTypeList && vnfcRefInd < vnfcTypeList.length()) {
String vnfcType = vnfcTypeList.getString(vnfcRefInd);
if (StringUtils.isNotBlank(vnfcType)) {
context.setAttribute(VNFC_TYPE, vnfcType);
}
- log.info("Setting vnfc type from vnfc-type-list ::" + vnfcType);
+ log.info("Setting vnfc type from vnfc-type-list :: " + vnfcType);
}
if (StringUtils.isNotBlank(model)) {
dbservice.processSdcReferences(context,
- dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
+ dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model),
+ model);
} else {
dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
}
if (pdFile) {
log.info("Sending information related to pdfile Artifact");
tryUpdateContext(dbservice, context, pdFile, suffix, model);
- pdFile = false;// set to false afterprocessing yang and Tosca
+ pdFile = false; // set to false after processing yang and Tosca
}
}
-
}
private void tryUpdateContext(DBService dbservice, SvcLogicContext context, boolean pdFile, String suffix,
- String model) throws SvcLogicException, SQLException, ConfigurationException, DBException {
+ String model)
+ throws SvcLogicException, SQLException, ConfigurationException, DBException {
if (pdFile) {
context.setAttribute(ARTIFACT_NAME, "Tosca".concat(suffix));
context.setAttribute(FILE_CATEGORY, TOSCA_MODEL);
public void processConfigTypeActions(JSONObject content, DBService dbservice, SvcLogicContext context)
throws ArtifactHandlerInternalException {
+
try {
- if (isContentActionConfig(content)
+ if (contentsActionEquals(content, CONFIGURE_PARAM)
+ || contentsActionEquals(content, CONFIG_MODIFY_PARAM)
+ || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)
|| contentsActionEquals(content, GET_CONFIG)
|| contentsActionEquals(content, POST_EVACUATE)
|| contentsActionEquals(content, PRE_EVACUATE)
|| contentsActionEquals(content, POST_REBUILD)
|| contentsActionEquals(content, PRE_REBUILD)
|| contentsActionEquals(content, STOP_TRAFFIC)
- ) {
+ ) {
if (content.has(DOWNLOAD_DG_REFERENCE) && content.getString(DOWNLOAD_DG_REFERENCE).length() > 0) {
private void tryProcessInterfaceProtocol(JSONObject content, DBService dbservice, SvcLogicContext context)
throws SvcLogicException, SQLException, ConfigurationException, DBException {
- if (isContentActionConfig(content)) {
+
+ if (contentsActionEquals(content, CONFIGURE_PARAM) || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)) {
boolean isUpdateRequired = dbservice.isArtifactUpdateRequired(context, DB_DEVICE_INTERFACE_PROTOCOL);
- if (isContentActionConfig(content) && !isUpdateRequired) {
+ if (contentsActionEquals(content, CONFIGURE_PARAM)
+ || (contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)
+ && !isUpdateRequired)) {
+
dbservice.processDeviceInterfaceProtocol(context, isUpdateRequired);
}
}
}
-
- //Consolidates the if statements required to check if the action is one of the config actions
- private boolean isContentActionConfig(JSONObject content) {
- return contentsActionEquals(content, CONFIGURE_PARAM)
- || contentsActionEquals(content, CONFIG_MODIFY_PARAM)
- || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM);
- }
private boolean contentsActionEquals(JSONObject content, String action) {
return content.getString(ACTION).equals(action);
JSONObject capabilities, String capabilityArtifactName, String vnfType)
throws ArtifactHandlerInternalException {
- log.info("Begin-->processAndStoreCapabilitiesArtifact ");
+ log.info("Begin-->processAndStoreCapabilitiesArtifact");
try {
JSONObject newCapabilitiesObject = new JSONObject();
context.setAttribute(ARTIFACT_CONTENTS, newCapabilitiesObject.toString());
dbService.processSdcReferences(context, dbService.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
int intVersion = 0;
- String internalVersion = dbService.getInternalVersionNumber(context, context.getAttribute(ARTIFACT_NAME),
- null);
- log.info("Internal Version number received from Database : " + internalVersion);
+ String internalVersion =
+ dbService.getInternalVersionNumber(context, context.getAttribute(ARTIFACT_NAME), null);
+ log.info("Internal Version number received from Database: " + internalVersion);
if (internalVersion != null) {
intVersion = Integer.parseInt(internalVersion) + 1;
}
log.error("Error saving capabilities artifact to DB", e);
throw new ArtifactHandlerInternalException("Error saving capabilities artifact to DB", e);
} finally {
- log.info("End-->processAndStoreCapabilitiesArtifact ");
+ log.info("End-->processAndStoreCapabilitiesArtifact");
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
JSONObject docParams = new JSONObject();
docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID,
- "TLSUUID" + templateData.getRequestInformation().getRequestId());
+ "TLSUUID" + templateData.getRequestInformation().getRequestId());
docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "TLDID" + random);
docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, "TLServiceName");
docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "Template Loader Test");
docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS, "[]");
docParams.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "TLRUID" + random);
docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "TLRIName");
- docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, "TLResourceName");
+ docParams.put(SdcArtifactHandlerConstants.RESOURCE_NAME, "TLResourceName");
docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSION, "TLResourceVersion");
docParams.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "TLResourceType");
docParams.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "TLAUUID" + random);
docParams
- .put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName());
+ .put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName());
docParams.put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, "APPC-CONFIG");
docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSION,
- templateData.getDocumentParameters().getArtifactVersion());
- docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "SdcTestDescription");
+ templateData.getDocumentParameters().getArtifactVersion());
+ docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESCRIPTION, "SdcTestDescription");
docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents());
json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams);
- log.info("Final data =" + this.templateData);
+ log.info("Final data = " + this.templateData);
return String.format("{\"input\": %s}", json.toString());
}
requestInfo.put(SdcArtifactHandlerConstants.SOURCE, templateData.getRequestInformation().getSource());
String serviceDescription = serviceDescriptionData(
- templateData.getDocumentParameters().getServiceDescription());
+ templateData.getDocumentParameters().getServiceDescription());
JSONObject docParams = new JSONObject();
docParams.put(SdcArtifactHandlerConstants.SERVICE_UUID, templateData.getDocumentParameters().getResourceUuid());
- docParams
- .put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, templateData.getDocumentParameters().getDistributionId());
+ docParams.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID,
+ templateData.getDocumentParameters().getDistributionId());
docParams.put(SdcArtifactHandlerConstants.SERVICE_NAME, templateData.getDocumentParameters().getServiceName());
docParams.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, serviceDescription);
docParams.put(SdcArtifactHandlerConstants.SERVICE_ARTIFACTS,
- templateData.getDocumentParameters().getServiceArtifacts());
+ templateData.getDocumentParameters().getServiceArtifacts());
docParams
- .put(SdcArtifactHandlerConstants.RESOURCE_UUID, templateData.getDocumentParameters().getResourceUuid());
+ .put(SdcArtifactHandlerConstants.RESOURCE_UUID, templateData.getDocumentParameters().getResourceUuid());
docParams.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME,
- templateData.getDocumentParameters().getResourceInstanceName());
- docParams.put(SdcArtifactHandlerConstants.REOURCE_NAME, templateData.getDocumentParameters().getResourceName());
+ templateData.getDocumentParameters().getResourceInstanceName());
+ docParams
+ .put(SdcArtifactHandlerConstants.RESOURCE_NAME, templateData.getDocumentParameters().getResourceName());
docParams.put(SdcArtifactHandlerConstants.RESOURCE_VERSION,
- templateData.getDocumentParameters().getResourceVersion());
+ templateData.getDocumentParameters().getResourceVersion());
docParams
- .put(SdcArtifactHandlerConstants.RESOURCE_TYPE, templateData.getDocumentParameters().getResourceType());
+ .put(SdcArtifactHandlerConstants.RESOURCE_TYPE, templateData.getDocumentParameters().getResourceType());
docParams
- .put(SdcArtifactHandlerConstants.ARTIFACT_UUID, templateData.getDocumentParameters().getArtifactUuid());
+ .put(SdcArtifactHandlerConstants.ARTIFACT_UUID, templateData.getDocumentParameters().getArtifactUuid());
docParams
- .put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName());
+ .put(SdcArtifactHandlerConstants.ARTIFACT_NAME, templateData.getDocumentParameters().getArtifactName());
docParams
- .put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, templateData.getDocumentParameters().getArtifactType());
+ .put(SdcArtifactHandlerConstants.ARTIFACT_TYPE, templateData.getDocumentParameters().getArtifactType());
docParams.put(SdcArtifactHandlerConstants.ARTIFACT_VERSION,
- templateData.getDocumentParameters().getArtifactVersion());
- docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION,
- templateData.getDocumentParameters().getArtifactDescription());
+ templateData.getDocumentParameters().getArtifactVersion());
+ docParams.put(SdcArtifactHandlerConstants.ARTIFACT_DESCRIPTION,
+ templateData.getDocumentParameters().getArtifactDescription());
docParams.put("artifact-contents", templateData.getDocumentParameters().getArtifactContents());
json.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
json.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, docParams);
- log.info("Final data =" + this.templateData);
+ log.info("Final data = " + this.templateData);
return String.format("{\"input\": %s}", json.toString());
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class SdcArtifactHandlerConstants {
public static final String DOCUMENT_PARAMETERS = "document-parameters";
- public static final String SERVICE_UUID = "service-uuid";
- public static final String DISTRIBUTION_ID = "distribution-id";
+ public static final String SERVICE_UUID = "service-uuid";
+ public static final String DISTRIBUTION_ID = "distribution-id";
public static final String REQUEST_ID = "request-id";
- public static final String REQUEST_ACTION = "request-action";
+ public static final String REQUEST_ACTION = "request-action";
public static final String SOURCE = "source";
- public static final String SERVICE_NAME = "service-name";
- public static final String SERVICE_DESCRIPTION ="service-description";
- public static final String SERVICE_ARTIFACTS = "service-artifacts";
- public static final String RESOURCE_UUID ="resource-uuid";
+ public static final String SERVICE_NAME = "service-name";
+ public static final String SERVICE_DESCRIPTION = "service-description";
+ public static final String SERVICE_ARTIFACTS = "service-artifacts";
+ public static final String RESOURCE_UUID = "resource-uuid";
public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name";
- public static final String REOURCE_NAME = "resource-name";
- public static final String RESOURCE_VERSION ="resource-version";
- public static final String RESOURCE_TYPE= "resource-type";
- public static final String ARTIFACT_UUID ="artifact-uuid";
- public static final String ARTIFACT_NAME = "artifact-name";
- public static final String ARTIFACT_TYPE = "artifact-type";
+ public static final String RESOURCE_NAME = "resource-name";
+ public static final String REOURCE_NAME = "resource-name"; // misspelling that was once supported
+ public static final String RESOURCE_VERSION = "resource-version";
+ public static final String RESOURCE_TYPE = "resource-type";
+ public static final String ARTIFACT_UUID = "artifact-uuid";
+ public static final String ARTIFACT_NAME = "artifact-name";
+ public static final String ARTIFACT_TYPE = "artifact-type";
public static final String ARTIFACT_VERSION = "artifact-version";
- public static final String ARTIFACT_DESRIPTION = "artifact-description";
+ public static final String ARTIFACT_DESCRIPTION = "artifact-description";
+ public static final String ARTIFACT_DESRIPTION = "artifact-description"; // misspelling that was once supported
public static final String ARTIFACT_CONTENTS = "artifact-contents";
public static final String REQUEST_INFORMATION = "request-information";
public static final String INTERNAL_VERSION = "internal-versoin";
public static final String VNFC_FUNCTION_CODE = "vnfc-function-code";
public static final String VNFC_FUNCTION_CODE_LIST = "vnfc-function-code-list";
public static final String GROUP_NOTATION = "group-notation";
- public static final String IPADDRESS_V4_OAM_VIP = "ipaddress-v4-oam-vip";
- public static final String GROUP_NOTATION_TYPE = "group-notation-type";
+ public static final String IPADDRESS_V4_OAM_VIP = "ipaddress-v4-oam-vip";
+ public static final String GROUP_NOTATION_TYPE = "group-notation-type";
public static final String GROUP_NOTATION_VALUE = "group-notation-value";
public static final String TEMPLATE_ID = "template-id";
public static final String REFERENCE = "reference";
public static final String PORT_NUMBER = "port-number";
public static final String DOWNLOAD_DG_REFERENCE = "download-dg-reference";
public static final String VNFC_TYPE_LIST = "vnfc-type-list";
-
+
+
public static final String DB_DOWNLOAD_DG_REFERENCE = "DOWNLOAD_DG_REFERENCE";
public static final String DB_SDC_REFERENCE = "ASDC_REFERENCE";
public static final String DB_DEVICE_INTERFACE_PROTOCOL = "DEVICE_INTERFACE_PROTOCOL";
public static final String TOSCA_MODEL = "tosca_model";
public static final String DESIGN_TOOL = "Design-tool";
public static final String ACTION_LEVEL_VNFC = "VNFC";
- public static final String ACTION_LEVEL_VF_MODULE ="VF-MODULE";
+ public static final String ACTION_LEVEL_VF_MODULE = "VF-MODULE";
public static final String ACTION_LEVEL_VNF = "VNF";
public static final String ACTION_LEVEL_VM = "VM";
public static final String CAPABILITY = "capability";
public static final String TEMPLATE = "template";
public static final String ARTIFACT_NAME_REFERENCE = "reference";
public static final String ARTIFACT_NAME_CAPABILITY = "capability";
- public static final String APPC_CONFIG_DIR="/opt/appcauth";
- public static final String URL="url";
- public static final String OPENSTACK = "OS";
- public static final String ANSIBLE = "ansible";
-
+ public static final String APPC_CONFIG_DIR = "/opt/appcauth";
+ public static final String URL = "url";
+ public static final String OPENSTACK = "OS";
+ public static final String ANSIBLE = "ansible";
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
artifactHandlerNode = Mockito.spy(new ArtifactHandlerNode());
PowerMockito.mockStatic(DBService.class);
dbServiceMock = Mockito.mock(DBService.class);
- Mockito.doReturn("12345").when(dbServiceMock).getInternalVersionNumber(Mockito.any(), Mockito.anyString(), Mockito.anyString());
+ Mockito.doReturn("12345")
+ .when(dbServiceMock).getInternalVersionNumber(Mockito.any(), Mockito.anyString(), Mockito.anyString());
PowerMockito.when(DBService.initialise()).thenReturn(dbServiceMock);
PowerMockito.mockStatic(YANGGeneratorFactory.class);
YANGGenerator yangGeneratorMock = Mockito.mock(YANGGenerator.class);
JSONObject documentInfo = getDocumentInfo("templates/reference_template");
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "reference_Junit.json");
requestInfo.put("RequestInfo", "testValue");
- requestInfo.put("request-id","testREQUEST_ID");
+ requestInfo.put("request-id", "testREQUEST_ID");
input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo);
input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
postData.put("input", input);
String artifactId = "1";
String yangContents = "SomeContent";
Whitebox.invokeMethod(artifactHandlerNode, "updateYangContents", artifactId, yangContents);
- Mockito.verify(dbServiceMock).updateYangContents(Mockito.any(SvcLogicContext.class),
- Mockito.anyString(), Mockito.anyString());
+ Mockito.verify(dbServiceMock)
+ .updateYangContents(Mockito.any(SvcLogicContext.class), Mockito.anyString(), Mockito.anyString());
}
@Test
public void testProcessVmList() throws Exception{
String contentStr = "{\r\n\t\"action\": \"ConfigScaleOut\",\r\n\t\"action-level\": \"VNF\",\r\n\t\"scope\": "
- + "{\r\n\t\t\"vnf-type\": \"ScaleOutVNF\",\r\n\t\t\"vnfc-type\": \"\"\r\n\t},\r\n\t\"template\": \"Y\",\r\n\t\"vm\": "
- + "[\r\n\t{ \r\n\t\t\"vm-instance\": 1,\r\n\t\t\"template-id\":\"id1\",\r\n\t\t\r\n\t\t\"vnfc\": [{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": \"t1\",\r\n\t\t\t\"vnfc-function-code\": "
- + "\"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n\t\t\t\"ipaddress-v4-oam-vip\": \"N\",\r\n\t\t\t\"group-notation-value\": "
- + "\"GNValue\"\r\n\t\t}]\r\n\t},\r\n\t{ \r\n\t\t\"vm-instance\": 1,\r\n\t\t\"template-id\":\"id2\",\r\n\t\t\r\n\t\t\"vnfc\": [{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": "
- + "\"t1\",\r\n\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n\t\t\t\"ipaddress-v4-oam-vip\": \"N\",\r\n\t\t\t\"group-notation-value\": "
- + "\"GNValue\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"vnfc-instance\": 2,\r\n\t\t\t\"vnfc-type\": \"t2\",\r\n\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": "
- + "\"GNType\",\r\n\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t}]\r\n\t},\r\n\t{\r\n\t\t\"vm-instance\": 2,\r\n\t\t\"template-id\":\"id3\",\r\n\t\t\"vnfc\": "
- + "[{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": \"t3\",\r\n\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": "
- + "\"GNType\",\r\n\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t}]\r\n\t}],\r\n\t\"device-protocol\": "
- + "\"TEST-PROTOCOL\",\r\n\t\"user-name\": \"Testnetconf\",\r\n\t\"port-number\": \"22\",\r\n\t\"artifact-list\": [{\r\n\t\t\"artifact-name\": \"Testv_template.json\",\r\n\t\t\"artifact-type\": "
- + "\"Testconfig_template\"\r\n\t},\r\n\t{\r\n\t\t\"artifact-name\": \"TESTv_parameter_definitions.json\",\r\n\t\t\"artifact-type\": \"Testparameter_definitions\"\r\n\t},\r\n\t{\r\n\t\t\"artifact-name\": "
- + "\"PD_JunitTESTv_parameter_yang.json\",\r\n\t\t\"artifact-type\": \"PD_definations\"\r\n\t}]\r\n}";
+ + "{\r\n\t\t\"vnf-type\": \"ScaleOutVNF\",\r\n\t\t\"vnfc-type\": \"\"\r\n\t},\r\n"
+ + "\t\"template\": \"Y\",\r\n\t\"vm\": "
+ + "[\r\n\t{ \r\n\t\t\"vm-instance\": 1,\r\n\t\t\"template-id\":\"id1\",\r\n\t\t\r\n\t\t\"vnfc\": "
+ + "[{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": \"t1\",\r\n\t\t\t\"vnfc-function-code\": "
+ + "\"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n"
+ + "\t\t\t\"ipaddress-v4-oam-vip\": \"N\",\r\n"
+ + "\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t}]\r\n\t},\r\n"
+ + "\t{ \r\n\t\t\"vm-instance\": 1,\r\n\t\t\"template-id\":\"id2\",\r\n"
+ + "\t\t\r\n\t\t\"vnfc\": [{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": \"t1\",\r\n"
+ + "\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n"
+ + "\t\t\t\"ipaddress-v4-oam-vip\": \"N\",\r\n\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t},\r\n"
+ + "\t\t{\r\n\t\t\t\"vnfc-instance\": 2,\r\n\t\t\t\"vnfc-type\": \"t2\",\r\n"
+ + "\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n"
+ + "\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t}]\r\n"
+ + "\t},\r\n\t{\r\n\t\t\"vm-instance\": 2,\r\n\t\t\"template-id\":\"id3\",\r\n"
+ + "\t\t\"vnfc\": [{\r\n\t\t\t\"vnfc-instance\": 1,\r\n\t\t\t\"vnfc-type\": \"t3\",\r\n"
+ + "\t\t\t\"vnfc-function-code\": \"Testdbg\",\r\n\t\t\t\"group-notation-type\": \"GNType\",\r\n"
+ + "\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\"group-notation-value\": \"GNValue\"\r\n\t\t}]\r\n"
+ + "\t}],\r\n\t\"device-protocol\": \"TEST-PROTOCOL\",\r\n\t\"user-name\": \"Testnetconf\",\r\n"
+ + "\t\"port-number\": \"22\",\r\n\t\"artifact-list\": [{\r\n"
+ + "\t\t\"artifact-name\": \"Testv_template.json\",\r\n"
+ + "\t\t\"artifact-type\": \"Testconfig_template\"\r\n\t},\r\n"
+ + "\t{\r\n\t\t\"artifact-name\": \"TESTv_parameter_definitions.json\",\r\n"
+ + "\t\t\"artifact-type\": \"Testparameter_definitions\"\r\n\t},\r\n\t{\r\n"
+ + "\t\t\"artifact-name\": \"PD_JunitTESTv_parameter_yang.json\",\r\n"
+ + "\t\t\"artifact-type\": \"PD_definations\"\r\n\t}]\r\n}";
JSONObject content=new JSONObject(contentStr);
MockDBService dbService = MockDBService.initialise();
SvcLogicContext context = new SvcLogicContext();
}
@Test
- public void testProcessConfigTypeActions() throws Exception{
+ public void testProcessConfigTypeActions() throws Exception {
String contentStr = "{\"action\": \"ConfigScaleOut\"}";
- JSONObject content=new JSONObject(contentStr);
+ JSONObject content = new JSONObject(contentStr);
MockDBService dbService = MockDBService.initialise();
SvcLogicContext context = new SvcLogicContext();
- context.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL,"Test");
+ context.setAttribute(SdcArtifactHandlerConstants.DEVICE_PROTOCOL, "Test");
artifactHandlerNode.processConfigTypeActions(content, dbService, context);
}
@Test
public void testProcessActionLists() throws Exception {
String contentStr = "{\r\n\t\"action\": \"HealthCheck\",\r\n\t\"action-level\": \"vm\",\r\n\t\"scope\":"
- + " {\r\n\t\t\"vnf-type\": \"vDBE-I\",\r\n\t\t\"vnfc-type\": null\r\n\t},\r\n\t\"template\": "
- + "\"N\",\r\n\t\"device-protocol\": \"REST\",\r\n\t\"vnfc-function-code-list\": [\"SSC\", \"MMSC\"]\r\n}";
+ + " {\r\n\t\t\"vnf-type\": \"vDBE-I\",\r\n\t\t\"vnfc-type\": null\r\n\t},\r\n\t\"template\": \"N\",\r\n"
+ + "\t\"device-protocol\": \"REST\",\r\n\t\"vnfc-function-code-list\": [\"SSC\", \"MMSC\"]\r\n}";
JSONObject content = new JSONObject(contentStr);
JSONArray vmActionVnfcFunctionCodesList = new JSONArray();
JSONArray vnfActionList = new JSONArray();
@Test
public void testIsCapabilityArtifactNeeded() throws Exception {
- String scopeObjStr1= "{\"vnf-type\":\"someVnf\",\"vnfc-type\":\"somVnfc\"}";
- String scopeObjStr2= "{\"vnf-type\":\"someVnf\",\"vnfc-type\":\"\"}";
+ String scopeObjStr1 = "{\"vnf-type\":\"someVnf\",\"vnfc-type\":\"somVnfc\"}";
+ String scopeObjStr2 = "{\"vnf-type\":\"someVnf\",\"vnfc-type\":\"\"}";
JSONObject scope1 = new JSONObject(scopeObjStr1);
JSONObject scope2 = new JSONObject(scopeObjStr2);
SvcLogicContext context = new SvcLogicContext();
@Test
public void testProcessArtifactListsWithMultipleTemplates() throws Exception {
- String contentStr = "{\r\n\t\t\"action\": \"ConfigScaleOut\",\r\n\t\t\"action-level\": \"vnf\",\r\n\t\t\"scope\": {\r\n\t\t\t\"vnf-type\": "
- + "\"vCfgSO-0405\",\r\n\t\t\t\"vnfc-type\": \"\"\r\n\t\t},\r\n\t\t\"template\": \"Y\",\r\n\t\t\"vm\": [{\r\n\t\t\t\"template-id\": "
- + "\"TID-0405-EZ\",\r\n\t\t\t\"vm-instance\": 1,\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n\t\t\t\t\"vnfc-function-code\": "
- + "\"Cfg-ez\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n\t\t\t\t\"group-notation-value\":"
- + " \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vCfg-0405-ez\"\r\n\t\t\t}]\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"template-id\": "
- + "\"TID-0405-EZ\",\r\n\t\t\t\"vm-instance\": 2,\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n\t\t\t\t\"vnfc-function-code\": "
- + "\"Cfg-ez\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n\t\t\t\t\"group-notation-value\":"
- + " \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vCfg-0405-ez\"\r\n\t\t\t}]\r\n\t\t}],\r\n\t\t\"device-protocol\": \"ANSIBLE\",\r\n\t\t\"user-name\": \"root\","
- + "\r\n\t\t\"port-number\": \"22\",\r\n\t\t\"artifact-list\": [{\r\n\t\t\t\"artifact-name\": \"template_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ.json\","
- + "\r\n\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ.yaml\","
- + "\r\n\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": "
- + "\"template_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ-2.json\",\r\n\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": "
- + "\"pd_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ-2.yaml\",\r\n\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t}],\r\n\t\t\"template-id-list\":"
- + " [\"TID-0405-EZ\",\r\n\t\t\"TID-0405-EZ-2\"],\r\n\t\t\"scopeType\": \"vnf-type\"\r\n\t}";
+ String contentStr = "{\r\n\t\t\"action\": \"ConfigScaleOut\",\r\n\t\t\"action-level\": \"vnf\",\r\n"
+ + "\t\t\"scope\": {\r\n\t\t\t\"vnf-type\": \"vCfgSO-0405\",\r\n\t\t\t\"vnfc-type\": \"\"\r\n\t\t},\r\n"
+ + "\t\t\"template\": \"Y\",\r\n\t\t\"vm\": [{\r\n\t\t\t\"template-id\": \"TID-0405-EZ\",\r\n"
+ + "\t\t\t\"vm-instance\": 1,\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n"
+ + "\t\t\t\t\"vnfc-function-code\": \"Cfg-ez\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n"
+ + "\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n"
+ + "\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vCfg-0405-ez\"\r\n"
+ + "\t\t\t}]\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"template-id\": \"TID-0405-EZ\",\r\n"
+ + "\t\t\t\"vm-instance\": 2,\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n"
+ + "\t\t\t\t\"vnfc-function-code\": \"Cfg-ez\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n"
+ + "\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n"
+ + "\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vCfg-0405-ez\"\r\n"
+ + "\t\t\t}]\r\n\t\t}],\r\n\t\t\"device-protocol\": \"ANSIBLE\",\r\n\t\t\"user-name\": \"root\",\r\n"
+ + "\t\t\"port-number\": \"22\",\r\n\t\t\"artifact-list\": [{\r\n"
+ + "\t\t\t\"artifact-name\": \"template_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ.json\",\r\n"
+ + "\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n\t\t{\r\n"
+ + "\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ.yaml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t},\r\n\t\t{\r\n"
+ + "\t\t\t\"artifact-name\": \"template_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ-2.json\",\r\n"
+ + "\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n\t\t{\r\n"
+ + "\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_vCfgSO-0405_0.0.1V_TID-0405-EZ-2.yaml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t}],\r\n"
+ + "\t\t\"template-id-list\": [\"TID-0405-EZ\",\r\n\t\t\"TID-0405-EZ-2\"],\r\n"
+ + "\t\t\"scopeType\": \"vnf-type\"\r\n\t}";
JSONObject content = new JSONObject(contentStr);
MockDBService dbService = MockDBService.initialise();
SvcLogicContext context = new SvcLogicContext();
@Test
public void testProcessArtifactListsWithVnfcTypeList() throws Exception {
- String contentStr = "{\r\n\t\"action\": \"Configure\",\r\n\t\"action-level\": \"vnf\",\r\n\t\"scope\": {\r\n\t\t\"vnf-type\": "
- + "\"newtypeofvnf\",\r\n\t\t\"vnfc-type-list\": [\"vnfctype1\",\"vnfctype2\"]\r\n\t},\r\n\t\"template\": \"Y\",\r\n\t\"vm\":"
- + " [{\r\n\t\t\t\"vm-instance\": 1,\r\n\t\t\t\"template-id\": \"vnfctype1\",\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": "
- + "\"1\",\r\n\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\t\"group-notation-type\": "
- + "\"first-vnfc-name\",\r\n\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n\t\t},"
- + "\r\n\t\t{\r\n\t\t\t\"vm-instance\": 1,\r\n\t\t\t\"template-id\": \"vnfctype2\",\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": "
- + "\"1\",\r\n\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\t\"group-notation-type\": "
- + "\"first-vnfc-name\",\r\n\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n\t\t},"
- + "\r\n\t\t{\r\n\t\t\t\"vm-instance\": 2,\r\n\t\t\t\"template-id\": \"vnfctype2\",\r\n\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": "
- + "\"1\",\r\n\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n\t\t\t\t\"group-notation-type\": "
- + "\"first-vnfc-name\",\r\n\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n\t\t}\r\n\t],"
- + "\r\n\t\"device-protocol\": \"NETCONF-XML\",\r\n\t\"user-name\": \"netconf\",\r\n\t\"port-number\": \"20\",\r\n\t\"artifact-list\": "
- + "[{\r\n\t\t\t\"artifact-name\": \"template_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype1.xml\",\r\n\t\t\t\"artifact-type\": "
- + "\"config_template\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype1.yaml\","
- + "\r\n\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": "
- + "\"template_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype2.xml\",\r\n\t\t\t\"artifact-type\": "
- + "\"config_template\"\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype2.yaml\","
- + "\r\n\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t}\r\n\t],\r\n\t\"scopeType\": \"vnf-type\"\r\n}";
+ String contentStr = "{\r\n\t\"action\": \"Configure\",\r\n\t\"action-level\": \"vnf\",\r\n\t\"scope\": {\r\n"
+ + "\t\t\"vnf-type\": \"newtypeofvnf\",\r\n\t\t\"vnfc-type-list\": [\"vnfctype1\",\"vnfctype2\"]\r\n"
+ + "\t},\r\n\t\"template\": \"Y\",\r\n\t\"vm\": [{\r\n\t\t\t\"vm-instance\": 1,\r\n"
+ + "\t\t\t\"template-id\": \"vnfctype1\",\r\n\t\t\t\"vnfc\": [{\r\n"
+ + "\t\t\t\t\"vnfc-instance\": \"1\",\r\n\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n"
+ + "\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n"
+ + "\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n"
+ + "\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n"
+ + "\t\t},\r\n\t\t{\r\n\t\t\t\"vm-instance\": 1,\r\n\t\t\t\"template-id\": \"vnfctype2\",\r\n"
+ + "\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n"
+ + "\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n"
+ + "\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n"
+ + "\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n"
+ + "\t\t},\r\n\t\t{\r\n\t\t\t\"vm-instance\": 2,\r\n\t\t\t\"template-id\": \"vnfctype2\",\r\n"
+ + "\t\t\t\"vnfc\": [{\r\n\t\t\t\t\"vnfc-instance\": \"1\",\r\n"
+ + "\t\t\t\t\"vnfc-function-code\": \"fcx\",\r\n\t\t\t\t\"ipaddress-v4-oam-vip\": \"Y\",\r\n"
+ + "\t\t\t\t\"group-notation-type\": \"first-vnfc-name\",\r\n"
+ + "\t\t\t\t\"group-notation-value\": \"pair\",\r\n\t\t\t\t\"vnfc-type\": \"vDBE\"\r\n\t\t\t}]\r\n"
+ + "\t\t}\r\n\t],\r\n\t\"device-protocol\": \"NETCONF-XML\",\r\n\t\"user-name\": \"netconf\",\r\n"
+ + "\t\"port-number\": \"20\",\r\n\t\"artifact-list\": [{\r\n"
+ + "\t\t\t\"artifact-name\": \"template_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype1.xml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n\t\t{\r\n"
+ + "\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype1.yaml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t},\r\n"
+ + "\t\t{\r\n\t\t\t\"artifact-name\": \"template_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype2.xml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"config_template\"\r\n\t\t},\r\n"
+ + "\t\t{\r\n\t\t\t\"artifact-name\": \"pd_ConfigScaleOut_newtypeofvnf_0.0.1V_vnfctype2.yaml\",\r\n"
+ + "\t\t\t\"artifact-type\": \"parameter_definitions\"\r\n\t\t}\r\n\t],\r\n"
+ + "\t\"scopeType\": \"vnf-type\"\r\n}";
JSONObject content = new JSONObject(contentStr);
MockDBService dbService = MockDBService.initialise();
SvcLogicContext context = new SvcLogicContext();
JSONObject scope = (JSONObject)content.get("scope");
JSONArray vnfcTypeList = artifactHandlerNode.setVnfcTypeInformation(scope, context);
artifactHandlerNode.processArtifactList(content, dbService, context, vnfcTypeList);
- JSONArray vnfcLists = scope.getJSONArray("vnfc-type-list");
+ JSONArray vnfcLists = scope.getJSONArray("vnfc-type-list");
assertEquals(vnfcLists.toString(), "[\"vnfctype1\",\"vnfctype2\"]");
- assertEquals(context.getAttribute("vnfc-type"),"vnfctype2");
+ assertEquals(context.getAttribute("vnfc-type"), "vnfctype2");
assertNotNull (vnfcTypeList);
}
JSONObject documentInfo = getDocumentInfo("templates/pd_template");
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "pd_Junit.json");
requestInfo.put("RequestInfo", "testValue");
- requestInfo.put("request-id","testREQUEST_ID");
+ requestInfo.put("request-id", "testREQUEST_ID");
input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo);
input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
postData.put("input", input);
private JSONObject getDocumentInfo(String filename) throws IOException {
JSONObject documentInfo = new JSONObject();
- String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader()
- .getResourceAsStream(filename), Charset.defaultCharset());
+ String artifactContent = IOUtils.toString(
+ ArtifactHandlerProviderUtilTest.class.getClassLoader().getResourceAsStream(filename),
+ Charset.defaultCharset());
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent);
documentInfo.put(SdcArtifactHandlerConstants.SERVICE_UUID, "12345");
documentInfo.put(SdcArtifactHandlerConstants.DISTRIBUTION_ID, "12345");
documentInfo.put(SdcArtifactHandlerConstants.SERVICE_NAME, "12345");
documentInfo.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "12345");
- documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "12345");
+ documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "12345");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "12345");
+ documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_NAME, "12345");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_VERSION, "12345");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "12345");
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "12345");
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION, "12345");
return documentInfo;
}
-
-
+
+
@Test
public void testValidateAnsibleAdminArtifact() throws Exception {
- String contentStr = "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\",\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\","
- + "\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]},{\"region-id\":\"san4b\","
- + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]}]},{\"cloud-owner\":\"nc1.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
- + "\"tenant-id-list\":[\"tenantuuid3\",\"tenantuuid4\"]}]}],\"description\":\"fqdn for east zone Production\",\"username\":\"attuid\","
- + "\"create-date\":\"\",\"modify-username\":\"\",\"modify-date\":\"\"},{\"vnf-management-server-fqdn\":\"fqdn-value2 url:port\","
- + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid5\","
- + "\"tenantuuid6\"]},{\"region-id\":\"san4b\",\"tenant-id-list\":[\"tenantuuid5\",\"tenantuuid6\"]}]},{\"cloud-owner\":\"nc1.0\","
- + "\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid7\",\"tenantuuid8\"]}]}],"
- + "\"description\":\"fqdn for east zone Test\",\"username\":\"attuid\",\"create-date\":\"\","
- + "\"modify-username\":\"\",\"modify-date\":\"\"}]}";
-
- JSONObject documentInfo = new JSONObject();
+ String contentStr = "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\","
+ + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]},{\"region-id\":\"san4b\","
+ + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]}]},{\"cloud-owner\":\"nc1.0\","
+ + "\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid3\","
+ + "\"tenantuuid4\"]}]}],\"description\":\"fqdn for east zone Production\",\"username\":\"attuid\","
+ + "\"create-date\":\"\",\"modify-username\":\"\",\"modify-date\":\"\"},"
+ + "{\"vnf-management-server-fqdn\":\"fqdn-value2 url:port\","
+ + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid5\",\"tenantuuid6\"]},{\"region-id\":\"san4b\","
+ + "\"tenant-id-list\":[\"tenantuuid5\",\"tenantuuid6\"]}]},{\"cloud-owner\":\"nc1.0\","
+ + "\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid7\",\"tenantuuid8\"]}]}],"
+ + "\"description\":\"fqdn for east zone Test\",\"username\":\"attuid\",\"create-date\":\"\","
+ + "\"modify-username\":\"\",\"modify-date\":\"\"}]}";
+
+ JSONObject documentInfo = new JSONObject();
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, contentStr);
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "ansible_admin_FQDN_Artifact_0.0.1V.json");
artifactHandlerNode.validateAnsibleAdminArtifact(documentInfo);
}
-
+
@Test
public void testValidateAnsibleAdminArtifactWithException() throws Exception {
- String contentStrOne = "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\",\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\","
- + "\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]},{\"region-id\":\"san4b\","
- + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]}]},{\"cloud-owner\":\"nc1.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
- + "\"tenant-id-list\":[\"tenantuuid3\",\"tenantuuid4\"]}]}],\"description\":\"fqdn for east zone Production\",\"username\":\"attuid\","
- + "\"create-date\":\"\",\"modify-username\":\"\",\"modify-date\":\"\"},{\"vnf-management-server-fqdn\":\"fqdn-value2 url:port\","
- + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid1\","
- + "\"tenantuuid6\"]},{\"region-id\":\"san4b\",\"tenant-id-list\":[\"tenantuuid5\",\"tenantuuid6\"]}]},{\"cloud-owner\":\"nc1.0\","
- + "\"region-id-list\":[{\"region-id\":\"san4a\",\"tenant-id-list\":[\"tenantuuid7\",\"tenantuuid8\"]}]}],"
- + "\"description\":\"fqdn for east zone Test\",\"username\":\"attuid\",\"create-date\":\"\","
- + "\"modify-username\":\"\",\"modify-date\":\"\"}]}";
- JSONObject documentInfoOne = new JSONObject();
- documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, contentStrOne);
- documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "ansible_admin_FQDN_Artifact_0.0.1V.json");
-
- try {
- artifactHandlerNode.validateAnsibleAdminArtifact(documentInfoOne);
- fail("Missing exception");
- }catch(ArtifactHandlerInternalException e) {
+ String contentStrOne = "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\","
+ + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]},{\"region-id\":\"san4b\","
+ + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid2\"]}]},{\"cloud-owner\":\"nc1.0\","
+ + "\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid3\",\"tenantuuid4\"]}]}],"
+ + "\"description\":\"fqdn for east zone Production\",\"username\":\"attuid\",\"create-date\":\"\","
+ + "\"modify-username\":\"\",\"modify-date\":\"\"},"
+ + "{\"vnf-management-server-fqdn\":\"fqdn-value2 url:port\","
+ + "\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\",\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid1\",\"tenantuuid6\"]},{\"region-id\":\"san4b\","
+ + "\"tenant-id-list\":[\"tenantuuid5\",\"tenantuuid6\"]}]},{\"cloud-owner\":\"nc1.0\","
+ + "\"region-id-list\":[{\"region-id\":\"san4a\","
+ + "\"tenant-id-list\":[\"tenantuuid7\",\"tenantuuid8\"]}]}],"
+ + "\"description\":\"fqdn for east zone Test\",\"username\":\"attuid\",\"create-date\":\"\","
+ + "\"modify-username\":\"\",\"modify-date\":\"\"}]}";
+ JSONObject documentInfoOne = new JSONObject();
+ documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, contentStrOne);
+ documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "ansible_admin_FQDN_Artifact_0.0.1V.json");
+
+ try {
+ artifactHandlerNode.validateAnsibleAdminArtifact(documentInfoOne);
+ fail("Missing exception");
+ } catch (ArtifactHandlerInternalException e) {
assertTrue(e.getMessage().contains("Validation Failure"));
- }
-
+ }
+
}
-
+
@Test
public void testValidateAnsibleAdminArtifactWithJSONException() throws Exception {
- String contentStrOne = "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\",\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\"}";
-
- JSONObject documentInfoOne = new JSONObject();
+ String contentStrOne =
+ "{\"fqdn-list\":[{\"vnf-management-server-fqdn\":\"fqdn-value1 url:port\",\"cloud-owner-list\":[{\"cloud-owner\":\"aic3.0\"}";
+
+ JSONObject documentInfoOne = new JSONObject();
documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, contentStrOne);
documentInfoOne.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "ansible_admin_FQDN_Artifact_0.0.1V.json");
-
+
try {
artifactHandlerNode.validateAnsibleAdminArtifact(documentInfoOne);
fail("Missing exception");
- }catch(ArtifactHandlerInternalException je) {
- assertTrue(je.getMessage().contains("JSON Exception"));
-
- }
-
- }
-
+ } catch (ArtifactHandlerInternalException je) {
+ assertTrue(je.getMessage().contains("JSON Exception"));
+ }
+
+ }
+
@Test
public void testProcessArtifactWithException() throws Exception {
SvcLogicContext ctx = new SvcLogicContext();
inParams.put("response_prefix", "prefix");
JSONObject requestInfo = new JSONObject();
JSONObject documentInfo = new JSONObject();
- String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader()
- .getResourceAsStream("templates/reference_template"), Charset.defaultCharset());
+ String artifactContent = IOUtils.toString(
+ ArtifactHandlerProviderUtilTest.class.getClassLoader().getResourceAsStream("templates/reference_template"),
+ Charset.defaultCharset());
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent);
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "");
requestInfo.put("RequestInfo", "testValue");
- requestInfo.put("request-id","testREQUEST_ID");
+ requestInfo.put("request-id", "testREQUEST_ID");
input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo);
input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
postData.put("input", input);
try {
artifactHandlerNode.processArtifact(inParams, ctx);
fail("Missing exception");
- }catch(Exception e) {
- assertTrue(e.getMessage().contains("Missing Artifact Name"));
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Missing Artifact Name"));
}
-
+
}
+
@Test
public void testProcessArtifactWithExceptionforAnsible() throws Exception {
SvcLogicContext ctx = new SvcLogicContext();
inParams.put("response_prefix", "prefix");
JSONObject requestInfo = new JSONObject();
JSONObject documentInfo = new JSONObject();
- String artifactContent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader()
- .getResourceAsStream("templates/reference_template"), Charset.defaultCharset());
+ String artifactContent = IOUtils.toString(
+ ArtifactHandlerProviderUtilTest.class.getClassLoader().getResourceAsStream("templates/reference_template"),
+ Charset.defaultCharset());
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_CONTENTS, artifactContent);
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_NAME, "ansible_admin_FQDN_Artifact_0.0.2V.json");
requestInfo.put("RequestInfo", "testValue");
- requestInfo.put("request-id","testREQUEST_ID");
+ requestInfo.put("request-id", "testREQUEST_ID");
input.put(SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS, documentInfo);
input.put(SdcArtifactHandlerConstants.REQUEST_INFORMATION, requestInfo);
postData.put("input", input);
inParams.put("postData", postData.toString());
-
+
try {
- artifactHandlerNode.processArtifact(inParams, ctx);
- fail("Missing exception");
- }catch(Exception e) {
- assertTrue(e.getMessage().contains("JSON Exception:ansible admin"));
+ artifactHandlerNode.processArtifact(inParams, ctx);
+ fail("Missing exception");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("JSON Exception:ansible admin"));
}
- }
-
+ }
+
@Test
public void testProcessAndStoreCapablitiesArtifact() throws Exception {
ArtifactHandlerNode ah = new ArtifactHandlerNode();
documentInfo.put(SdcArtifactHandlerConstants.SERVICE_DESCRIPTION, "testDesc");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_UUID, "testRes");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME, "testResIns");
+ documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_NAME, "testResName");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_VERSION, "testVers");
documentInfo.put(SdcArtifactHandlerConstants.RESOURCE_TYPE, "testResType");
documentInfo.put(SdcArtifactHandlerConstants.ARTIFACT_UUID, "testArtifactUuid");
Whitebox.invokeMethod(ah, "processAndStoreCapabilitiesArtifact", dbService, documentInfo, capabilities,
"artifactName", "someVnf");
}
-
+
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
-import org.junit.Test;
import org.junit.Ignore;
+import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInput;
import org.opendaylight.yang.gen.v1.org.onap.appc.artifacthandler.rev170321.UploadartifactInputBuilder;
ahprovider.processTemplate(obj.toString());
}
- @Ignore
+ // @Ignore
@Test(expected = Exception.class)
public void testcreateDummyRequestData() throws Exception {
String artifact_conetent = IOUtils.toString(ArtifactHandlerProviderUtilTest.class.getClassLoader()
obj.put("artifact-version", "0.01");
obj.put("artifact-contents", artifact_conetent);
ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil();
- ahprovider.createDummyRequestData();
+ String requestInfo = ahprovider.createDummyRequestData();
}
@Test
assertEquals("Test String is ''test''", ahprovider.escapeSql(testStr));
}
+ @Test
+ public void testGetRandom() throws Exception {
+ ArtifactHandlerProviderUtil ahprovider = new ArtifactHandlerProviderUtil();
+ Whitebox.invokeMethod(ahprovider, "getRandom");
+ assertTrue(true);
+ }
+
@Test
public void testEscapeUtils() throws Exception {
String str = "The Test string is 'test'";
builder.setRequestInformation(mockRequestInformation);
UploadartifactInput uploadArtifactInput = builder.build();
Whitebox.setInternalState(ahprovider, "templateData", uploadArtifactInput);
- assertTrue(ahprovider.createDummyRequestData().startsWith("{\"input\": {\"document-parameters\":{\"service-uuid\":\"TLSUUIDREQUEST ID\""));
+ assertTrue(ahprovider.createDummyRequestData()
+ .startsWith("{\"input\": {\"document-parameters\":{\"service-uuid\":\"TLSUUIDREQUEST ID\""));
}
@Test
ahProvider.createRequestData());
}
}
-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.fasterxml.jackson.annotation.JsonProperty;
public class DesignInfo{
-
+
@JsonProperty("vnf-type")
String vnf_type;
-
+
@JsonProperty("vnfc-type")
String vnfc_type;
-
+
@JsonProperty("protocol")
String protocol;
-
+
@JsonProperty("incart")
String inCart;
-
+
@JsonProperty("action")
String action;
-
+
@JsonProperty("artifact-name")
String artifact_name;
-
@JsonProperty("artifact-type")
String artifact_type;
+ @JsonProperty("permission")
+ String permission;
+
+ @JsonProperty("creatorUserId")
+ String creatorUserId;
+
public String getArtifact_type() {
return artifact_type;
}
this.inCart = inCart;
}
+ public String getPermission() {
+ return permission;
+ }
+
+ public void setPermission(String permission) {
+ this.permission = permission;
+ }
+
+ public String getCreatorUserId() {
+ return creatorUserId;
+ }
+
+ public void setCreatorUserId(String creatorUserId) {
+ this.creatorUserId = creatorUserId;
+ }
+
@Override
public String toString() {
return "DesignInfo [vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol=" + protocol + ", inCart="
+ inCart + "]";
}
-
+
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class DesignResponse{
-
@JsonProperty("userID")
- String userId ;
-
+ String userId;
+
@JsonProperty("designInfo")
List<DesignInfo> designInfoList;
-
+
@JsonProperty("statusInfo")
List<StatusInfo> statusInfoList;
-
+
@JsonProperty("artifactInfo")
List<ArtifactInfo> artifactInfo;
-
+
+ @JsonProperty("vnf-type")
+ String vnfType;
+
+ @JsonProperty("users")
+ List<UserPermissionInfo> users;
public List<ArtifactInfo> getArtifactInfo() {
return artifactInfo;
public void setDesignInfoList(List<DesignInfo> designInfoList) {
this.designInfoList = designInfoList;
}
-
+
public List<StatusInfo> getStatusInfoList() {
return statusInfoList;
}
public void setStatusInfoList(List<StatusInfo> statusInfoList) {
this.statusInfoList = statusInfoList;
}
+
+ public String getVnfType() {
+ return vnfType;
+ }
+
+ public void setVnfType(String vnfType) {
+ this.vnfType = vnfType;
+ }
+
+ public List<UserPermissionInfo> getUsers() {
+ return users;
+ }
+
+ public void setUsers(List<UserPermissionInfo> userPermInfoList) {
+ this.users = userPermInfoList;
+ }
+
}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP : APPC
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * =============================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.design.data;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class UserPermissionInfo {
+
+ @JsonProperty("userID")
+ String userID;
+ @JsonProperty("permission")
+ String permission;
+
+ public String getUserID() {
+ return userID;
+ }
+
+ public String getPermission() {
+ return permission;
+ }
+
+ public void setUserID(String user_id) {
+ this.userID = user_id;
+ }
+
+ public void setPermission(String perm) {
+ this.permission = perm;
+ }
+}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class DbResponseProcessor {
private static final EELFLogger log = EELFManager.getInstance().getLogger(DbResponseProcessor.class);
- public String parseResponse(String dbresposne, String action) throws Exception {
-
- log.info("Starting Parsing the response for action :[" + action + "]\n data:[" + dbresposne +"]" );
- String response ;
+ public String parseResponse(String dbresponse, String action) throws Exception {
+
+ log.info("Starting Parsing the response for action :[" + action + "]\ndata:[" + dbresponse + "]");
+ String response;
switch (action) {
case DesignServiceConstants.GETDESIGNS:
- response = getDesignsResponse(dbresposne);
+ response = getDesignsResponse(dbresponse);
break;
case DesignServiceConstants.GETAPPCTIMESTAMPUTC:
- response = getAppcTimestampResponse(dbresposne);
+ response = getAppcTimestampResponse(dbresponse);
break;
case DesignServiceConstants.ADDINCART:
- response = getAddInCartResponse(dbresposne);
- break ;
+ response = getAddInCartResponse(dbresponse);
+ break;
case DesignServiceConstants.GETARTIFACTREFERENCE:
- response= getArtifactReferenceResponse(dbresposne);
+ response = getArtifactReferenceResponse(dbresponse);
break;
case DesignServiceConstants.GETARTIFACT:
- response= getArtifactResponse(dbresposne);
+ response = getArtifactResponse(dbresponse);
break;
case DesignServiceConstants.GETGUIREFERENCE:
- response= getGuiReferenceResponse(dbresposne);
+ response = getGuiReferenceResponse(dbresponse);
break;
case DesignServiceConstants.GETSTATUS:
- response= getStatusResponse(dbresposne);
+ response = getStatusResponse(dbresponse);
break;
case DesignServiceConstants.UPLOADARTIFACT:
- response= getsetStatusResponse(dbresposne);
- break;
+ response = getSetStatusResponse(dbresponse);
+ break;
case DesignServiceConstants.SETPROTOCOLREFERENCE:
- response= getsetStatusResponse(dbresposne);
- break;
+ response = getSetStatusResponse(dbresponse);
+ break;
case DesignServiceConstants.SETINCART:
- response= getsetStatusResponse(dbresposne);
- break;
+ response = getSetStatusResponse(dbresponse);
+ break;
case DesignServiceConstants.UPLOADADMINARTIFACT:
- response= getsetStatusResponse(dbresposne);
- break;
+ response = getSetStatusResponse(dbresponse);
+ break;
case DesignServiceConstants.CHECKVNF:
- response= getStatusResponse(dbresposne);
- break;
+ response = getStatusResponse(dbresponse);
+ break;
+ case DesignServiceConstants.RETRIEVEVNFPERMISSIONS:
+ response = getStatusResponse(dbresponse);
+ break;
+ case DesignServiceConstants.SAVEVNFPERMISSIONS:
+ response = getRetrieveVnfPermissionsResponse(dbresponse);
+ break;
default:
- log.error("Action " + action + " Not Supported by response Parser");
- throw new Exception(" Action " + action + " not found while processing request ");
+ log.error("Action " + action + " Not Supported by Response Parser");
+ throw new Exception("Action " + action + " not found while processing request");
- }
- return response;
+ }
+ return response;
}
- private String getArtifactResponse(String dbresposne) {
+ private String getArtifactResponse(String dbresponse) {
// TODO Auto-generated method stub
- return dbresposne;
+ return dbresponse;
}
- private String getsetStatusResponse(String dbresposne) {
+ private String getSetStatusResponse(String dbresponse) {
// TODO Auto-generated method stub
return null;
}
- private String getStatusResponse(String dbresposne) {
- log.info("Returning reposne from Response Parser " + dbresposne);
- return dbresposne;
+ private String getStatusResponse(String dbresponse) {
+ log.info("Returning response from Response Parser " + dbresponse);
+ return dbresponse;
}
- private String getGuiReferenceResponse(String dbresposne) {
+ private String getGuiReferenceResponse(String dbresponse) {
// TODO Auto-generated method stub
return null;
}
- private String getArtifactReferenceResponse(String dbresposne) {
+ private String getArtifactReferenceResponse(String dbresponse) {
// TODO Auto-generated method stub
return null;
}
- private String getAddInCartResponse(String dbresposne) {
+ private String getAddInCartResponse(String dbresponse) {
// TODO Auto-generated method stub
return null;
}
- private String getDesignsResponse(String dbresposne) {
- return dbresposne;
-
+ private String getDesignsResponse(String dbresponse) {
+ return dbresponse;
}
- private String getAppcTimestampResponse(String dbresposne) {
- log.info("getAppcTimestampResponse:[" + dbresposne +"]" );
- return dbresposne;
+ private String getAppcTimestampResponse(String dbresponse) {
+ log.info("getAppcTimestampResponse:[" + dbresponse +"]" );
+ return dbresponse;
}
+
+ private String getRetrieveVnfPermissionsResponse(String dbresponse) {
+ log.info("Returning response from Response Parser " + dbresponse);
+ return dbresponse;
+ }
+
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Strings;
+
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
+import java.util.Date;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
import org.json.JSONObject;
import org.onap.appc.design.data.ArtifactInfo;
import org.onap.appc.design.data.DesignInfo;
import org.onap.appc.design.data.DesignResponse;
import org.onap.appc.design.data.StatusInfo;
+import org.onap.appc.design.data.UserPermissionInfo;
import org.onap.appc.design.services.util.ArtifactHandlerClient;
import org.onap.appc.design.services.util.DesignServiceConstants;
import org.onap.ccsdk.sli.adaptors.resource.sql.SqlResource;
import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
-import org.apache.commons.lang.StringUtils;
public class DesignDBService {
private static final EELFLogger log = EELFManager.getInstance().getLogger(DesignDBService.class);
private static DesignDBService dgGeneralDBService;
-
+ private static ArtifactHandlerFactory artifactHandlerFactory = new ArtifactHandlerFactory();
private static final String SUCCESS_JSON = "{\"update\" : \"success\" } ";
private static final String STATUS = "STATUS";
- private static final String INFO_STR = "Info : ";
- private static final String DB_OPERATION_ERROR = "Error while DB operation : ";
+ private static final String INFO_STR = "Info: ";
+ private static final String DB_OPERATION_ERROR = "Error during DB operation: ";
private static final String VNFC_TYPE = "vnfc-type";
- private static final String QUERY_STR = "Query String :";
+ private static final String VNF_TYPE = "vnf-type";
+ private static final String QUERY_STR = "Query String: ";
private static final String USER_ID = "userID";
+ private static final String COLUMN_USER_ID = "user_id";
+ private static final String COLUMN_PERMISSION = "permission";
private SvcLogicResource serviceLogic;
private DbService dbservice;
- private static ArtifactHandlerFactory artifactHandlerFactory = new ArtifactHandlerFactory();
-
public static DesignDBService initialise() {
if (dgGeneralDBService == null) {
dgGeneralDBService = new DesignDBService();
}
}
- public String execute(String action, String payload, String requestID) throws Exception {
+ public String execute(String action, String payload, String requestId) throws Exception {
- log.info("Received execute request for action : " + action + " with Payload : " + payload);
+ log.info("Received execute request for action: " + action + " with Payload: " + payload);
RequestValidator.validate(action, payload);
String response;
dbservice = new DbService();
switch (action) {
case DesignServiceConstants.GETDESIGNS:
- response = getDesigns(payload, requestID);
+ response = getDesigns(payload, requestId);
break;
case DesignServiceConstants.GETAPPCTIMESTAMPUTC:
- response = getAppcTimestampUTC( requestID );
+ response = getAppcTimestampUTC(requestId);
break;
case DesignServiceConstants.ADDINCART:
- response = setInCart(payload, requestID);
+ response = setInCart(payload, requestId);
break;
case DesignServiceConstants.GETARTIFACTREFERENCE:
- response = getArtifactReference(payload, requestID);
+ response = getArtifactReference(payload, requestId);
break;
case DesignServiceConstants.GETARTIFACT:
- response = getArtifact(payload, requestID);
+ response = getArtifact(payload, requestId);
break;
case DesignServiceConstants.GETGUIREFERENCE:
- response = getGuiReference(payload, requestID);
+ response = getGuiReference(payload, requestId);
break;
case DesignServiceConstants.GETSTATUS:
- response = getStatus(payload, requestID);
+ response = getStatus(payload, requestId);
break;
case DesignServiceConstants.SETSTATUS:
- response = setStatus(payload, requestID);
+ response = setStatus(payload, requestId);
break;
case DesignServiceConstants.UPLOADARTIFACT:
- response = uploadArtifact(payload, requestID);
+ response = uploadArtifact(payload, requestId);
break;
case DesignServiceConstants.SETPROTOCOLREFERENCE:
- response = setProtocolReference(payload, requestID);
+ response = setProtocolReference(payload, requestId);
break;
case DesignServiceConstants.UPLOADADMINARTIFACT:
- response = uploadAdminArtifact(payload, requestID);
+ response = uploadAdminArtifact(payload, requestId);
break;
case DesignServiceConstants.CHECKVNF:
- response = checkVNF(payload, requestID);
+ response = checkVNF(payload, requestId);
+ break;
+ case DesignServiceConstants.RETRIEVEVNFPERMISSIONS:
+ response = retrieveVnfPermissions(payload, requestId);
+ break;
+ case DesignServiceConstants.SAVEVNFPERMISSIONS:
+ response = saveUserPermissionInfo(payload, requestId);
break;
default:
- throw new DBException(" Action " + action + " not found while processing request ");
+ throw new DBException("Action " + action + " not found while processing request");
}
return response;
}
+ private String saveUserPermissionInfo(String payload, String requestId) throws Exception {
+ try {
+ if (requestId == null || requestId.isEmpty()) {
+ throw new DBException("requestId in saveUserPermissionInfo request is null or Blank");
+ }
+ log.info("Received Save User Permission from " + requestId + " with payload " + payload);
+ Date startTime = new Date();
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ String dbDate = dateFormat.format(startTime);
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode payloadObject = objectMapper.readTree(payload);
+ String vnf_type = payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue();
+ String modifier = payloadObject.get(DesignServiceConstants.CREATORUSERID).textValue();
+ JsonNode users = payloadObject.get("users");
+ if (users == null || !users.isArray()) {
+ throw new DBException("Users list is not provided in the input payload");
+ }
+ for (JsonNode node : users) {
+ String userId = node.get(DesignServiceConstants.USER_ID).textValue();
+ String permission = node.get(DesignServiceConstants.PERMISSION).textValue();
+ ArrayList<String> argList = new ArrayList<>();
+ argList.add(vnf_type);
+ argList.add(userId);
+ log.info("Checking User - " + userId + " current permissions in db for this vnf type");
+ String queryString = "SELECT PERMISSION FROM DT_USER_PERMISSIONS WHERE VNF_TYPE = ? AND USER_ID = ?";
+ log.info(QUERY_STR + queryString);
+ String user_permission = null;
+ int rowCount = 0;
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ while (data.next()) {
+ rowCount++;
+ user_permission = data.getString("PERMISSION");
+ if (Strings.isNullOrEmpty(permission)) {
+ log.info("Received request to delete db record for User - " + userId);
+ ArrayList<String> delArgList = new ArrayList<>();
+ delArgList.add(vnf_type);
+ delArgList.add(userId);
+ String deleteQuery = "DELETE FROM DT_USER_PERMISSIONS WHERE VNF_TYPE = ? AND USER_ID = ?";
+ log.info(QUERY_STR + deleteQuery);
+ log.info("Arguments List: " + delArgList);
+ boolean status = dbservice.updateDBData(deleteQuery, delArgList);
+ if (!status) {
+ throw new DBException("Error while deleting record from DT_USER_PERMISSIONS");
+ } else {
+ log.info("Record deleted");
+ }
+ } else if (user_permission.matches(permission)) {
+ log.info("User " + userId + " permission record found in db for same vnf_type " + vnf_type
+ + ". No update needed.");
+ } else {
+ log.info("User's permission record will be updated. New permission: " + permission
+ + " for user " + userId + " as requested by " + requestId
+ + " will be saved to database.");
+ ArrayList<String> updateArgList = new ArrayList<>();
+ updateArgList.add(permission);
+ updateArgList.add(modifier);
+ updateArgList.add(dbDate);
+ updateArgList.add(vnf_type);
+ updateArgList.add(userId);
+
+ String updateQuery =
+ "UPDATE DT_USER_PERMISSIONS SET PERMISSION = ?, MODIFIER = ?, DATE_MODIFIED = ?"
+ + " WHERE VNF_TYPE = ? AND USER_ID = ?";
+ log.info(QUERY_STR + updateQuery);
+ log.info("Arguments List: " + updateArgList);
+ boolean updateStatus = dbservice.updateDBData(updateQuery, updateArgList);
+ if (!updateStatus) {
+ throw new DBException("Error while updating User Permissions");
+ }
+ }
+ }
+ }
+ if (rowCount == 0 && !(Strings.isNullOrEmpty(permission))) {
+ log.info("User not found in database for this vnf_type. The new permission " + permission
+ + " for user " + userId + " and vnf_type " + vnf_type + " as requested by " + requestId
+ + " will be saved to database.");
+ ArrayList<String> insertArgList = new ArrayList<>();
+ insertArgList.add(vnf_type);
+ insertArgList.add(userId);
+ insertArgList.add(permission);
+ insertArgList.add(modifier);
+ String insertQuery =
+ "INSERT INTO DT_USER_PERMISSIONS (VNF_TYPE, USER_ID, PERMISSION, DATE_MODIFIED, MODIFIER)"
+ + " VALUES (?, ?, ?, sysdate(), ?)";
+ log.info(QUERY_STR + insertQuery);
+ log.info("Arguments List: " + insertArgList);
+ boolean updateStatus = dbservice.updateDBData(insertQuery, insertArgList);
+ if (!updateStatus) {
+ throw new DBException("Error while inserting record for User Permissions");
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("An error occurred in saveUserPermissionInfo " + e.getMessage(), e);
+ throw e;
+ }
+ return SUCCESS_JSON;
+ }
+
private String checkVNF(String payload, String requestId) throws Exception {
+ try {
+ log.info("Got into Check VNF Request with payload: " + payload);
+ if (payload == null || payload.isEmpty()) {
+ throw new DBException("Payload in CheckVNF request is null or Blank");
+ }
+ if (requestId == null || requestId.isEmpty()) {
+ throw new DBException("requestId in CheckVNF request is null or Blank");
+ }
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode payloadObject = objectMapper.readTree(payload);
+ String vnfType = payloadObject.get("vnf-type").textValue();
- log.info("Got into Check VNF Request with payload: " + payload);
- if (StringUtils.isBlank(payload))
- throw new DBException("Payload in CheckVNF request is null or Blank");
- if (StringUtils.isBlank(requestId))
- throw new DBException("requestId in CheckVNF request is null or Blank");
- ObjectMapper objectMapper = new ObjectMapper();
- JsonNode payloadObject = objectMapper.readTree(payload);
- String vnfType = payloadObject.get("vnf-type").textValue();
- log.info("Check VNF Request with VNF TYPE: " + vnfType);
- ArrayList<String> argList = new ArrayList<>();
- argList.add(vnfType);
- String queryString = "SELECT DT_ACTION_STATUS_ID,USER FROM sdnctl.DT_ACTION_STATUS WHERE VNF_TYPE = ? ORDER BY DT_ACTION_STATUS_ID DESC LIMIT 1 ; ";
- log.info(QUERY_STR + queryString);
- ResultSet data = dbservice.getDBData(queryString, argList);
- int rowCount = 0;
- String user = null;
- String dtActionStatusId = null;
- while (data.next()) {
- rowCount++;
- user = data.getString("USER");
- dtActionStatusId = data.getString("DT_ACTION_STATUS_ID");
- }
- log.debug("DT_ACTION_STATUS_ID-> " + dtActionStatusId + " user-> " + user);
- JSONObject jObject = new JSONObject();
- if (rowCount == 0) {
- log.debug("vnf-type does not present in APPC DB, row Count:" + rowCount);
- jObject.put("result", "No");
- } else {
- log.debug("vnf-type present in APPC DB, row Count:" + rowCount);
- jObject.put("result", "Yes");
- jObject.put("user", user);
- }
- log.info("Check VNF result: " + jObject.toString());
+ log.info("Check VNF Request with VNF TYPE: " + vnfType);
+
+ ArrayList<String> argList = new ArrayList<>();
+ argList.add(vnfType);
+
+ String queryString =
+ "SELECT DT_ACTION_STATUS_ID, USER FROM sdnctl.DT_ACTION_STATUS WHERE VNF_TYPE = ?"
+ + " ORDER BY DT_ACTION_STATUS_ID DESC LIMIT 1;";
+
+ log.info(QUERY_STR + queryString);
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+
+ int rowCount = 0;
+ String user = null;
+ String dtActionStatusId = null;
+
+ while (data.next()) {
+ rowCount++;
+ user = data.getString("USER");
+ dtActionStatusId = data.getString("DT_ACTION_STATUS_ID");
+ }
+
+ log.debug("DT_ACTION_STATUS_ID " + dtActionStatusId + " user " + user);
+
+ JSONObject jObject = new JSONObject();
+
+
+ if (rowCount == 0) {
+ log.debug("vnf-type not present in APPC DB, row Count: " + rowCount);
+ jObject.put("result", "No");
+ } else {
+ log.debug("vnf-type present in APPC DB, row Count: " + rowCount);
+ jObject.put("result", "Yes");
+ jObject.put("user", user);
+ }
+
+ log.info("Check VNF result: " + jObject.toString());
+ return jObject.toString();
- return jObject.toString();
+ }
+ } catch (Exception e) {
+ log.error("An error occurred in checkVNF " + e.getMessage(), e);
+ throw e;
+ }
}
private String uploadAdminArtifact(String payload, String requestId) throws Exception {
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
+ JsonNode payloadObject = objectMapper.readTree(payload);
+ log.info("Got upload Admin Artifact with requestId: " + requestId + " & Payload: "
+ + payloadObject.asText());
+
+ if (Strings.isNullOrEmpty(requestId)) {
+ throw new DBException("Request-id is missing in the uploadAdminArtifact payload.");
+ }
+
+ ArtifactHandlerClient ac = new ArtifactHandlerClient();
+ String requestString = ac.createArtifactData(payload, requestId);
+ ac.execute(requestString, "POST");
- ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
- JsonNode payloadObject = objectMapper.readTree(payload);
- log.info("Got upload Admin Aritfact with requestId : " + requestId + " & Payload" + payloadObject.asText());
- if (StringUtils.isBlank(requestId)) {
- throw new DBException("Request-id is missing in the uploadAdminArtifact payload . ");
- }
- ArtifactHandlerClient ac = new ArtifactHandlerClient();
- String requestString = ac.createArtifactData(payload, requestId);
- ac.execute(requestString, "POST");
+ int sdcArtifactId = getSDCArtifactIDbyRequestID(requestId);
+ if (sdcArtifactId == 0) {
+ throw new DBException("Error occurred while validating/Saving the artifact to SDC_ARTIFACTS"
+ + " or getting SDC_ARTIFACTS_ID.");
+ }
- int sdcArtifactId = getSDCArtifactIDbyRequestID(requestId);
- if (sdcArtifactId == 0)
- throw new DBException(
- "Error occured while validating/Saving the artifact to SDC_ARTIFACTS or getting SDC_ARTIFACTS_ID .");
- JsonNode json = payloadObject.get(DesignServiceConstants.USER_ID);
- if (json == null) {
- throw new DBException("User Id is null");
- } else if (json.asText().trim().isEmpty()) {
- log.info("UserId in Admin Aritfact is blank, User Id : " + json.asText());
- throw new DBException("User Id is blank");
- }
+ JsonNode json = payloadObject.get(DesignServiceConstants.USER_ID);
+ if (json == null) {
+ throw new DBException("User Id is null");
+ } else if (json.asText().trim().isEmpty()) {
+ log.info("UserId in Admin Artifact is blank, User Id: " + json.asText());
+ throw new DBException("User Id is blank");
+ }
- int sdcReferenceId = 0;
- createArtifactTrackingRecord(payload, requestId, sdcArtifactId, sdcReferenceId);
+ int sdcReferenceId = 0;
+ createArtifactTrackingRecord(payload, requestId, sdcArtifactId, sdcReferenceId);
+ } catch (Exception e) {
+ log.error("An error occurred in uploadAdminArtifact: " + e.getMessage(), e);
+ throw e;
+ }
return SUCCESS_JSON;
}
- private String getAppcTimestampUTC( String requestID) throws Exception
- {
- log.info("Starting getAppcTimestampUTC: requestID:" + requestID );
- java.util.TimeZone gmtTZ= java.util.TimeZone.getTimeZone("GMT");
- java.text.SimpleDateFormat formatter =
- new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );
- formatter.setTimeZone( gmtTZ );
- java.util.Date dateVal= new java.util.Date();
- log.info("getAppcTimestampUTC: current local Date:[" + dateVal+ "]");
- String timeStr= formatter.format( dateVal );
- log.info("getAppcTimestampUTC: returning:[" + timeStr + "]");
- return timeStr;
+ private String getAppcTimestampUTC(String requestId) throws Exception {
+ log.info("Starting getAppcTimestampUTC: requestId: " + requestId);
+ java.util.TimeZone gmtTZ = java.util.TimeZone.getTimeZone("GMT");
+ java.text.SimpleDateFormat formatter =
+ new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+ formatter.setTimeZone(gmtTZ);
+ java.util.Date dateVal = new java.util.Date();
+ log.info("getAppcTimestampUTC: current local Date: [" + dateVal + "]");
+ String timeStr = formatter.format(dateVal);
+ log.info("getAppcTimestampUTC: returning: [" + timeStr + "]");
+ return timeStr;
}
- private String setInCart(String payload, String requestID) throws Exception {
+ private String setInCart(String payload, String requestId) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode payloadObject = objectMapper.readTree(payload);
argList.add(payloadObject.get(DesignServiceConstants.INCART).textValue());
argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue());
- String queryString = "UPDATE DT_ARTIFACT_TRACKING SET INCART= ? WHERE ASDC_REFERENCE_ID IN "
- + " (SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE_ID WHERE VNF_TYPE = ? ";
+ String queryString =
+ "UPDATE DT_ARTIFACT_TRACKING SET INCART = ? WHERE ASDC_REFERENCE_ID IN"
+ + " (SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE_ID WHERE VNF_TYPE = ?";
- if (payloadObject.get(DesignServiceConstants.VNF_TYPE) != null && !payloadObject
- .get(DesignServiceConstants.VNF_TYPE).textValue().isEmpty()) {
- queryString = queryString + " AND VNFC_TYPE = ? ) AND USER = ? ";
+ if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null
+ && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
+ queryString += " AND VNFC_TYPE = ?";
argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
- } else {
- queryString = queryString + " ) AND USER = ? ";
}
+ queryString += ") AND USER = ?";
argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
log.info(QUERY_STR + queryString);
boolean data = dbservice.updateDBData(queryString, argList);
return SUCCESS_JSON;
}
- private String setProtocolReference(String payload, String requestID) throws Exception {
+ private String setProtocolReference(String payload, String requestId) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode payloadObject = objectMapper.readTree(payload);
argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue());
argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue());
- String queryString = " DELETE FROM PROTOCOL_REFERENCE WHERE ACTION = ? AND ACTION_LEVEL AND VNF_TYPE= ? AND PROTOCOL = ? ";
+ String queryString = "DELETE FROM PROTOCOL_REFERENCE WHERE ACTION = ? AND ACTION_LEVEL AND VNF_TYPE = ? AND PROTOCOL = ?";
- log.info("Delete Query String :" + queryString);
+ log.info("Delete Query String: " + queryString);
boolean data;
log.info("Record Deleted");
if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null &&
!payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
- queryString = queryString + " AND VNFC_TYPE = ? )";
- } else {
- queryString = queryString + " ) ";
+ queryString += " AND VNFC_TYPE = ?";
}
+ queryString += ")";
log.info(QUERY_STR + queryString);
data = dbservice.updateDBData(queryString, argList);
return SUCCESS_JSON;
}
- private String uploadArtifact(String payload, String requestID) throws Exception {
+ private String uploadArtifact(String payload, String requestId) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
JsonNode payloadObject = objectMapper.readTree(payload);
- log.info("Got upload Aritfact with Payload : " + payloadObject.asText());
+ log.info("Got upload Artifact with Payload: " + payloadObject.asText());
try {
ArtifactHandlerClient ac = artifactHandlerFactory.ahi();
- String requestString = ac.createArtifactData(payload, requestID);
+ String requestString = ac.createArtifactData(payload, requestId);
ac.execute(requestString, "POST");
- int sdcArtifactId = getSDCArtifactIDbyRequestID(requestID);
+ int sdcArtifactId = getSDCArtifactIDbyRequestID(requestId);
int sdcReferenceId = getSDCReferenceID(payload);
- createArtifactTrackingRecord(payload, requestID, sdcArtifactId, sdcReferenceId);
+ createArtifactTrackingRecord(payload, requestId, sdcArtifactId, sdcReferenceId);
String status = getDataFromActionStatus(payload, STATUS);
if (status == null || status.isEmpty()) {
- log.info("Action Status is: "+ status);
- setActionStatus(payload, "Not Tested");
+ log.info("Action Status is: " + status);
+ setActionStatus(payload, "Not Tested");
}
linkstatusRelationShip(sdcArtifactId, sdcReferenceId, payload);
-
+ savePermissionInfo(payload, requestId);
} catch (Exception e) {
- log.error("An error occured in uploadArtifact", e);
+ log.error("An error occurred in uploadArtifact", e);
throw e;
}
return SUCCESS_JSON;
}
+ private void savePermissionInfo(String payload, String requestId) throws Exception {
+
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode payloadObject = objectMapper.readTree(payload);
+ ArrayList<String> argList = new ArrayList<>();
+ argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue());
+ argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
+ log.info("Entered savePermissionInfo from uploadArtifact with payload " + payload);
+ String queryString = "SELECT PERMISSION FROM DT_USER_PERMISSIONS WHERE VNF_TYPE = ? AND USER_ID = ?";
+ log.info(QUERY_STR + queryString);
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ String user_permission = null;
+ int rowCount = 0;
+ while (data.next()) {
+ rowCount++;
+ user_permission = data.getString("PERMISSION");
+ log.info("User exists in database with permission = " + user_permission);
+ }
+ if (rowCount == 0) {
+ log.info("No record found in database");
+ log.info("Inserting one record in database");
+ String permission = "owner";
+ ArrayList<String> insertArgList = new ArrayList<>();
+ insertArgList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue());
+ insertArgList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
+ insertArgList.add(permission);
+ insertArgList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
+ String insertQuery =
+ "INSERT INTO DT_USER_PERMISSIONS (VNF_TYPE, USER_ID, PERMISSION, DATE_MODIFIED, MODIFIER)"
+ + " VALUES (?, ?, ?, sysdate(), ?)";
+ log.info(QUERY_STR + insertQuery);
+ log.info("Arguments List: " + insertArgList);
+ boolean updateStatus = dbservice.updateDBData(insertQuery, insertArgList);
+ if (!updateStatus) {
+ throw new DBException("Error while inserting record to DT_USER_PERMISSIONS");
+ }
+ }
+ }
+ }
private void linkstatusRelationShip(int sdcArtifactId, int sdcReferenceId, String payload) throws Exception {
argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
String queryString =
- "INSERT INTO DT_STATUS_RELATIONSHIP (DT_ARTIFACT_TRACKING_ID,DT_ACTION_STATUS_ID) VALUES " +
- "(( SELECT DT_ARTIFACT_TRACKING_ID FROM DT_ARTIFACT_TRACKING WHERE ASDC_ARTIFACTS_ID = ? AND ASDC_REFERENCE_ID = ? ) , "
- + "( SELECT DT_ACTION_STATUS_ID FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? ";
-
- if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
- .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
- queryString = queryString + " AND VNFC_TYPE = ? GROUP BY VNF_TYPE HAVING COUNT(VNF_TYPE)>=1 ) )";
- } else {
- queryString = queryString + " GROUP BY VNF_TYPE HAVING COUNT(VNF_TYPE)>=1 ) ) ";
+ "INSERT INTO DT_STATUS_RELATIONSHIP (DT_ARTIFACT_TRACKING_ID, DT_ACTION_STATUS_ID) VALUES"
+ + " ((SELECT DT_ARTIFACT_TRACKING_ID FROM DT_ARTIFACT_TRACKING"
+ + " WHERE ASDC_ARTIFACTS_ID = ? AND ASDC_REFERENCE_ID = ?),"
+ + " (SELECT DT_ACTION_STATUS_ID FROM DT_ACTION_STATUS"
+ + " WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ?";
+
+ if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null
+ && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
+ queryString += " AND VNFC_TYPE = ?";
}
+ queryString += " GROUP BY VNF_TYPE HAVING COUNT(VNF_TYPE)>=1 ))";
log.info(QUERY_STR + queryString);
boolean data = dbservice.updateDBData(queryString, argList);
if (!data) {
- throw new DBException("Error while updating RelationShip table");
+ throw new DBException("Error while updating Relationship table");
}
}
argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_TYPE).textValue());
argList.add(payloadObject.get(DesignServiceConstants.ARTIFACT_NAME).textValue());
- String queryString = " SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE WHERE VNF_TYPE = ? "
- + " AND ARTIFACT_TYPE = ? AND ARTIFACT_NAME = ? ";
+ String queryString =
+ "SELECT ASDC_REFERENCE_ID FROM ASDC_REFERENCE WHERE VNF_TYPE = ?"
+ + " AND ARTIFACT_TYPE = ? AND ARTIFACT_NAME = ?";
- if (payloadObject.get(DesignServiceConstants.ACTION) != null && !payloadObject
- .get(DesignServiceConstants.ACTION).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.ACTION) != null
+ && !payloadObject.get(DesignServiceConstants.ACTION).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue());
- queryString = queryString + " AND ACTION = ? ";
+ queryString += " AND ACTION = ?";
}
- if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
- .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null
+ && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
- queryString = queryString + " AND VNFC_TYPE = ? ";
-
+ queryString += " AND VNFC_TYPE = ?";
}
log.info(QUERY_STR + queryString);
- ResultSet data = dbservice.getDBData(queryString, argList);
- int sdcReferenceId = 0;
- while (data.next()) {
- sdcReferenceId = data.getInt("ASDC_REFERENCE_ID");
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ int sdcReferenceId = 0;
+ while (data.next()) {
+ sdcReferenceId = data.getInt("ASDC_REFERENCE_ID");
+ }
+ log.info("Got sdcReferenceId = " + sdcReferenceId);
+ return sdcReferenceId;
}
- log.info("Got sdcReferenceId= " + sdcReferenceId);
- return sdcReferenceId;
}
private String getDataFromActionStatus(String payload, String dataValue) throws Exception {
argList.add(payloadObject.get(DesignServiceConstants.ACTION).textValue());
argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
String queryString =
- " SELECT " + dataValue + " FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ? ";
- if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
- .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
+ "SELECT " + dataValue + " FROM DT_ACTION_STATUS WHERE VNF_TYPE = ? AND ACTION = ? AND USER = ?";
+ if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null
+ && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
- queryString = queryString + " AND VNFC_TYPE = ? ";
+ queryString += " AND VNFC_TYPE = ?";
}
log.info(QUERY_STR + queryString);
- ResultSet data = dbservice.getDBData(queryString, argList);
- while (data.next()) {
- status = data.getString(STATUS);
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ while (data.next()) {
+ status = data.getString(STATUS);
+ }
+ log.info("DT_ACTION_STATUS Status = " + status);
+ return status;
}
- log.info("DT_ACTION_STATUS Status = " + status);
- return status;
}
private void setActionStatus(String payload, String status) throws Exception {
argList.add(payloadObject.get(DesignServiceConstants.VNF_TYPE).textValue());
String insertQuery = " INSERT INTO DT_ACTION_STATUS (ACTION, VNF_TYPE, VNFC_TYPE, USER, TECHNOLOGY, UPDATED_DATE, STATUS) VALUES (?,?,?,?,?,sysdate() , ?); ";
- if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null && !payloadObject
- .get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.VNFC_TYPE) != null
+ && !payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
log.info("Vnfc-Type: " + payloadObject.get(DesignServiceConstants.VNFC_TYPE).textValue());
} else {
argList.add(null);
}
argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
- if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null && !payloadObject
- .get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null
+ && !payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue());
} else {
argList.add(null);
log.info("QueryString: " + insertQuery);
log.info("Arguments List: " + argList);
boolean updateStatus = dbservice.updateDBData(insertQuery, argList);
- if (!updateStatus)
+ if (!updateStatus) {
throw new DBException("Error while updating Action Status");
+ }
}
- private void createArtifactTrackingRecord(String payload, String requestID, int sdcArtifactId, int sdcReferenceId)
- throws Exception {
+ private void createArtifactTrackingRecord(String payload, String requestId, int sdcArtifactId, int sdcReferenceId)
+ throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode payloadObject = objectMapper.readTree(payload);
argList.add(String.valueOf(sdcArtifactId));
argList.add(String.valueOf(sdcReferenceId));
argList.add(payloadObject.get(DesignServiceConstants.USER_ID).textValue());
- if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null && !payloadObject
- .get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.TECHNOLOGY) != null
+ && !payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.TECHNOLOGY).textValue());
} else {
argList.add("");
}
- if (payloadObject.get(DesignServiceConstants.PROTOCOL) != null && !payloadObject
- .get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) {
+ if (payloadObject.get(DesignServiceConstants.PROTOCOL) != null
+ && !payloadObject.get(DesignServiceConstants.PROTOCOL).textValue().isEmpty()) {
argList.add(payloadObject.get(DesignServiceConstants.PROTOCOL).textValue());
} else {
argList.add("");
}
- String queryString = "INSERT INTO DT_ARTIFACT_TRACKING (ASDC_ARTIFACTS_ID, ASDC_REFERENCE_ID, USER, TECHNOLOGY, CREATION_DATE, UPDATED_DATE, ARTIFACT_STATUS, PROTOCOL, IN_CART) VALUES (? , ? , ?, ?, sysdate() , sysdate(), 'Created', ? ,'N' )";
+ String queryString =
+ "INSERT INTO DT_ARTIFACT_TRACKING (ASDC_ARTIFACTS_ID, ASDC_REFERENCE_ID, USER, TECHNOLOGY,"
+ + " CREATION_DATE, UPDATED_DATE, ARTIFACT_STATUS, PROTOCOL, IN_CART)"
+ + " VALUES (?, ?, ?, ?, sysdate(), sysdate(), 'Created', ?, 'N')";
log.info(QUERY_STR + queryString);
boolean data = dbservice.updateDBData(queryString, argList);
if (!data) {
- throw new DBException("Error Updating DT_ARTIFACT_TRACKING ");
+ throw new DBException("Error Updating DT_ARTIFACT_TRACKING");
}
}
- private int getSDCArtifactIDbyRequestID(String requestID) throws Exception {
+ private int getSDCArtifactIDbyRequestID(String requestId) throws Exception {
log.info("Starting getArtifactIDbyRequestID DB Operation");
int artifactId = 0;
try {
ArrayList<String> argList = new ArrayList<>();
- argList.add("TLSUUID" + requestID);
- String queryString = " SELECT ASDC_ARTIFACTS_ID FROM ASDC_ARTIFACTS where SERVICE_UUID = ? ";
- log.info(QUERY_STR + queryString+ " & UUID or" + "TLSUUID :" + requestID);
- ResultSet data = dbservice.getDBData(queryString, argList);
- while (data.next()) {
- artifactId = data.getInt("ASDC_ARTIFACTS_ID");
+ argList.add("TLSUUID" + requestId);
+ String queryString = "SELECT ASDC_ARTIFACTS_ID FROM ASDC_ARTIFACTS where SERVICE_UUID = ?";
+ log.info(QUERY_STR + queryString + " & UUID: " + "TLSUUID" + requestId);
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ while (data.next()) {
+ artifactId = data.getInt("ASDC_ARTIFACTS_ID");
+ }
}
} catch (Exception e) {
log.error("An error occurred in getSDCArtifactIDbyRequestID", e);
throw e;
}
- log.info("Got SDC_ARTIFACTS_ID As :" + artifactId);
+ log.info("Got SDC_ARTIFACTS_ID As: " + artifactId);
return artifactId;
}
- private String getArtifact(String payload, String requestID) throws Exception {
+ private String getArtifact(String payload, String requestId) throws Exception {
log.info("Starting getArtifact DB Operation");
try {
ObjectMapper objectMapper = new ObjectMapper();
argList.add(artifactName);
argList.add(payloadObject.get("artifact-type").textValue());
- String queryString = "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS where "
- + " ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ? ";
+ String queryString =
+ "SELECT INTERNAL_VERSION, ARTIFACT_CONTENT FROM ASDC_ARTIFACTS"
+ + " where ARTIFACT_NAME = ? AND ARTIFACT_TYPE = ?";
+
log.info(QUERY_STR + queryString);
- ResultSet data = dbservice.getDBData(queryString, argList);
String artifactContent = null;
- int rowCount = 0;
- int hightestVerion = -1;
- while (data.next()) {
- rowCount++;
- int version = data.getInt("INTERNAL_VERSION");
- if (hightestVerion < version) {
- artifactContent = data.getString("ARTIFACT_CONTENT");
- hightestVerion = version;
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+
+ int rowCount = 0;
+ int highestVersion = -1;
+
+ while (data.next()) {
+ rowCount++;
+
+ int version = data.getInt("INTERNAL_VERSION");
+ if (highestVersion < version) {
+ artifactContent = data.getString("ARTIFACT_CONTENT");
+ highestVersion = version;
+ }
+ }
+
+ log.debug("No of rows: " + rowCount + " highest Internal Version " + highestVersion);
+
+ if (rowCount == 0) {
+ throw new DBException(
+ "Sorry!!! APPC DB doesn't have any artifact Named: " + artifactName);
+ }
+
+ if (artifactContent == null || artifactContent.isEmpty()) {
+ throw new DBException("Sorry!!! Artifact Content is stored blank in APPC DB for " + artifactName
+ + " and Internal version " + highestVersion);
}
}
- log.debug("No of rows: " + rowCount + " highest Inetrnal Version" + hightestVerion);
- if (rowCount == 0) {
- throw new DBException("Sorry !!!APPC DB doesn't have any artifact Named : " + artifactName);
- }
- if (artifactContent == null || artifactContent.isEmpty()) {
- throw new DBException("Sorry !!! Artifact Content is stored blank in APPC DB for " + artifactName
- + " and Internal version " + hightestVerion);
- }
+
DesignResponse designResponse = new DesignResponse();
List<ArtifactInfo> artifactInfoList = new ArrayList<>();
ArtifactInfo artifactInfo = new ArtifactInfo();
designResponse.setArtifactInfo(artifactInfoList);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(designResponse);
- log.debug("End of getArtifact:" + INFO_STR + jsonString);
+ log.debug("End of getArtifact: " + INFO_STR + jsonString);
return jsonString;
} catch (Exception e) {
log.error(DB_OPERATION_ERROR, e);
}
}
- private String setStatus(String payload, String requestID) throws Exception {
+ private String setStatus(String payload, String requestId) throws Exception {
log.info("Starting getStatus DB Operation");
try {
if (payloadObject.get(VNFC_TYPE) != null && !payloadObject.get(VNFC_TYPE).textValue().isEmpty()) {
argList.add(payloadObject.get(VNFC_TYPE).textValue());
- queryString = queryString + " and DAS.VNFC_TYPE = ? ";
+ queryString += " and DAS.VNFC_TYPE = ?";
}
log.info(QUERY_STR + queryString);
}
}
- private String getStatus(String payload, String requestID) throws Exception {
+ private String getStatus(String payload, String requestId) throws Exception {
log.info("Starting getStatus DB Operation");
try {
String vnfcType = null;
argList.add(userID);
argList.add(vnfType);
- String queryString = "SELECT DAS.VNF_TYPE, DAS.VNFC_TYPE, DAS.STATUS, DAS.ACTION, DAT.ARTIFACT_STATUS "
- + "from DT_ACTION_STATUS DAS , DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR " +
- " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID "
- + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ? "
- + " and DAS.VNF_TYPE = ? ";
+ String queryString =
+ "SELECT DAS.VNF_TYPE, DAS.VNFC_TYPE, DAS.STATUS, DAS.ACTION, DAT.ARTIFACT_STATUS"
+ + " from DT_ACTION_STATUS DAS, DT_ARTIFACT_TRACKING DAT, DT_STATUS_RELATIONSHIP DSR"
+ + " where DAT.USER = DAS.USER and DSR.DT_ARTIFACT_TRACKING_ID = DAT.DT_ARTIFACT_TRACKING_ID"
+ + " and DSR.DT_ACTION_STATUS_ID = DAS.DT_ACTION_STATUS_ID and DAT.USER = ?"
+ + " and DAS.VNF_TYPE = ?";
if (vnfcType != null && !vnfcType.isEmpty()) {
argList.add(vnfcType);
- queryString = queryString + " and DAS.VNFC_TYPE = ? ";
+ queryString = queryString + " and DAS.VNFC_TYPE = ?";
}
log.info(QUERY_STR + queryString);
DesignResponse designResponse = new DesignResponse();
designResponse.setUserId(userID);
List<StatusInfo> statusInfoList = new ArrayList<>();
- ResultSet data = dbservice.getDBData(queryString, argList);
- while (data.next()) {
- StatusInfo statusInfo = new StatusInfo();
- statusInfo.setAction(data.getString("ACTION"));
- statusInfo.setAction_status(data.getString(STATUS));
- statusInfo.setArtifact_status(data.getString("ARTIFACT_STATUS"));
- statusInfo.setVnf_type(data.getString("VNF_TYPE"));
- statusInfo.setVnfc_type(data.getString("VNFC_TYPE"));
- statusInfoList.add(statusInfo);
- }
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ while (data.next()) {
+ StatusInfo statusInfo = new StatusInfo();
+ statusInfo.setAction(data.getString("ACTION"));
+ statusInfo.setAction_status(data.getString(STATUS));
+ statusInfo.setArtifact_status(data.getString("ARTIFACT_STATUS"));
+ statusInfo.setVnf_type(data.getString("VNF_TYPE"));
+ statusInfo.setVnfc_type(data.getString("VNFC_TYPE"));
+ statusInfoList.add(statusInfo);
+ }
- if (statusInfoList.isEmpty()) {
- throw new DBException(
- "OOPS !!!! No VNF information available for VNF-TYPE : " + vnfType + " for User : " + userID);
+ if (statusInfoList.isEmpty()) {
+ throw new DBException(
+ "OOPS!!!! No VNF information available for VNF-TYPE: " + vnfType + " for User: " + userID);
+ }
}
designResponse.setStatusInfoList(statusInfoList);
ObjectMapper mapper = new ObjectMapper();
throw e;
} catch (Exception e) {
log.error(DB_OPERATION_ERROR + e.getMessage());
- log.error("Exception : ", e);
+ log.error("Exception:", e);
throw e;
}
}
- private String getGuiReference(String payload, String requestID) {
+ private String getGuiReference(String payload, String requestId) {
// TODO Auto-generated method stub
return null;
}
- private String getArtifactReference(String payload, String requestID) {
+ private String getArtifactReference(String payload, String requestId) {
// TODO Auto-generated method stub
return null;
}
- private String getDesigns(String payload, String requestID) throws Exception {
+ private String getDesigns(String payload, String requestId) throws Exception {
String queryString;
log.info("Starting getDesigns DB Operation");
}
ArrayList<String> argList = new ArrayList<>();
argList.add(userID);
+ argList.add(userID);
+ queryString =
+ "SELECT DISTINCT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART, AR.ACTION, AR.ARTIFACT_NAME,"
+ + " AR.ARTIFACT_TYPE, DUP.PERMISSION, DAS.USER FROM "
+ + DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT, "
+ + DesignServiceConstants.DB_SDC_REFERENCE + " AR, " + DesignServiceConstants.DB_DT_USER_PERMISSIONS
+ + " DUP, " + DesignServiceConstants.DB_DT_ACTION_STATUS + " DAS "
+ + " WHERE AR.VNF_TYPE = DUP.VNF_TYPE AND DAS.VNF_TYPE = DUP.VNF_TYPE"
+ + " AND DAT.ASDC_REFERENCE_ID = AR.ASDC_REFERENCE_ID AND DUP.USER_ID = ? AND AR.VNF_TYPE IN"
+ + " (SELECT DUP.VNF_TYPE FROM DT_USER_PERMISSIONS DUP"
+ + " WHERE DUP.PERMISSION IN('owner','contributor') AND DUP.USER_ID = ? GROUP BY VNF_TYPE)";
if (filterKey != null) {
- queryString =
- "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART, AR.ACTION, AR.ARTIFACT_NAME, AR.ARTIFACT_TYPE from "
- +
- DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , "
- + DesignServiceConstants.DB_SDC_REFERENCE +
- " AR where DAT.ASDC_REFERENCE_ID= AR.ASDC_REFERENCE_ID and DAT.USER = ? and AR.ARTIFACT_NAME like '%"
- + filterKey + "%' GROUP BY AR.VNF_TYPE,AR.ARTIFACT_NAME";
- } else {
- queryString =
- "SELECT AR.VNF_TYPE, AR.VNFC_TYPE, DAT.PROTOCOL, DAT.IN_CART, AR.ACTION, AR.ARTIFACT_NAME, AR.ARTIFACT_TYPE from "
- +
- DesignServiceConstants.DB_DT_ARTIFACT_TRACKING + " DAT , "
- + DesignServiceConstants.DB_SDC_REFERENCE +
- " AR where DAT.ASDC_REFERENCE_ID= AR.ASDC_REFERENCE_ID and DAT.USER = ? GROUP BY AR.VNF_TYPE,AR.ARTIFACT_NAME";
+ queryString += " AND AR.ARTIFACT_NAME like '%" + filterKey + "%'";
}
+ queryString += " GROUP BY AR.VNF_TYPE, AR.ARTIFACT_NAME";
+
+ log.info("QUERY FOR getDesigns: " + queryString);
DesignResponse designResponse = new DesignResponse();
designResponse.setUserId(userID);
List<DesignInfo> designInfoList = new ArrayList<>();
- ResultSet data = dbservice.getDBData(queryString, argList);
- while (data.next()) {
- DesignInfo designInfo = new DesignInfo();
- designInfo.setInCart(data.getString("IN_CART"));
- designInfo.setProtocol(data.getString("PROTOCOL"));
- designInfo.setVnf_type(data.getString("VNF_TYPE"));
- designInfo.setVnfc_type(data.getString("VNFC_TYPE"));
- designInfo.setAction(data.getString("ACTION"));
- designInfo.setArtifact_type(data.getString("ARTIFACT_TYPE"));
- designInfo.setArtifact_name(data.getString("ARTIFACT_NAME"));
- designInfoList.add(designInfo);
- }
- if (designInfoList.isEmpty()) {
- throw new DBException(
- " Welcome to CDT, Looks like you dont have Design Yet... Lets create some....");
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+ while (data.next()) {
+ DesignInfo designInfo = new DesignInfo();
+ designInfo.setInCart(data.getString("IN_CART"));
+ designInfo.setProtocol(data.getString("PROTOCOL"));
+ designInfo.setVnf_type(data.getString("VNF_TYPE"));
+ designInfo.setVnfc_type(data.getString("VNFC_TYPE"));
+ designInfo.setAction(data.getString("ACTION"));
+ designInfo.setArtifact_type(data.getString("ARTIFACT_TYPE"));
+ designInfo.setArtifact_name(data.getString("ARTIFACT_NAME"));
+ designInfo.setPermission(data.getString("PERMISSION"));
+ designInfo.setCreatorUserId(data.getString("USER"));
+ designInfoList.add(designInfo);
+ }
+ if (designInfoList.isEmpty()) {
+ throw new DBException(
+ "Welcome to CDT, Looks like you don't have Design Yet... Let's create some....");
+ }
}
designResponse.setDesignInfoList(designInfoList);
ObjectMapper mapper = new ObjectMapper();
log.info(INFO_STR + jsonString);
return jsonString;
} catch (Exception e) {
- log.error("Error while Starting getDesgins DB operation : ", e);
+ log.error("Error while Starting getDesigns DB operation:", e);
throw e;
}
}
- public static class ArtifactHandlerFactory {
+ private String retrieveVnfPermissions(String payload, String requestId) throws Exception {
+ log.info("Starting retrieveVnfPermissions DB Operation");
+
+ try {
+ ObjectMapper objectMapper = new ObjectMapper();
+ JsonNode payloadObject = objectMapper.readTree(payload);
+ ArrayList<String> argList = new ArrayList<>();
+ String vnfType = payloadObject.get(VNF_TYPE).textValue();
+ argList.add(vnfType);
- public ArtifactHandlerClient ahi() throws Exception{
+ String queryString = "SELECT USER_ID, PERMISSION FROM DT_USER_PERMISSIONS WHERE VNF_TYPE = ?";
+ log.info(QUERY_STR + queryString);
+ List<UserPermissionInfo> userPermList = new ArrayList<>();
+ try (ResultSet data = dbservice.getDBData(queryString, argList)) {
+
+ int rowCount = 0;
+
+ while (data.next()) {
+ rowCount++;
+ UserPermissionInfo userPermInfo = new UserPermissionInfo();
+ userPermInfo.setUserID(data.getString(COLUMN_USER_ID));
+ userPermInfo.setPermission(data.getString(COLUMN_PERMISSION));
+ userPermList.add(userPermInfo);
+ }
+ log.info("Number of rows=" + rowCount + ", for vnf-type=" + vnfType);
+
+ if (userPermList.isEmpty()) {
+ throw new DBException("No user permissions information available for VNF-TYPE: " + vnfType);
+ }
+ }
+ DesignResponse designResponse = new DesignResponse();
+ designResponse.setUsers(userPermList);
+ designResponse.setVnfType(vnfType);
+ ObjectMapper mapper = new ObjectMapper();
+ String jsonString = mapper.writeValueAsString(designResponse);
+ log.info("End of retrieveVnfPermissions: " + INFO_STR + jsonString);
+ return jsonString;
+
+ } catch (Exception e) {
+ log.error("Error while Starting retrieveVnfPermissions DB operation:", e);
+ throw e;
+ }
+ }
+
+ public static class ArtifactHandlerFactory {
+ public ArtifactHandlerClient ahi() throws Exception {
return new ArtifactHandlerClient();
}
}
+
}
+
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
case DesignServiceConstants.UPLOADADMINARTIFACT:
errorString = resolveUploadArtifactErrorString(payloadObject);
break;
+ case DesignServiceConstants.RETRIEVEVNFPERMISSIONS:
+ errorString = resolveRetrieveVnfPermissionsErrorString(payloadObject);
+ break;
case SETPROTOCOLREFERENCE:
case SETINCART:
errorString = resolveErrorString(payloadObject);
case DesignServiceConstants.CHECKVNF:
errorString = resolveCheckVNFErrorString(payloadObject);
break;
+ case DesignServiceConstants.SAVEVNFPERMISSIONS:
+ errorString = resolveSaveUserPermissionErrorString(payloadObject);
+ break;
default:
throw new RequestValidationException(" Action " + action + " not found while processing request ");
}
checkForErrorString(errorString);
}
+ private static String resolveSaveUserPermissionErrorString(JsonNode payloadObject) {
+ if (nullOrEmpty(payloadObject, VNF_TYPE))
+ return VNF_TYPE;
+ return null;
+ }
+
private static String resolveCheckVNFErrorString(JsonNode payloadObject) {
- if (nullOrEmpty(payloadObject, VNF_TYPE))
+ if (nullOrEmpty(payloadObject, VNF_TYPE))
return VNF_TYPE;
return null;
}
return payload == null || payload.textValue().trim().isEmpty();
}
+ private static String resolveRetrieveVnfPermissionsErrorString(JsonNode payloadObject) {
+ if (nullOrEmpty(payloadObject, VNF_TYPE)) {
+ return VNF_TYPE;
+ }
+ return null;
+ }
}
-
-
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
-
-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.Response;
-import javax.ws.rs.core.Feature;
-import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.ws.rs.HttpMethod;
+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.Response;
+import javax.ws.rs.core.Feature;
import javax.ws.rs.core.MediaType;
-
+import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class ArtifactHandlerClient {
private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerClient.class);
- static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
+ public static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
private Properties props = new Properties();
public ArtifactHandlerClient() throws IOException {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
-
client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(getHostnameVerifier()).build();
String password = et.decrypt(props.getProperty("appc.upload.pass"));
if (HttpMethod.GET.equalsIgnoreCase(rpc)) {
clientResponse = webResource.request(responseDataType).get(Response.class);
} else if (HttpMethod.POST.equalsIgnoreCase(rpc)) {
- clientResponse = webResource.request(requestDataType).post(Entity.json(payload),Response.class);
+ clientResponse = webResource.request(requestDataType).post(Entity.json(payload), Response.class);
} else if (HttpMethod.PUT.equalsIgnoreCase(rpc)) {
- clientResponse = webResource.request(requestDataType).put(Entity.json(payload),Response.class);
+ clientResponse = webResource.request(requestDataType).put(Entity.json(payload), Response.class);
} else if (HttpMethod.DELETE.equalsIgnoreCase(rpc)) {
clientResponse = webResource.request().delete(Response.class);
}
} catch (Exception e) {
log.debug("failed in RESTCONT Action", e);
- throw new IOException("Error While Sending Rest Request" + e.getMessage(), e);
+ throw new IOException("Error While Sending Rest Request: " + e.getMessage(), e);
} finally {
// clean up.
if (client != null) {
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public static final String GETDESIGNS = "getDesigns";
public static final String GETAPPCTIMESTAMPUTC = "getAppcTimestampUTC";
- public static final String UPLOADARTIFACTS = "uploadArtifacts";
- public static final String VALIDATETEMPLATE = "validateTemplate";
- public static final String GETSTATUS = "getStatus";
- public static final String SETSTATUS = "setStatus";
+ public static final String UPLOADARTIFACTS = "uploadArtifacts";
+ public static final String VALIDATETEMPLATE = "validateTemplate";
+ public static final String GETSTATUS = "getStatus";
+ public static final String SETSTATUS = "setStatus";
public static final String GETGUIREFERENCE = "getGUIReference";
- public static final String GETARTIFACTREFERENCE = "getArtifactReference";
- public static final String GETAAIDATA = "getAAIData";
- public static final String GETINSTARDATA = "getInstarData";
- public static final String PUBLISHARTIFACTS = "publishdArtifacts";
- public static final String ADDINCART = "addInCart";
-
- public static final String SUCCESS = "success";
+ public static final String GETARTIFACTREFERENCE = "getArtifactReference";
+ public static final String GETAAIDATA = "getAAIData";
+ public static final String GETINSTARDATA = "getInstarData";
+ public static final String PUBLISHARTIFACTS = "publishdArtifacts";
+ public static final String ADDINCART = "addInCart";
+
+ public static final String SUCCESS = "success";
public static final String DESINGTIME = "DesignTime";
public static final String RUNTIME = "RunTime";
public static final String APPC_FLOW_CONTROLLER = "/appc-flow-controller.properties";
public static final String VNFC = "vnfc";
public static final String DOCUMENT_PARAMETERS = "document-parameters";
- public static final String SERVICE_UUID = "service-uuid";
- public static final String DISTRIBUTION_ID = "distribution-id";
+ public static final String SERVICE_UUID = "service-uuid";
+ public static final String DISTRIBUTION_ID = "distribution-id";
- public static final String SERVICE_NAME = "service-name";
- public static final String SERVICE_DESCRIPTION ="service-description";
- public static final String SERVICE_ARTIFACTS = "service-artifacts";
- public static final String RESOURCE_UUID ="resource-uuid";
+ public static final String SERVICE_NAME = "service-name";
+ public static final String SERVICE_DESCRIPTION = "service-description";
+ public static final String SERVICE_ARTIFACTS = "service-artifacts";
+ public static final String RESOURCE_UUID = "resource-uuid";
public static final String RESOURCE_INSTANCE_NAME = "resource-instance-name";
public static final String REOURCE_NAME = "resource-name";
- public static final String RESOURCE_VERSOIN ="resource-version";
- public static final String RESOURCE_TYPE= "resource-type";
- public static final String ARTIFACT_UUID ="artifact-uuid";
- public static final String ARTIFACT_NAME = "artifact-name";
-
- public static final String ARTIFACT_VERSOIN = "artifact-version";
+ public static final String RESOURCE_VERSOIN = "resource-version";
+ public static final String RESOURCE_TYPE = "resource-type";
+ public static final String ARTIFACT_UUID = "artifact-uuid";
+ public static final String ARTIFACT_NAME = "artifact-name";
+ public static final String DB_DT_ACTION_STATUS = "DT_ACTION_STATUS";
+ public static final String DB_DT_USER_PERMISSIONS = "DT_USER_PERMISSIONS";
+ public static final String ARTIFACT_VERSOIN = "artifact-version";
public static final String ARTIFACT_DESRIPTION = "artifact-description";
public static final String ARTIFACT_CONTENTS = "artifact-contents";
public static final String REQUEST_INFORMATION = "request-information";
public static final String INSTAR_V4_MASK = "v4Subnet";
public static final String INSTAR_V6_MASK = "v6Subnet";
public static final String CHECKVNF = "checkVNF";
+ public static final String RETRIEVEVNFPERMISSIONS = "retrieveVnfPermissions";
+ public static final String SAVEVNFPERMISSIONS = "saveVnfPermissions";
+ public static final String CREATORUSERID = "creator-userID";
+ public static final String PERMISSION = "permission";
+
private DesignServiceConstants() {
}
public static String getEnvironmentVariable(String env) {
return System.getenv(env);
}
-}
\ No newline at end of file
+
+}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class XResponseProcessor {
private final EELFLogger log = EELFManager.getInstance().getLogger(XInterfaceService.class);
- private static final String EXCEPTION_WHILE_RECEIVING_DATA = "Exception occured while receiving data";
+ private static final String EXCEPTION_WHILE_RECEIVING_DATA = "Exception occurred while receiving data";
Dme2Client dme2Client;
public static XResponseProcessor getInstance() {
// check the payload whether its having ipaddr along with subnet
ipAddress = payloadObject.get(DesignServiceConstants.INSTAR_V4_ADDRESS) != null
? payloadObject.get(DesignServiceConstants.INSTAR_V4_ADDRESS).textValue()
- : (payloadObject.get(DesignServiceConstants.INSTAR_V6_ADDRESS) != null)
- ? payloadObject.get(DesignServiceConstants.INSTAR_V6_ADDRESS).textValue()
- .toUpperCase()
- : null;
-
- mask = payloadObject.get(DesignServiceConstants.INSTAR_V4_MASK) != null
- ? payloadObject.get(DesignServiceConstants.INSTAR_V4_MASK).textValue()
- : (payloadObject.get(DesignServiceConstants.INSTAR_V6_MASK) != null)
- ? payloadObject.get(DesignServiceConstants.INSTAR_V6_MASK).textValue().toUpperCase()
- : null;
-
- // TODO -short format
-
- /*
- * if (mask != null) { queryParam = ipAddress + "," +mask ;
- * log.info("Calling Instar with IpAddress "+ ipAddress + " Mask value: "+ mask ); } else {
- * queryParam = "ipAddress "+ipAddress ; log.info("Calling Instar with IpAddress "+
- * ipAddress); }
- */
-
- payload = new HashMap<String, String>();
- payload.put("ipAddress", ipAddress);
- payload.put("mask", mask);
- log.info("Calling Instar with IpAddress " + ipAddress + " Mask value: " + mask);
- dme2Client = new Dme2Client("getVnfbyIpadress", "payload", payload);
-
- instarResponse = dme2Client.send();
-
- log.debug("Resposne from Instar = " + instarResponse);
- if (instarResponse == null || instarResponse.length() < 0)
- throw new Exception("No Data received from Instar for this action " + action);
+ : (payloadObject.get(DesignServiceConstants.INSTAR_V6_ADDRESS) != null)
+ ? payloadObject.get(DesignServiceConstants.INSTAR_V6_ADDRESS).textValue().toUpperCase()
+ : null;
+
+ mask = payloadObject.get(DesignServiceConstants.INSTAR_V4_MASK) != null
+ ? payloadObject.get(DesignServiceConstants.INSTAR_V4_MASK).textValue()
+
+ : (payloadObject.get(DesignServiceConstants.INSTAR_V6_MASK) != null)
+ ? payloadObject.get(DesignServiceConstants.INSTAR_V6_MASK).textValue().toUpperCase()
+ : null;
+
+ // TODO -short format
+
+ /* if (mask != null) {
+ * queryParam = ipAddress + "," + mask;
+ * log.info("Calling Instar with IpAddress " + ipAddress + " Mask value: " + mask);
+ * } else {
+ * queryParam = "ipAddress " + ipAddress;
+ * log.info("Calling Instar with IpAddress " + ipAddress);
+ * }
+ */
+
+ payload = new HashMap<String, String>();
+ payload.put("ipAddress", ipAddress);
+ payload.put("mask", mask);
+ log.info("Calling Instar with IpAddress " + ipAddress + " Mask value: " + mask);
+ dme2Client = new Dme2Client("getVnfbyIpadress", "payload", payload);
+
+ instarResponse = dme2Client.send();
+
+ log.debug("Response from Instar = " + instarResponse);
+ if (instarResponse == null || instarResponse.length() < 0)
+ throw new Exception("No Data received from Instar for this action " + action);
} catch (Exception e) {
log.error(EXCEPTION_WHILE_RECEIVING_DATA, e);
throw e;
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
public class TestDbResponse {
@Test
- public void testDbResponse() throws Exception{
+ public void testDbResponse() throws Exception {
DbResponseProcessor dbResponse = new DbResponseProcessor();
- dbResponse.parseResponse("Test", "getDesigns");
- dbResponse.parseResponse("Test", "addInCart");
- dbResponse.parseResponse("Test", "getArtifactReference");
- dbResponse.parseResponse("Test", "getArtifact");
- dbResponse.parseResponse("Test", "getGUIReference");
- dbResponse.parseResponse("Test", "getStatus");
- dbResponse.parseResponse("Test", "uploadArtifact");
- dbResponse.parseResponse("Test", "setProtocolReference");
- dbResponse.parseResponse("Test", "setInCart");
- dbResponse.parseResponse("Test", "getStatus");
- dbResponse.parseResponse("Test", "getAppcTimestampUTC");
-
+ dbResponse.parseResponse("Test", "getDesigns");
+ dbResponse.parseResponse("Test", "addInCart");
+ dbResponse.parseResponse("Test", "getArtifactReference");
+ dbResponse.parseResponse("Test", "getArtifact");
+ dbResponse.parseResponse("Test", "getGUIReference");
+ dbResponse.parseResponse("Test", "getStatus");
+ dbResponse.parseResponse("Test", "uploadArtifact");
+ dbResponse.parseResponse("Test", "setProtocolReference");
+ dbResponse.parseResponse("Test", "setInCart");
+ dbResponse.parseResponse("Test", "getStatus");
+ dbResponse.parseResponse("Test", "getAppcTimestampUTC");
+ dbResponse.parseResponse("Test", "retrieveVnfPermissions");
+ dbResponse.parseResponse("Test", "saveVnfPermissions");
}
}
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "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=========================================================
*/
import java.util.ArrayList;
import java.util.List;
+import org.junit.Assert;
import org.junit.Test;
import org.onap.appc.design.data.ArtifactInfo;
import org.onap.appc.design.data.DesignInfo;
import org.onap.appc.design.data.DesignRequest;
import org.onap.appc.design.data.DesignResponse;
import org.onap.appc.design.data.StatusInfo;
+import org.onap.appc.design.data.UserPermissionInfo;
public class TestDesigndata {
@Test
public void testSetUserID() {
- dr.setUserId("00000");
- dr.getUserId();
+ String userId = "0000";
+ dr.setUserId(userId);
+ Assert.assertEquals("Unexpected getUserId value", userId, dr.getUserId());
}
@Test
public void testSetDesignInfoList() {
DesignInfo di = new DesignInfo();
List<DesignInfo> li = new ArrayList<DesignInfo>();
- di.setAction("TestAction");
- di.setArtifact_name("TestName");
- di.setArtifact_type("TestType");
- di.setInCart("TestCart");
- di.setProtocol("TestProtocol");
- di.setVnf_type("TestVNF");
- di.setVnfc_type("TestVNFC");
+ String action = "TestAction";
+ di.setAction(action);
+ Assert.assertEquals("Unexpected getAction value", action, di.getAction());
+ String artifact_name = "TestName";
+ di.setArtifact_name(artifact_name);
+ Assert.assertEquals("Unexpected getArtifact_name value", artifact_name, di.getArtifact_name());
+ String artifact_type = "TestType";
+ di.setArtifact_type(artifact_type);
+ Assert.assertEquals("Unexpected getArtifact_type value", artifact_type, di.getArtifact_type());
+ String inCart = "TestCart";
+ di.setInCart(inCart);
+ Assert.assertEquals("Unexpected getInCart value", inCart, di.getInCart());
+ String protocol = "TestProtocol";
+ di.setProtocol(protocol);
+ Assert.assertEquals("Unexpected getProtocol value", protocol, di.getProtocol());
+ String vnf_type = "TestVNF";
+ di.setVnf_type(vnf_type);
+ Assert.assertEquals("Unexpected getVnf_type value", vnf_type, di.getVnf_type());
+ String vnfc_type = "TestVNFC";
+ di.setVnfc_type(vnfc_type);
+ Assert.assertEquals("Unexpected getVnfc_type value", vnfc_type, di.getVnfc_type());
li.add(di);
dr.setDesignInfoList(li);
+ Assert.assertEquals("Unexpected getDesignInfoList value", li, dr.getDesignInfoList());
}
@Test
public void testSetArtifactInfo() {
ArtifactInfo ai = new ArtifactInfo();
List<ArtifactInfo> li = new ArrayList<ArtifactInfo>();
- ai.setArtifact_content("TestContent");
+ String artifact_content = "TestContent";
+ ai.setArtifact_content(artifact_content);
+ Assert.assertEquals("Unexpected getArtifact_content value", artifact_content, ai.getArtifact_content());
li.add(ai);
dr.setArtifactInfo(li);
+ Assert.assertEquals("Unexpected getArtifactInfo value", li, dr.getArtifactInfo());
}
@Test
public void testStatusInfo() {
StatusInfo si = new StatusInfo();
List<StatusInfo> li = new ArrayList<StatusInfo>();
- si.setAction("TestAction");
- si.setAction_status("TestActionStatus");
- si.setArtifact_status("TestArtifactStatus");
- si.setVnf_type("TestVNF");
- si.setVnfc_type("TestVNFC");
+ String action = "TestAction";
+ si.setAction(action);
+ Assert.assertEquals("Unexpected getAction value", action, si.getAction());
+ String action_status = "TestActionStatus";
+ si.setAction_status(action_status);
+ Assert.assertEquals("Unexpected getAction_status value", action_status, si.getAction_status());
+ String artifact_status = "TestArtifactStatus";
+ si.setArtifact_status(artifact_status);
+ Assert.assertEquals("Unexpected getArtifact_status value", artifact_status, si.getArtifact_status());
+ String vnf_type = "TestVNF";
+ si.setVnf_type(vnf_type);
+ Assert.assertEquals("Unexpected getVnf_type value", vnf_type, si.getVnf_type());
+ String vnfc_type = "TestVNFC";
+ si.setVnfc_type(vnfc_type);
+ Assert.assertEquals("Unexpected getVnfc_type value", vnfc_type, si.getVnfc_type());
li.add(si);
dr.setStatusInfoList(li);
+ Assert.assertEquals("Unexpected getStatusInfoList value", li, dr.getStatusInfoList());
}
@Test
public void testDesignRequest() {
DesignRequest dreq = new DesignRequest();
- dreq.setAction("TestAction");
- dreq.setArtifact_contents("TestContent");
- dreq.setArtifact_name("TestName");
- dreq.setProtocol("TestProtocol");
- dreq.setUserId("0000");
- dreq.setVnf_type("testvnf");
- dreq.setVnfc_type("testvnfc");
- dreq.getAction();
- dreq.getArtifact_contents();
- dreq.getArtifact_name();
- dreq.getProtocol();
- dreq.getUserId();
- dreq.getVnf_type();
- dreq.getVnfc_type();
- dreq.toString();
+ String action = "TestAction";
+ dreq.setAction(action);
+ Assert.assertEquals("Unexpected getAction value", action, dreq.getAction());
+ String artifact_contents = "TestContent";
+ dreq.setArtifact_contents(artifact_contents);
+ Assert.assertEquals("Unexpected getArtifact_contents value", artifact_contents, dreq.getArtifact_contents());
+ String artifact_name = "TestName";
+ dreq.setArtifact_name(artifact_name);
+ Assert.assertEquals("Unexpected getArtifact_name value", artifact_name, dreq.getArtifact_name());
+ String protocol = "TestProtocol";
+ dreq.setProtocol(protocol);
+ Assert.assertEquals("Unexpected getProtocol value", protocol, dreq.getProtocol());
+ String userId = "0000";
+ dreq.setUserId(userId);
+ Assert.assertEquals("Unexpected getUserId value", userId, dreq.getUserId());
+ String vnf_type = "testvnf";
+ dreq.setVnf_type(vnf_type);
+ Assert.assertEquals("Unexpected getVnf_type value", vnf_type, dreq.getVnf_type());
+ String vnfc_type = "testvnfc";
+ dreq.setVnfc_type(vnfc_type);
+ Assert.assertEquals("Unexpected getVnfc_type value", vnfc_type, dreq.getVnfc_type());
+ String expecting =
+ "DesignRequest [userId=" + userId + ", vnf_type=" + vnf_type + ", vnfc_type=" + vnfc_type + ", protocol="
+ + protocol + ", action=" + action + ", artifact_name=" + artifact_name + ", artifact_contents="
+ + artifact_contents + "]";
+ Assert.assertEquals("Unexpected toString value", expecting, dreq.toString());
}
+
+ @Test
+ public void testUserPermissionInfo() {
+ UserPermissionInfo upi = new UserPermissionInfo();
+ List<UserPermissionInfo> li = new ArrayList<UserPermissionInfo>();
+ String userId = "uu1234";
+ upi.setUserID(userId);
+ Assert.assertEquals("Unexpected getUserId value", userId, upi.getUserID());
+ String permission = "owner";
+ upi.setPermission(permission);
+ Assert.assertEquals("Unexpected getPermission value", permission, upi.getPermission());
+ li.add(upi);
+ dr.setUsers(li);
+ Assert.assertEquals("Unexpected getUsers value", li, dr.getUsers());
+ }
+
}
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
- *
* ============LICENSE_END=========================================================
*/
package org.onap.appc.sdc.listener;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URL;
-import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
-
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
-
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.onap.appc.exceptions.APPCException;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
public class ProviderOperations {
-
private static final EELFLogger LOG = EELFManager.getInstance().getLogger(ProviderOperations.class);
-
private static String basic_auth;
private static URL defaultUrl;
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
- // Set Auth
- if (basic_auth != null) {
+ // Set Auth if Provider URL is specified and basic auth has been configured
+ if (basic_auth != null && defaultUrl != null && url.equals(defaultUrl)) {
post.setHeader("Authorization", "Basic " + basic_auth);
+ LOG.debug("ASDCListener ProviderOperations: Using basic authentication for request to url " + url);
+ } else {
+ LOG.debug("ASDCListener ProviderOperations: Not Using basic authentication for request to url " + url);
}
if (adtl_headers != null) {
}
/**
- * Sets the basic authentication header for the given user and password. If either entry is null then set basic auth
- * to null
+ * Sets the basic authentication header for the given user and password. If either entry is null
+ * then set basic auth to null
*
- * @param user
- * The user with optional domain name (for AAF)
- * @param password
- * The password for the user
+ * @param user The user with optional domain name (for AAF)
+ * @param password The password for the user
* @return The new value of the basic auth string that will be used in the request headers
*/
public static String setAuthentication(String user, String password) {
if (user != null && password != null) {
+ LOG.debug("SDCListener ProviderOperations:setAuthentication user is: " + user
+ + " Encrypted password: XXXX");
String authStr = user + ":" + password;
basic_auth = new String(Base64.encodeBase64(authStr.getBytes()));
} else {
/**
* Sets the default Provider URL to the provided URL. If the entry is null then sets to null.
*
- * @param URL The URL
+ * @param URL url The URL
*/
- public static void setDefaultUrl(URL URL) {
- if (URL != null) {
- defaultUrl = URL;
- } else {
- defaultUrl = null;
- }
+ public static void setDefaultUrl(URL url) {
+ defaultUrl = url;
}
+
@SuppressWarnings("deprecation")
private static HttpClient getHttpClient(URL url) throws APPCException {
HttpClient client;
client = new DefaultHttpClient();
} else {
throw new APPCException(
- "The provider.topology.url property is invalid. The url did not start with http[s]");
+ "The provider.topology.url property is invalid. The url did not start with http[s]");
}
return client;
}
public static class MySSLSocketFactory extends SSLSocketFactory {
private SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
- public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
- KeyStoreException, UnrecoverableKeyException {
+ public MySSLSocketFactory(KeyStore truststore)
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
@Override
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
+ public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
+ public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
}
};
- sslContext.init(null, new TrustManager[] {
- tm
- }, null);
+ sslContext.init(null, new TrustManager[] {tm}, null);
}
@Override
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
- throws IOException, UnknownHostException {
+ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
config = new SdcConfig(props);
ukey = props.getProperty("appc.sdc.provider.user");
uval = props.getProperty("appc.sdc.provider.pass");
- logger.debug(String.format("[%d] created SDC config provider URL [%s]", timeStamp, config.getStoreOpURI().toString()));
-
+ logger.debug(String.format("[%d] created SDC config provider URL [%s]",
+ timeStamp, config.getStoreOpURI().toString()));
client = DistributionClientFactory.createDistributionClient();
logger.debug(String.format("[%d] created SDC client", timeStamp));
URL url = new URL(String.format("http%s://%s/sdc2/rest/v1/consumers",
host.contains("443") ? "s" : "", host));
- logger.info(String.format("Attempting to register user %s on %s with salted pass of %s",
- config.getUser(), url, saltedPass[1]));
+ /*logger.info(String.format("Attempting to register user %s on %s with salted pass of %s",
+ config.getUser(), url, saltedPass[1]));*/
+ logger.info(String.format("Attempting to register user %s on %s with salted pass",
+ config.getUser(), url));
ProviderOperations providerOperations = new ProviderOperations();
ProviderOperations.setDefaultUrl(config.getStoreOpURI().toURL());
ProviderOperations.setAuthentication(ukey, uval);
ProviderResponse result = providerOperations.post(url, json, headers);
+/*
+ result = ProviderOperations.post(config.getStoreOpURI().toURL(), "{\"input\": {\"document-parameters\":{\"service-uuid\":\"c2d96f2c-58b2-45c1-b952-56d4982b48f4\",\"artifact-name\":\"reference_AllAction_vDBE_Svc_VoLTE_DBE_vDBE_U_vDBE_VF_VoLTE_DBE0_0.0.1V.json\",\"artifact-version\":\"1\",\"resource-name\":\"vDBE_VF_VoLTE_DBE\",\"artifact-description\":\"Reference file of VoLTE\",\"distribution-id\":\"6bdabf7d-2270-4da7-ba50-9b57e4a5e95b\",\"service-name\":\"vDBE_Svc_VoLTE_DBE_vDBE_U\",\"resource-instance-name\":\"vDBE_VF_VoLTE_DBE 0\",\"artifact-uuid\":\"93e9a91f-4b7f-4234-ae43-d7b3ba7bfb84\",\"resource-version\":\"7.0\",\"artifact-type\":\"APPC_CONFIG\",\"service-artifacts\":\"[]\",\"service-description\":\"ASDC vDBE Service for the VoLTE-vDBE project\",\"resource-uuid\":\"93bf7180-eba8-4b49-b81d-78fcd515ec89\",\"resource-type\":\"VF\",\"artifact-contents\":\"{\n\t\\\"reference_data\\\": [\n\t\t{\n\t\t\t\\\"action\\\": \\\"Configure\\\",\n\t\t\t\\\"action-level\\\": \\\"vnf\\\",\n\t\t\t\\\"scope\\\": {\n\t\t\t\t\\\"vnf-type\\\": \\\"vDBE_Svc_VoLTE_DBE_vDBE_U/vDBE_VF_VoLTE_DBE 0\\\",\n\t\t\t\t\\\"vnfc-type\\\": \\\"\\\"\n\t\t\t},\n\t\t\t\\\"template\\\": \\\"Y\\\",\n\t\t\t\\\"vm\\\": [\n\t\t\t\t{\n\t\t\t\t\t\\\"vm-instance\\\": 1,\n\t\t\t\t\t\\\"vnfc\\\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\\\"vnfc-instance\\\": \\\"1\\\",\n\t\t\t\t\t\t\t\\\"vnfc-function-code\\\": \\\"dbu\\\",\n\t\t\t\t\t\t\t\\\"ipaddress-v4-oam-vip\\\": \\\"Y\\\",\n\t\t\t\t\t\t\t\\\"group-notation-type\\\": \\\"first-vnfc-name\\\",\n\t\t\t\t\t\t\t\\\"group-notation-value\\\": \\\"pair\\\",\n\t\t\t\t\t\t\t\\\"vnfc-type\\\": \\\"vDBE-V - DBUX\\\"\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\\\"vm-instance\\\": 2,\n\t\t\t\t\t\\\"vnfc\\\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\\\"vnfc-instance\\\": \\\"1\\\",\n\t\t\t\t\t\t\t\\\"vnfc-function-code\\\": \\\"dbu\\\",\n\t\t\t\t\t\t\t\\\"ipaddress-v4-oam-vip\\\": \\\"Y\\\",\n\t\t\t\t\t\t\t\\\"group-notation-type\\\": \\\"first-vnfc-name\\\",\n\t\t\t\t\t\t\t\\\"group-notation-value\\\": \\\"pair\\\",\n\t\t\t\t\t\t\t\\\"vnfc-type\\\": \\\"vDBE-V - DBUX\\\"\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t],\n\t\t\t\\\"device-protocol\\\": \\\"NETCONF-XML\\\",\n\t\t\t\\\"user-name\\\": \\\"root\\\",\n\t\t\t\\\"port-number\\\": \\\"830\\\",\n\t\t\t\\\"artifact-list\\\": [\n\t\t\t\t{\n\t\t\t\t\t\\\"artifact-name\\\": \\\"template_Configure_vDBE_Svc_VoLTE_DBE_vDBE_U_vDBE_VF_VoLTE_DBE0_0.0.1V.xml\\\",\n\t\t\t\t\t\\\"artifact-type\\\": \\\"config_template\\\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\\\"artifact-name\\\": \\\"pd_Configure_vDBE_Svc_VoLTE_DBE_vDBE_U_vDBE_VF_VoLTE_DBE0_0.0.1V.yaml\\\",\n\t\t\t\t\t\\\"artifact-type\\\": \\\"parameter_definitions\\\"\n\t\t\t\t}\n\t\t\t],\n\t\t\t\\\"scopeType\\\": \\\"vnf-type\\\"\n\t\t},\n\t\t{\n\t\t\t\\\"action\\\": \\\"AllAction\\\",\n\t\t\t\\\"action-level\\\": \\\"vnf\\\",\n\t\t\t\\\"scope\\\": {\n\t\t\t\t\\\"vnf-type\\\": \\\"vDBE_Svc_VoLTE_DBE_vDBE_U/vDBE_VF_VoLTE_DBE 0\\\",\n\t\t\t\t\\\"vnfc-type\\\": \\\"\\\"\n\t\t\t},\n\t\t\t\\\"artifact-list\\\": [\n\t\t\t\t{\n\t\t\t\t\t\\\"artifact-name\\\": \\\"reference_AllAction_vDBE_Svc_VoLTE_DBE_vDBE_U_vDBE_VF_VoLTE_DBE0_0.0.1V.json\\\",\n\t\t\t\t\t\\\"artifact-type\\\": \\\"reference_template\\\"\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t]\n}\"}, \"request-information\":{\"request-action\":\"StoreSdcDocumentRequest\",\"source\":\"SDC\",\"request-id\":\"c2d96f2c-58b2-45c1-b952-56d4982b48f4\"}}}", null);
+ logger.info(String.format("Result Status 3 = %d", result.getStatus()));
+*/
return result.getStatus() == 200;
+
} catch (Exception e) {
logger.error(
"Error performing initial registration with SDC server. User may not be able to connect",
* ============LICENSE_START=======================================================
* ONAP : APPC
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Copyright (C) 2017 Amdocs
* =============================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import java.util.stream.Collectors;
import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
@RunWith(PowerMockRunner.class)
@PrepareForTest({IDistributionClient.class,
IDistributionClient client = PowerMockito.mock(IDistributionClient.class);
EventSender eventSender = PowerMockito.mock(EventSender.class);
sdcCallback = new SdcCallback(null, client);
- resourceContent=readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(),"");
- artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(client, eventSender, getNotificationData(), getResources().get(0)
- , getServiceArtifacts().get(0), null));
+ resourceContent =
+ readInput("/output/resource-ResourceAppc-template.yml").replaceAll(System.lineSeparator(), "");
+ artifactProcessor = Mockito.spy(new ToscaCsarArtifactProcessor(
+ client, eventSender, getNotificationData(), getResources().get(0), getServiceArtifacts().get(0), null));
storageService = PowerMockito.mock(ArtifactStorageService.class);
- Whitebox.setInternalState(artifactProcessor,"artifactStorageService", storageService);
- DependencyModelGenerator dependencyModelGeneratorMock=PowerMockito.mock(DependencyModelGenerator.class);
- PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(Matchers.anyString(),Matchers.anyString()))
+ Whitebox.setInternalState(artifactProcessor, "artifactStorageService", storageService);
+ DependencyModelGenerator dependencyModelGeneratorMock = PowerMockito.mock(DependencyModelGenerator.class);
+ PowerMockito.when(dependencyModelGeneratorMock.getDependencyModel(anyString(), anyString()))
.thenReturn("Dependency_model");
- Whitebox.setInternalState(artifactProcessor,"dependencyModelGenerator",dependencyModelGeneratorMock);
+ Whitebox.setInternalState(artifactProcessor, "dependencyModelGenerator", dependencyModelGeneratorMock);
PowerMockito.doCallRealMethod().when(artifactProcessor).processArtifact(anyObject());
PowerMockito.doCallRealMethod().when(artifactProcessor).run();
//PowerMockito.mockStatic(ArtifactProcessorFactory.class);
- ArtifactProcessorFactory artifactProcessorFactory=PowerMockito.mock(ArtifactProcessorFactory.class);
- PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(anyObject(), anyObject(),
- anyObject(), anyObject(),
- anyObject(), anyObject())).thenReturn(artifactProcessor);
+ ArtifactProcessorFactory artifactProcessorFactory = PowerMockito.mock(ArtifactProcessorFactory.class);
+ PowerMockito.when(artifactProcessorFactory.getArtifactProcessor(
+ /* (IDistributionClient) */ anyObject(), /* (EventSender) */ anyObject(),
+ /* (INotificationData) */ anyObject(), /* (IResourceInstance) */ anyObject(),
+ /* (IArtifactInfo) */ anyObject(), /* (URI) */ anyObject()))
+ .thenReturn(artifactProcessor);
- Whitebox.setInternalState(sdcCallback,"eventSender", eventSender);
- PowerMockito.doReturn(readDownloadResult()).when(client).download(anyObject());
- PowerMockito.doReturn(null).when(client).sendDownloadStatus(anyObject());
+ Whitebox.setInternalState(sdcCallback, "eventSender", eventSender);
+ PowerMockito.doReturn(readDownloadResult()).when(client).download(/* (IArtifactInfo) */ anyObject());
+ PowerMockito.doReturn(null).when(client).sendDownloadStatus(/* (IDistributionStatusMessage) */ anyObject());
- PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(Matchers.anyString(),
- Matchers.anyString(),Matchers.anyString());
+ PowerMockito.doReturn(null).when(storageService).retrieveSDCArtifact(anyString(), anyString(), anyString());
PowerMockito.doAnswer(invocationOnMock -> {
System.out.print(invocationOnMock.getArguments()[0].toString());
return null;
- }).when(storageService).storeSDCArtifact(anyObject());
+ }).when(storageService).storeSDCArtifact(/* (SDCArtifact) */ anyObject());
}
private IDistributionClientDownloadResult readDownloadResult() throws IOException, URISyntaxException {
- DistributionClientDownloadResultImpl downloadResult = new DistributionClientDownloadResultImpl
- (DistributionActionResultEnum.SUCCESS,"Download success");
+ DistributionClientDownloadResultImpl downloadResult =
+ new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, "Download success");
File file = new File(this.getClass().getResource("/csar/service-ServiceAppc-csar.csar").toURI());
byte[] bFile = new byte[(int) file.length()];
- FileInputStream fileInputStream = new FileInputStream(file);
- fileInputStream.read(bFile);
- fileInputStream.close();
+ try (FileInputStream fileInputStream = new FileInputStream(file)) {
+ fileInputStream.read(bFile);
+ } catch (Exception e){
+ e.printStackTrace();
+ }
downloadResult.setArtifactPayload(bFile);
return downloadResult;
@Test
- public void testSDCListener() throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
+ public void testSDCListener()
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
INotificationData notificationData = getNotificationData();
sdcCallback.activateCallback(notificationData);
pause();
@Test
public void testArtifacts() throws Exception {
PowerMockito.doAnswer(invocationOnMock -> {
- SDCArtifact artifact =(SDCArtifact)invocationOnMock.getArguments()[0];
- SDCReference reference=(SDCReference)invocationOnMock.getArguments()[1];
- Assert.assertEquals("abcd-efgh-ijkl",artifact.getArtifactUUID());
- Assert.assertEquals("Resource-APPC",reference.getVnfType());
- Assert.assertEquals(resourceContent.trim(),artifact.getArtifactContent().replaceAll(System.lineSeparator(),""));
+ SDCArtifact artifact = (SDCArtifact) invocationOnMock.getArguments()[0];
+ SDCReference reference = (SDCReference) invocationOnMock.getArguments()[1];
+ Assert.assertEquals("abcd-efgh-ijkl", artifact.getArtifactUUID());
+ Assert.assertEquals("Resource-APPC", reference.getVnfType());
+ Assert.assertEquals(resourceContent.trim(),
+ artifact.getArtifactContent().replaceAll(System.lineSeparator(), ""));
return null;
}).doAnswer(invocation -> {
- SDCArtifact artifact =(SDCArtifact)invocation.getArguments()[0];
- SDCReference reference=(SDCReference)invocation.getArguments()[1];
- Assert.assertEquals("Resource-APPC",reference.getVnfType());
- Assert.assertEquals("tosca_dependency_model",reference.getFileCategory());
- Assert.assertEquals("Dependency_model",artifact.getArtifactContent());
- Assert.assertEquals("Resource-APPC",artifact.getResourceName());
+ SDCArtifact artifact = (SDCArtifact) invocation.getArguments()[0];
+ SDCReference reference = (SDCReference) invocation.getArguments()[1];
+ Assert.assertEquals("Resource-APPC", reference.getVnfType());
+ Assert.assertEquals("tosca_dependency_model", reference.getFileCategory());
+ Assert.assertEquals("Dependency_model", artifact.getArtifactContent());
+ Assert.assertEquals("Resource-APPC", artifact.getResourceName());
return null;
- }).when(storageService).storeSDCArtifactWithReference(anyObject(),anyObject());
+ }).when(storageService).storeSDCArtifactWithReference(anyObject(), anyObject());
artifactProcessor.processArtifact(readDownloadResult());
}
private String readInput(String inputFile) throws URISyntaxException {
File file = new File(this.getClass().getResource(inputFile).toURI());
byte[] bFile = new byte[(int) file.length()];
- try(FileInputStream fileInputStream = new FileInputStream(file)){
+ try (FileInputStream fileInputStream = new FileInputStream(file)) {
fileInputStream.read(bFile);
} catch (Exception e){
e.printStackTrace();
return new String(bFile);
}
- private INotificationData getNotificationData() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
+ private INotificationData getNotificationData()
+ throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
- INotificationData notificationData = (INotificationData)getObject("org.onap.sdc.impl.NotificationDataImpl");
+ INotificationData notificationData =
+ (INotificationData) getObject("org.onap.sdc.impl.NotificationDataImpl");
List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
return notificationData;
}
- private List<IResourceInstance> getResources() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
+ private List<IResourceInstance> getResources()
+ throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
List<IResourceInstance> resources = new ArrayList<>();
- IResourceInstance resource = (IResourceInstance)getObject("org.onap.sdc.impl.JsonContainerResourceInstance");
+ IResourceInstance resource =
+ (IResourceInstance) getObject("org.onap.sdc.impl.JsonContainerResourceInstance");
List<IArtifactInfo> serviceArtifacts = getServiceArtifacts();
- invokeMethod(resource,"setArtifacts",serviceArtifacts);
- invokeMethod(resource,"setResourceName","Vnf");
- invokeMethod(resource,"setResourceVersion","1.0");
+ invokeMethod(resource, "setArtifacts", serviceArtifacts);
+ invokeMethod(resource, "setResourceName", "Vnf");
+ invokeMethod(resource, "setResourceVersion", "1.0");
resources.add(resource);
return resources;
}
- private void invokeMethod(Object object, String methodName,Object... arguments) throws IllegalAccessException, InvocationTargetException {
+ private void invokeMethod(Object object, String methodName, Object... arguments)
+ throws IllegalAccessException, InvocationTargetException {
Method[] methods = object.getClass().getDeclaredMethods();
- for(Method method:methods){
+ for(Method method : methods) {
if(methodName.equalsIgnoreCase(method.getName())){
method.setAccessible(true);
- method.invoke(object,arguments);
+ method.invoke(object, arguments);
}
}
}
- private Object getObject(String fqcn) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
+ private Object getObject(String fqcn)
+ throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
Constructor constructor = Arrays.asList(Class.forName(fqcn).getDeclaredConstructors())
.stream()
- .filter(constructor1 -> constructor1.getParameterCount()==0)
+ .filter(constructor1 -> constructor1.getParameterCount() == 0)
.collect(Collectors.toList())
.get(0);
constructor.setAccessible(true);
return constructor.newInstance();
}
- private List<IArtifactInfo> getServiceArtifacts() throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
+ private List<IArtifactInfo> getServiceArtifacts()
+ throws ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException {
List<IArtifactInfo> serviceArtifacts = new ArrayList<>();
- IArtifactInfo artifactInfo = (IArtifactInfo)getObject("org.onap.sdc.impl.ArtifactInfoImpl");
- invokeMethod(artifactInfo,"setArtifactType","TOSCA_CSAR");
- invokeMethod(artifactInfo,"setArtifactUUID","abcd-efgh-ijkl");
+ IArtifactInfo artifactInfo = (IArtifactInfo) getObject("org.onap.sdc.impl.ArtifactInfoImpl");
+ invokeMethod(artifactInfo, "setArtifactType", "TOSCA_CSAR");
+ invokeMethod(artifactInfo, "setArtifactUUID", "abcd-efgh-ijkl");
serviceArtifacts.add(artifactInfo);
return serviceArtifacts;
}