Merge "asdc controller treat distributionid as requestid"
authorSteve Smokowski <ss835w@att.com>
Fri, 16 Aug 2019 13:05:51 +0000 (13:05 +0000)
committerGerrit Code Review <gerrit@onap.org>
Fri, 16 Aug 2019 13:05:51 +0000 (13:05 +0000)
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java
adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java [deleted file]
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExecuteBuildingBlockRainyDay.java
bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/servicedecomposition/tasks/ExtractPojosForBB.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java
mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/CamundaRequestHandlerTest.java
mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsUnitTest.java

index c0e065c..153de2f 100644 (file)
@@ -1477,13 +1477,19 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             }
 
             if (subnet.getAllocationPools() != null) {
-                curR = curR + "      allocation_pools:\n";
+                StringBuilder tempBuf = new StringBuilder();
+                tempBuf.append(curR);
+                tempBuf.append("      allocation_pools:\n");
                 for (Pool pool : subnet.getAllocationPools()) {
                     if (!commonUtils.isNullOrEmpty(pool.getStart()) && !commonUtils.isNullOrEmpty(pool.getEnd())) {
-                        curR = curR + "       - start: " + pool.getStart() + "\n";
-                        curR = curR + "         end: " + pool.getEnd() + "\n";
+                        tempBuf.append("       - start: ");
+                        tempBuf.append(pool.getStart());
+                        tempBuf.append("\n         end: ");
+                        tempBuf.append(pool.getEnd());
+                        tempBuf.append("\n");
                     }
                 }
+                curR = tempBuf.toString();
             }
 
             resourcesBuf.append(curR);
@@ -1492,7 +1498,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter {
             curO = curO.replace("%subnetId%", subnet.getSubnetId());
 
             outputsBuf.append(curO);
-
         }
         // append resources and outputs in heatTemplate
         logger.debug("Tempate initial:{}", heatTemplate);
diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/CSAR.java
deleted file mode 100644 (file)
index 7786b87..0000000
+++ /dev/null
@@ -1,189 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.so.adapters.vnf;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-import org.onap.so.adapters.vdu.VduArtifact;
-import org.onap.so.adapters.vdu.VduArtifact.ArtifactType;
-import org.onap.so.adapters.vdu.VduModelInfo;
-import org.onap.so.adapters.vnf.exceptions.VnfException;
-import com.google.common.io.Files;
-
-/**
- * The purpose of this class is to create a CSAR byte array from Vdu inputs for the purpose of forwarding to a TOSCA
- * orchestrator.
- * 
- * @author DeWayne
- *
- */
-public class CSAR {
-    private static final String MANIFEST_FILENAME = "MANIFEST.MF";
-    private VduModelInfo vduModel;
-
-    public CSAR(VduModelInfo model) {
-        this.vduModel = model;
-    }
-
-    /**
-     * Creates a byte array representation of a CSAR corresponding to the VduBlueprint arg in the constructor.
-     * 
-     * @return
-     * @throws VnfException
-     */
-    public byte[] create() {
-        File dir = Files.createTempDir();
-
-        /**
-         * Create subdir
-         */
-        File metadir = new File(dir.getAbsolutePath() + "/TOSCA-Metadata");
-        if (!metadir.mkdir()) {
-            throw new RuntimeException("CSAR TOSCA-Metadata directory create failed");
-        }
-
-        /**
-         * Organize model info for consumption
-         */
-        VduArtifact mainTemplate = null;
-        List<VduArtifact> extraFiles = new ArrayList<>();
-        for (VduArtifact artifact : vduModel.getArtifacts()) {
-            if (artifact.getType() == ArtifactType.MAIN_TEMPLATE) {
-                mainTemplate = artifact;
-            } else {
-                extraFiles.add(artifact);
-            }
-        }
-
-        if (mainTemplate == null) { // make a dummy to avoid null pointers
-            mainTemplate = new VduArtifact("", new byte[0], null);
-        }
-
-        /**
-         * Write template files
-         */
-        try (OutputStream ofs = new FileOutputStream(new File(dir, mainTemplate.getName()));
-                PrintStream mfstream =
-                        new PrintStream(new File(metadir.getAbsolutePath() + '/' + MANIFEST_FILENAME));) {
-            ofs.write(mainTemplate.getContent());
-
-            /**
-             * Write other files
-             */
-            if (!extraFiles.isEmpty()) {
-                for (VduArtifact artifact : extraFiles) {
-                    try (OutputStream out = new FileOutputStream(new File(dir, artifact.getName()));) {
-                        out.write(artifact.getContent());
-                    }
-                }
-            }
-
-
-            /**
-             * Create manifest
-             */
-            mfstream.println("TOSCA-Meta-File-Version: 1.0");
-            mfstream.println("CSAR-Version: 1.1");
-            mfstream.println("Created-by: ONAP");
-            mfstream.println("Entry-Definitions: " + mainTemplate.getName());
-
-            /**
-             * ZIP it up
-             */
-            ByteArrayOutputStream zipbytes = new ByteArrayOutputStream();
-            ZipOutputStream zos = new ZipOutputStream(zipbytes);
-            compressTree(zos, "", dir, dir);
-            zos.close();
-            return zipbytes.toByteArray();
-
-        } catch (Exception e) {
-            throw new RuntimeException("Failed to create CSAR: " + e.getMessage());
-        } finally {
-            /**
-             * Clean up tmpdir
-             */
-            deleteDirectory(dir);
-        }
-    }
-
-    /**
-     * Private methods
-     */
-
-    /**
-     * Compresses (ZIPs) a directory tree
-     * 
-     * @param dir
-     * @throws IOException
-     */
-    private void compressTree(ZipOutputStream zos, String path, File basedir, File dir) throws IOException {
-        if (!dir.isDirectory())
-            return;
-
-        for (File f : dir.listFiles()) {
-            if (f.isDirectory()) {
-                String newpath = path + f.getName() + '/';
-                ZipEntry entry = new ZipEntry(newpath);
-                zos.putNextEntry(entry);
-                zos.closeEntry();
-                compressTree(zos, newpath, basedir, f);
-            } else {
-                ZipEntry ze = new ZipEntry(
-                        f.getAbsolutePath().substring(basedir.getAbsolutePath().length() + 1).replaceAll("\\\\", "/"));
-                zos.putNextEntry(ze);
-                // read the file and write to ZipOutputStream
-                try (FileInputStream fis = new FileInputStream(f);) {
-                    byte[] buffer = new byte[1024];
-                    int len;
-                    while ((len = fis.read(buffer)) > 0) {
-                        zos.write(buffer, 0, len);
-                    }
-                }
-                zos.closeEntry();
-            }
-        }
-    }
-
-    private boolean deleteDirectory(File directory) {
-        if (directory.exists()) {
-            File[] files = directory.listFiles();
-            if (null != files) {
-                for (int i = 0; i < files.length; i++) {
-                    if (files[i].isDirectory()) {
-                        deleteDirectory(files[i]);
-                    } else {
-                        files[i].delete();
-                    }
-                }
-            }
-        }
-        return (directory.delete());
-    }
-}
index 09a5424..be53e50 100644 (file)
@@ -104,6 +104,7 @@ public class ExecuteBuildingBlockRainyDay {
                     }
                 } catch (Exception ex) {
                     // keep default serviceType value
+                    logger.error("Exception in serviceType retrivel", ex);
                 }
                 String vnfType = ASTERISK;
                 try {
@@ -115,6 +116,7 @@ public class ExecuteBuildingBlockRainyDay {
                     }
                 } catch (Exception ex) {
                     // keep default vnfType value
+                    logger.error("Exception in vnfType retrivel", ex);
                 }
 
                 String errorCode = ASTERISK;
@@ -122,12 +124,14 @@ public class ExecuteBuildingBlockRainyDay {
                     errorCode = "" + workflowException.getErrorCode();
                 } catch (Exception ex) {
                     // keep default errorCode value
+                    logger.error("Exception in errorCode retrivel", ex);
                 }
 
                 try {
                     errorCode = "" + (String) execution.getVariable("WorkflowExceptionCode");
                 } catch (Exception ex) {
                     // keep default errorCode value
+                    logger.error("Exception in errorCode retrivel", ex);
                 }
 
                 String workStep = ASTERISK;
@@ -135,6 +139,7 @@ public class ExecuteBuildingBlockRainyDay {
                     workStep = workflowException.getWorkStep();
                 } catch (Exception ex) {
                     // keep default workStep value
+                    logger.error("Exception in workStep retrivel", ex);
                 }
 
                 String errorMessage = ASTERISK;
@@ -142,6 +147,7 @@ public class ExecuteBuildingBlockRainyDay {
                     errorMessage = workflowException.getErrorMessage();
                 } catch (Exception ex) {
                     // keep default workStep value
+                    logger.error("Exception in errorMessage retrivel", ex);
                 }
 
                 String serviceRole = ASTERISK;
@@ -177,14 +183,14 @@ public class ExecuteBuildingBlockRainyDay {
                         logger.error("Failed to update Request Db Infra Active Requests with Retry Status", ex);
                     }
                 }
-                if (handlingCode.equals("RollbackToAssigned") && !aLaCarte) {
+                if ("RollbackToAssigned".equals(handlingCode) && !aLaCarte) {
                     handlingCode = "Rollback";
                 }
                 if (handlingCode.startsWith("Rollback")) {
                     String targetState = "";
-                    if (handlingCode.equalsIgnoreCase("RollbackToAssigned")) {
+                    if ("RollbackToAssigned".equalsIgnoreCase(handlingCode)) {
                         targetState = Status.ROLLED_BACK_TO_ASSIGNED.toString();
-                    } else if (handlingCode.equalsIgnoreCase("RollbackToCreated")) {
+                    } else if ("RollbackToCreated".equalsIgnoreCase(handlingCode)) {
                         targetState = Status.ROLLED_BACK_TO_CREATED.toString();
                     } else {
                         targetState = Status.ROLLED_BACK.toString();
@@ -204,7 +210,7 @@ public class ExecuteBuildingBlockRainyDay {
             int envMaxRetries = Integer.parseInt(this.environment.getProperty(maxRetries));
             execution.setVariable("maxRetries", envMaxRetries);
         } catch (Exception ex) {
-            logger.error("Could not read maxRetries from config file. Setting max to 5 retries");
+            logger.error("Could not read maxRetries from config file. Setting max to 5 retries", ex);
             execution.setVariable("maxRetries", 5);
         }
     }
@@ -247,8 +253,7 @@ public class ExecuteBuildingBlockRainyDay {
             request.setLastModifiedBy("CamundaBPMN");
             requestDbclient.updateInfraActiveRequests(request);
         } catch (Exception e) {
-            logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: "
-                    + e.getMessage());
+            logger.error("Failed to update Request db with extSystemErrorSource or rollbackExtSystemErrorSource: ", e);
         }
     }
 
index b2dbd97..aee28ca 100644 (file)
@@ -90,7 +90,6 @@ public class ExtractPojosForBB {
                     result = lookupObjectInList(serviceInstance.getConfigurations(), value);
                     break;
                 case VPN_ID:
-                    serviceInstance = extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
                     result = lookupObjectInList(gBBInput.getCustomer().getVpnBindings(), value);
                     break;
                 case VPN_BONDING_LINK_ID:
@@ -107,8 +106,9 @@ public class ExtractPojosForBB {
         } catch (BBObjectNotFoundException e) { // re-throw parent object not found
             throw e;
         } catch (Exception e) { // convert all other exceptions to object not found
-            logger.warn("BBObjectNotFoundException in ExtractPojosForBB",
-                    "BBObject " + key + " was not found in " + "gBBInput using reference value: " + value);
+            logger.warn(
+                    "BBObjectNotFoundException in ExtractPojosForBB, BBObject {} was not found in gBBInput using reference value: {} {}",
+                    key, value, e);
             throw new BBObjectNotFoundException(key, value);
         }
 
@@ -119,13 +119,8 @@ public class ExtractPojosForBB {
         }
     }
 
-    protected <T> Optional<T> lookupObject(Object obj, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
-        return findValue(obj, value);
-    }
-
-    protected <T> Optional<T> lookupObjectInList(List<?> list, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    protected <T> Optional<T> lookupObjectInList(List<?> list, String value)
+            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
         Optional<T> result = Optional.empty();
         for (Object obj : list) {
             result = findValue(obj, value);
@@ -137,8 +132,8 @@ public class ExtractPojosForBB {
 
     }
 
-    protected <T> Optional<T> findValue(Object obj, String value) throws IllegalAccessException,
-            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
+    protected <T> Optional<T> findValue(Object obj, String value)
+            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
         for (Field field : obj.getClass().getDeclaredFields()) {
             if (field.isAnnotationPresent(Id.class)) {
                 String fieldName = field.getName();
index 451fa64..e56eb42 100644 (file)
@@ -115,7 +115,7 @@ public class CamundaRequestHandler {
 
         List<HistoricProcessInstanceEntity> historicProcessInstanceList = response.getBody();
 
-        if (historicProcessInstanceList != null) {
+        if (historicProcessInstanceList != null && !historicProcessInstanceList.isEmpty()) {
             Collections.reverse(historicProcessInstanceList);
             processInstanceId = historicProcessInstanceList.get(0).getId();
         } else {
index 6f36fb2..a5ccb1b 100644 (file)
@@ -42,6 +42,7 @@ import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
 import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.EnumUtils;
 import org.apache.http.HttpStatus;
 import org.onap.so.apihandler.common.ErrorNumbers;
 import org.onap.so.apihandler.common.ResponseBuilder;
@@ -411,7 +412,11 @@ public class OrchestrationRequests {
 
     protected String mapRequestStatusToRequest(InfraActiveRequests iar, String format) {
         if (iar.getRequestStatus() != null) {
-            if (!StringUtils.isBlank(format) && OrchestrationRequestFormat.DETAIL.toString().equalsIgnoreCase(format)) {
+            boolean requestFormat = false;
+            if (format != null) {
+                requestFormat = EnumUtils.isValidEnum(OrchestrationRequestFormat.class, format.toUpperCase());
+            }
+            if (requestFormat) {
                 return iar.getRequestStatus();
             } else {
                 if (Status.ABORTED.toString().equalsIgnoreCase(iar.getRequestStatus())
index e6b5163..830f38f 100644 (file)
@@ -30,6 +30,7 @@ import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
 import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
@@ -119,7 +120,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameTest() throws IOException {
+    public void getActivityNameTest() {
         String expectedActivityName = "Last task executed: BB to Execute";
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
 
@@ -127,7 +128,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameNullActivityNameTest() throws IOException {
+    public void getActivityNameNullActivityNameTest() {
         String expectedActivityName = "Task name is null.";
         HistoricActivityInstanceEntity activityInstance = new HistoricActivityInstanceEntity();
         List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>();
@@ -139,7 +140,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameNullListTest() throws IOException {
+    public void getActivityNameNullListTest() {
         String expectedActivityName = "No results returned on activityInstance history lookup.";
         List<HistoricActivityInstanceEntity> activityInstanceList = null;
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
@@ -148,7 +149,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getActivityNameEmptyListTest() throws IOException {
+    public void getActivityNameEmptyListTest() {
         String expectedActivityName = "No results returned on activityInstance history lookup.";
         List<HistoricActivityInstanceEntity> activityInstanceList = new ArrayList<>();
         String actualActivityName = camundaRequestHandler.getActivityName(activityInstanceList);
@@ -157,7 +158,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameTest() throws IOException, ContactCamundaException {
+    public void getTaskNameTest() throws ContactCamundaException {
         doReturn(processInstanceResponse).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
         doReturn(activityInstanceResponse).when(camundaRequestHandler)
                 .getCamundaActivityHistory("c4c6b647-a26e-11e9-b144-0242ac14000b", REQUEST_ID);
@@ -170,7 +171,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameNullProcessInstanceListTest() throws IOException, ContactCamundaException {
+    public void getTaskNameNullProcessInstanceListTest() throws ContactCamundaException {
         ResponseEntity<List<HistoricProcessInstanceEntity>> response = new ResponseEntity<>(null, HttpStatus.OK);
         doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
         String expected = "No processInstances returned for requestId: " + REQUEST_ID;
@@ -181,7 +182,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameNullProcessInstanceIdTest() throws IOException, ContactCamundaException {
+    public void getTaskNameNullProcessInstanceIdTest() throws ContactCamundaException {
         HistoricProcessInstanceEntity processInstance = new HistoricProcessInstanceEntity();
         List<HistoricProcessInstanceEntity> processInstanceList = new ArrayList<>();
         processInstanceList.add(processInstance);
@@ -196,7 +197,19 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getTaskNameProcessInstanceLookupFailureTest() throws IOException, ContactCamundaException {
+    public void getTaskNameEmptyProcessInstanceListTest() throws ContactCamundaException {
+        ResponseEntity<List<HistoricProcessInstanceEntity>> response =
+                new ResponseEntity<>(Collections.emptyList(), HttpStatus.OK);
+        doReturn(response).when(camundaRequestHandler).getCamundaProcessInstanceHistory(REQUEST_ID);
+        String expected = "No processInstances returned for requestId: " + REQUEST_ID;
+
+        String actual = camundaRequestHandler.getTaskName(REQUEST_ID);
+
+        assertEquals(expected, actual);
+    }
+
+    @Test
+    public void getTaskNameProcessInstanceLookupFailureTest() throws ContactCamundaException {
         doThrow(HttpClientErrorException.class).when(camundaRequestHandler)
                 .getCamundaProcessInstanceHistory(REQUEST_ID);
 
@@ -205,7 +218,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaActivityHistoryTest() throws IOException, ContactCamundaException {
+    public void getCamundaActivityHistoryTest() throws ContactCamundaException {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl = "http://localhost:8089/sobpmnengine/history/activity-instance?processInstanceId="
@@ -239,7 +252,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaProccesInstanceHistoryTest() throws IOException, ContactCamundaException {
+    public void getCamundaProccesInstanceHistoryTest() {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl =
@@ -292,7 +305,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void getCamundaProccesInstanceHistoryFailThenSuccessTest() throws IOException, ContactCamundaException {
+    public void getCamundaProccesInstanceHistoryFailThenSuccessTest() {
         HttpHeaders headers = setHeaders();
         HttpEntity<?> requestEntity = new HttpEntity<>(headers);
         String targetUrl =
@@ -310,7 +323,7 @@ public class CamundaRequestHandlerTest {
     }
 
     @Test
-    public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException {
+    public void setCamundaHeadersTest() {
         String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password
         String key = "07a7159d3bf51a0e53be7a8f89699be7";
 
index 5023155..f672648 100644 (file)
@@ -295,6 +295,14 @@ public class OrchestrationRequestsUnitTest {
         assertEquals(Status.ABORTED.toString(), result);
     }
 
+    @Test
+    public void mapRequestStatusToRequestForFormatStatusDetailTest() throws ApiException {
+        iar.setRequestStatus(Status.ABORTED.toString());
+        String result = orchestrationRequests.mapRequestStatusToRequest(iar, "statusDetail");
+
+        assertEquals(Status.ABORTED.toString(), result);
+    }
+
 
     @Test
     public void mapRequestStatusToRequestForFormatEmptyStringTest() throws ApiException {