Implementation for TMF 633 API - POST /serviceSpecification
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / servicecatalog / SdcClient.java
index fed9bb5..29a4a25 100644 (file)
  * or implied. See the License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.onap.nbi.apis.servicecatalog;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.net.URI;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.util.*;
+import java.util.Map.Entry;
+import javax.annotation.PostConstruct;
 import org.apache.commons.io.IOUtils;
 import org.onap.nbi.OnapComponentsUrlPaths;
 import org.onap.nbi.exceptions.BackendFunctionalException;
@@ -31,9 +36,11 @@ import org.springframework.http.HttpEntity;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.ResourceAccessException;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.web.util.UriComponentsBuilder;
 
@@ -44,7 +51,6 @@ import org.springframework.web.util.UriComponentsBuilder;
 @Service
 public class SdcClient {
 
-    public static final String HTTP_CALL_SDC_ON = "HTTP call SDC on ";
     @Autowired
     private RestTemplate restTemplate;
 
@@ -59,29 +65,45 @@ public class SdcClient {
 
     private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
     private static final String HEADER_AUTHORIZATION = "Authorization";
+    // changes for Post Implementation
+    private static final String USER_ID = "USER_ID";
 
     private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
 
+    private String sdcGetUrl;
+    private String sdcFindUrl;
+    private String sdcHealthCheck;
 
-    public LinkedHashMap callGet(String id) {
-        StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
-                .append("/").append(id).append(OnapComponentsUrlPaths.SDC_GET_PATH);
+    @PostConstruct
+    private void setUpAndLogSDCUrl() {
+        sdcGetUrl = new StringBuilder().append(sdcHost)
+                .append(OnapComponentsUrlPaths.SDC_ROOT_URL + "/{id}" + OnapComponentsUrlPaths.SDC_GET_PATH).toString();
+        sdcFindUrl = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL).toString();
+        sdcHealthCheck = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_HEALTH_CHECK).toString();
 
-        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
+        LOGGER.info("SDC GET url :  " + sdcGetUrl);
+        LOGGER.info("SDC FIND url :  " + sdcFindUrl);
+        LOGGER.info("SDC HealthCheck :  " + sdcHealthCheck);
 
-        ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
+    }
+
+    public Map callGet(String id) {
+
+        String callUrl = sdcGetUrl.replace("{id}", id);
+        UriComponentsBuilder callURLFormated = UriComponentsBuilder.fromHttpUrl(callUrl);
+        ResponseEntity<Object> response = callSdc(callURLFormated.build().encode().toUri());
         return (LinkedHashMap) response.getBody();
 
     }
 
     public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
 
-        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHost + OnapComponentsUrlPaths.SDC_ROOT_URL);
+        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcFindUrl);
         if (parametersMap != null) {
             Map<String, String> stringStringMap = parametersMap.toSingleValueMap();
-            for (String key : stringStringMap.keySet()) {
-                if (!key.equals("fields")) {
-                    callURI.queryParam(key, stringStringMap.get(key));
+            for (Entry<String, String> entry : stringStringMap.entrySet()) {
+                if (!entry.getKey().equals("fields")) {
+                    callURI.queryParam(entry.getKey(), entry.getValue());
                 }
             }
         }
@@ -91,14 +113,25 @@ public class SdcClient {
 
     }
 
+    public LinkedHashMap callCheckConnectivity() {
+
+        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHealthCheck);
+        ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
+        return (LinkedHashMap) response.getBody();
+
+    }
 
     public File callGetWithAttachment(String toscaModelUrl) {
         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
 
         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
 
+        File directory = new File("temptoscafile");
+        if (!directory.exists()) {
+            directory.mkdir();
+        }
 
-        String fileName = System.currentTimeMillis() + "tosca.csar";
+        String fileName = "temptoscafile/" + System.currentTimeMillis() + "tosca.csar";
         ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
         File toscaFile = new File(fileName);
         try {
@@ -114,50 +147,121 @@ public class SdcClient {
 
     }
 
+    public Path getServiceToscaModel(String uuid) throws IOException {
+        StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
+                .append("/").append(uuid).append(OnapComponentsUrlPaths.SDC_TOSCA_PATH);
+
+        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
+
+        InputStream inputStream = (InputStream) callSdc(callURI.build().encode().toUri()).getBody();
+
+        return createTmpFile(inputStream);
+    }
+    /**
+     *
+     * @param serviceCatalogObject
+     * @param userId
+     */
+    public Map callPost(HashMap<Object, Object> serviceCatalogObject, String userId) {
+        // post url is the same as find url
+        UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcFindUrl);
+        ResponseEntity<Object> response = callSdcForPost(callURI.build().encode().toUri(), serviceCatalogObject,
+                userId);
+        // return (List<LinkedHashMap>) response.getBody();
+        return (LinkedHashMap) response.getBody();
+    }
+
+    private Path createTmpFile(InputStream csarInputStream) throws IOException {
+        Path csarFile = Files.createTempFile("csar", ".zip");
+        Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
+
+        LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
+
+        return csarFile;
+    }
+
     private HttpEntity<String> buildRequestHeader() {
         HttpHeaders httpHeaders = new HttpHeaders();
+        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
         httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
         httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
-        HttpEntity<String> entity = new HttpEntity<>("parameters", httpHeaders);
-
-        return entity;
+        return new HttpEntity<>("parameters", httpHeaders);
     }
 
-
     private ResponseEntity<Object> callSdc(URI callURI) {
         ResponseEntity<Object> response =
                 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
-        LOGGER.debug("response body : " + response.getBody().toString());
-        LOGGER.info("response status : " + response.getStatusCodeValue());
+
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("response body : {} ", response.getBody().toString());
+        }
+        LOGGER.info("response status : {}", response.getStatusCodeValue());
         loggDebugIfResponseKo(callURI.toString(), response);
         return response;
     }
 
-
     private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
         try {
             ResponseEntity<byte[]> response =
                     restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), byte[].class);
             LOGGER.info("response status : " + response.getStatusCodeValue());
-            if (!response.getStatusCode().equals(HttpStatus.OK)) {
-                LOGGER.warn(HTTP_CALL_SDC_ON + callURI.toString() + " returns " + response.getStatusCodeValue() + ", "
-                        + response.getBody().toString());
+            if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
+                LOGGER.warn("HTTP call SDC on {} returns {} ", callURI.toString(), response.getStatusCodeValue());
             }
             return response;
 
         } catch (BackendFunctionalException e) {
-            LOGGER.error(HTTP_CALL_SDC_ON + callURI.toString() + " error " + e);
+            LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString(), e);
             return null;
         }
     }
 
-
     private void loggDebugIfResponseKo(String callURI, ResponseEntity<Object> response) {
-        if (!response.getStatusCode().equals(HttpStatus.OK)) {
-            LOGGER.warn(HTTP_CALL_SDC_ON + callURI + " returns " + response.getStatusCodeValue() + ", "
-                + response.getBody().toString());
+        if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
+            LOGGER.warn("HTTP call SDC on {} returns {} , {}", callURI, response.getStatusCodeValue(),
+                    response.getBody().toString());
         }
     }
-}
 
+    //changes for Post implementation start
+    /**
+     *
+     * @param callURI
+     * @param obj
+     * @param userId
+     * @return
+     */
+    private ResponseEntity<Object> callSdcForPost(URI callURI, Object obj, String userId) {
+        ResponseEntity<Object> response = restTemplate.exchange(callURI, HttpMethod.POST,
+                new HttpEntity<>(obj, buildRequestHeaderForPost(userId)), Object.class);
+
+        if (null == response) {
+            return null;
+        } else {
 
+            if (LOGGER.isDebugEnabled()) {
+                LOGGER.debug("response body : {} ", response.getBody().toString());
+            }
+            LOGGER.info("response status : {}", response.getStatusCodeValue());
+            return response;
+        }
+
+    }
+    /**
+     *
+     * @param userId
+     * @return
+     */
+    private HttpHeaders buildRequestHeaderForPost(String userId) {
+        HttpHeaders httpHeaders = new HttpHeaders();
+
+        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
+        httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
+        httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
+        httpHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
+        httpHeaders.add(USER_ID, userId);
+
+        return httpHeaders;
+    }
+
+}