Simulate Request for SDC to get CSAR 49/91549/3
authoreHanan <eoin.hanan@est.tech>
Tue, 16 Jul 2019 15:27:06 +0000 (15:27 +0000)
committereHanan <eoin.hanan@est.tech>
Tue, 16 Jul 2019 15:27:06 +0000 (15:27 +0000)
Change-Id: I1b711b3eee8623d79ac9e00307ce48d6207d64d6
Issue-ID: SO-1951
Signed-off-by: eHanan <eoin.hanan@est.tech>
plans/so/integration-etsi-testing/so-simulators/pom.xml
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/pom.xml
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/Constant.java
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/SdcSimulatorApplication.java
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/SdcSimulatorController.java
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProvider.java [new file with mode: 0644]
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProviderImpl.java [new file with mode: 0644]
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/resources/csar/default_csar_file.csar [new file with mode: 0644]
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/test/java/org/onap/so/sdc/simulator/SdcSimulatorControllerTest.java
plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/test/java/org/onap/so/sdc/simulator/providers/ResourceProviderImplTest.java [new file with mode: 0644]

index feca047..5e582c8 100644 (file)
@@ -44,7 +44,7 @@
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-tomcat</artifactId>
-            <scope>provided</scope>
+            <scope>compile</scope>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
index 6a1bacc..397d4a7 100644 (file)
@@ -1,5 +1,5 @@
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <parent>
         <artifactId>so-simulators</artifactId>
         <groupId>org.onap.so.simulators</groupId>
index c4e9c46..d03bb7b 100644 (file)
@@ -20,7 +20,21 @@ package org.onap.so.sdc.simulator;
  */
 public class Constant {
 
-    public static final String BASE_URL = "/sdc/simulator/v1";
+    public static final String BASE_URL = "/simulator/sdc/v1/catalog";
 
-    private Constant() {}
+    public static final String HEALTHY = "healthy";
+
+    public static final String DEFAULT_CSAR_NAME = "default_csar_file";
+
+    public static final String DOT = ".";
+
+    public static final String DOT_CSAR = DOT + "csar";
+
+    public static final String DEFAULT_CSAR_NAME_WITH_EXT = DEFAULT_CSAR_NAME + DOT_CSAR;
+
+    public static final String DEFAULT_CSAR_PATH = "/csar/" + DEFAULT_CSAR_NAME_WITH_EXT;
+
+
+    private Constant() {
+    }
 }
index 6bcd04d..abb183b 100644 (file)
@@ -27,8 +27,9 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
 /**
  * @author Waqas Ikram (waqas.ikram@est.tech)
  */
-@SpringBootApplication
+@SpringBootApplication(scanBasePackages = {"org.onap"})
 public class SdcSimulatorApplication extends SpringBootServletInitializer {
+
     public static void main(final String[] args) {
         SpringApplication.run(SdcSimulatorApplication.class, args);
     }
index 12e179f..953df6f 100644 (file)
 
 package org.onap.so.sdc.simulator;
 
+import java.util.Optional;
+import javax.ws.rs.core.MediaType;
+import org.onap.so.sdc.simulator.providers.ResourceProvider;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseStatus;
 import org.springframework.web.bind.annotation.RestController;
-import javax.ws.rs.core.MediaType;
 
 /**
  * @author Waqas Ikram (waqas.ikram@est.tech)
  */
 @RestController
-@RequestMapping(path = Constant.BASE_URL, produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
+@RequestMapping(path = Constant.BASE_URL)
 public class SdcSimulatorController {
 
+    private ResourceProvider resourceProvider;
+
+    public SdcSimulatorController(@Autowired final ResourceProvider resourceProvider) {
+        this.resourceProvider = resourceProvider;
+    }
+
     private static final Logger LOGGER = LoggerFactory.getLogger(SdcSimulatorController.class);
 
-    @GetMapping(value = "/healthcheck")
+    @GetMapping(value = "/healthcheck", produces = MediaType.APPLICATION_JSON)
     @ResponseStatus(code = HttpStatus.OK)
     public String healthCheck() {
         LOGGER.info("Running health check ...");
-        return "healthy";
+        return Constant.HEALTHY;
     }
 
+    @GetMapping(value = "/resources/{csarId}/toscaModel", produces = MediaType.APPLICATION_OCTET_STREAM)
+    public ResponseEntity<byte[]> getCsar(@PathVariable("csarId") final String csarId) {
+        LOGGER.info("Running getCsar for {} ...", csarId);
+        final Optional<byte[]> resource = resourceProvider.getResource(csarId);
+        if (resource.isPresent()) {
+            return new ResponseEntity<>(resource.get(), HttpStatus.OK);
+        }
+        LOGGER.error("Unable to find csar: {}", csarId);
+
+        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
+    }
 
 }
diff --git a/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProvider.java b/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProvider.java
new file mode 100644 (file)
index 0000000..83994b4
--- /dev/null
@@ -0,0 +1,36 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *   Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ *  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.
+ *
+ *  SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.sdc.simulator.providers;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Optional;
+
+/**
+ * @author Eoin Hanan (eoin.hanan@est.tech)
+ */
+public interface ResourceProvider {
+
+    Optional<byte[]> getResource(final String csarId);
+
+    Optional<InputStream> getInputStream(final String csarId) throws IOException;
+
+}
diff --git a/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProviderImpl.java b/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/java/org/onap/so/sdc/simulator/providers/ResourceProviderImpl.java
new file mode 100644 (file)
index 0000000..302dcb6
--- /dev/null
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *   Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ *  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.
+ *
+ *  SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.sdc.simulator.providers;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Optional;
+import org.onap.so.sdc.simulator.Constant;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StreamUtils;
+
+/**
+ * @author Eoin Hanan (eoin.hanan@est.tech)
+ */
+@Service
+public class ResourceProviderImpl implements ResourceProvider {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceProvider.class);
+
+    private final String resourceLocation;
+
+    public ResourceProviderImpl(@Value("${sdc.resource.location:/app/csars/}") final String resourceLocation) {
+        this.resourceLocation = resourceLocation;
+    }
+
+    @Override
+    public Optional<byte[]> getResource(final String csarId) {
+        try {
+            final Optional<InputStream> optionalInputStream = getInputStream(csarId);
+            if (optionalInputStream.isPresent()) {
+                return Optional.of(StreamUtils.copyToByteArray(optionalInputStream.get()));
+            }
+        } catch (final IOException ioException) {
+            LOGGER.warn("Unable to create file stream ...", ioException);
+        }
+
+        return Optional.empty();
+    }
+
+    @Override
+    public Optional<InputStream> getInputStream(final String csarId) throws IOException {
+        final Path filePath = Paths.get(resourceLocation, csarId + ".csar");
+        if (Files.exists(filePath)) {
+            return Optional.of(Files.newInputStream(filePath));
+        }
+
+        LOGGER.info("Couldn't find file on file system '{}', will return default csar", filePath);
+        final ClassPathResource classPathResource = new ClassPathResource(getDefaultCsarPath(), this.getClass());
+        if (classPathResource.exists()) {
+            return Optional.of(classPathResource.getInputStream());
+        }
+
+        LOGGER.error("Couldn't find default csar in classpath ....");
+        return Optional.empty();
+    }
+
+    /*
+     * Used in test
+     */
+    String getDefaultCsarPath() {
+        return Constant.DEFAULT_CSAR_PATH;
+    }
+}
\ No newline at end of file
diff --git a/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/resources/csar/default_csar_file.csar b/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/resources/csar/default_csar_file.csar
new file mode 100644 (file)
index 0000000..63b70ec
Binary files /dev/null and b/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/main/resources/csar/default_csar_file.csar differ
index e0d44e9..5c7a77a 100644 (file)
 package org.onap.so.sdc.simulator;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Optional;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.onap.so.sdc.simulator.providers.ResourceProvider;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
 import org.springframework.boot.test.web.client.TestRestTemplate;
 import org.springframework.boot.web.server.LocalServerPort;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.MediaType;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.test.context.ActiveProfiles;
 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -42,8 +48,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 @RunWith(SpringJUnit4ClassRunner.class)
 @ActiveProfiles("test")
 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
+@Configuration
 public class SdcSimulatorControllerTest {
 
+    private static final String MOCKER_SDC_CONTROLLER_BEAN = "mockResourceProvider";
+
     @LocalServerPort
     private int port;
 
@@ -51,16 +60,41 @@ public class SdcSimulatorControllerTest {
     private TestRestTemplate restTemplate;
 
     @Test
-    public void testHealthCheck() {
-        final HttpHeaders headers = new HttpHeaders();
-        headers.setContentType(MediaType.APPLICATION_JSON);
+    public void test_healthCheck_matchContent() {
+        final String url = getBaseUrl() + "/healthcheck";
+        final ResponseEntity<String> object = restTemplate.getForEntity(url, String.class);
+
+        assertEquals(Constant.HEALTHY, object.getBody());
+
+    }
+
+    @Test
+    public void test_getCsar_validCsarId_matchContent() {
+
+        final String url = getBaseUrl() + "/resources/" + Constant.DEFAULT_CSAR_NAME + "/toscaModel";
 
-        final HttpEntity<?> request = new HttpEntity<>(headers);
-        final String url = "http://localhost:" + port + Constant.BASE_URL + "/healthcheck";
-        final ResponseEntity<String> object = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
+        final ResponseEntity<byte[]> response = restTemplate.getForEntity(url, byte[].class);
 
-        assertEquals("healthy", object.getBody());
+        assertTrue(response.hasBody());
+        assertEquals(3982, response.getBody().length);
+
+        assertEquals(HttpStatus.OK, response.getStatusCode());
+    }
+
+    @Test
+    public void test_getCsar_invalidCsar_internalServerError() {
+        final ResourceProvider mockedResourceProvider = Mockito.mock(ResourceProvider.class);
+        Mockito.when(mockedResourceProvider.getResource(Mockito.anyString())).thenReturn(Optional.empty());
+        final SdcSimulatorController objUnderTest = new SdcSimulatorController(mockedResourceProvider);
+
+        final ResponseEntity<byte[]> response = objUnderTest.getCsar(Constant.DEFAULT_CSAR_NAME);
+
+        assertFalse(response.hasBody());
+        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
+    }
 
+    private String getBaseUrl() {
+        return "http://localhost:" + port + Constant.BASE_URL;
     }
 
 }
diff --git a/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/test/java/org/onap/so/sdc/simulator/providers/ResourceProviderImplTest.java b/plans/so/integration-etsi-testing/so-simulators/sdc-simulator/src/test/java/org/onap/so/sdc/simulator/providers/ResourceProviderImplTest.java
new file mode 100644 (file)
index 0000000..a06d1e7
--- /dev/null
@@ -0,0 +1,98 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.sdc.simulator.providers;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.onap.so.sdc.simulator.Constant;
+import org.springframework.core.io.ClassPathResource;
+import org.springframework.util.StreamUtils;
+
+/**
+ * @author Waqas Ikram (waqas.ikram@est.tech)
+ * @author Eoin Hanan (eoin.hanan@est.tech)
+ */
+public class ResourceProviderImplTest {
+
+    @Rule
+    public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+    private static final String DUMMY_CONTENT = "Hell world";
+
+    @Test
+    public void test_getResource_withValidPath_matchContent() throws IOException {
+        final File folder = temporaryFolder.newFolder();
+        final Path file = Files.createFile(folder.toPath().resolve("empty.csar"));
+
+        Files.write(file, DUMMY_CONTENT.getBytes());
+
+        final ResourceProviderImpl objUnderTest = new ResourceProviderImpl(folder.getPath());
+
+        assertArrayEquals(DUMMY_CONTENT.getBytes(), objUnderTest.getResource("empty").get());
+    }
+
+    @Test
+    public void test_getResource_withoutValidPath_matchContent() throws IOException {
+        final ClassPathResource classPathResource = new ClassPathResource(Constant.DEFAULT_CSAR_PATH, this.getClass());
+
+        final byte[] expectedResult = StreamUtils.copyToByteArray(classPathResource.getInputStream());
+
+        final ResourceProviderImpl objUnderTest = new ResourceProviderImpl("");
+
+        assertArrayEquals(expectedResult, objUnderTest.getResource(Constant.DEFAULT_CSAR_NAME).get());
+    }
+
+    @Test
+    public void test_getResource_unbleToreadFileFromClasspath_emptyOptional() throws IOException {
+
+        final ResourceProviderImpl objUnderTest = new ResourceProviderImpl("") {
+            @Override
+            String getDefaultCsarPath() {
+                return "/some/dummy/path";
+            }
+        };
+        assertFalse(objUnderTest.getResource(Constant.DEFAULT_CSAR_NAME).isPresent());
+
+    }
+
+    @Test
+    public void test_getResource_withValidPathAndUnabletoRead_emptyOptional() throws IOException {
+        final File folder = temporaryFolder.newFolder();
+        final Path file = Files.createFile(folder.toPath().resolve("empty.csar"));
+
+        Files.write(file, DUMMY_CONTENT.getBytes());
+        file.toFile().setReadable(false);
+
+        final ResourceProviderImpl objUnderTest = new ResourceProviderImpl(folder.getPath());
+
+        assertFalse(objUnderTest.getResource("empty").isPresent());
+
+    }
+
+}
\ No newline at end of file