Add more JUnit test cases 64/3964/2
authorAndrew Gauld <agauld@att.com>
Fri, 15 Mar 2019 20:13:46 +0000 (20:13 +0000)
committerAndrew Gauld <agauld@att.com>
Mon, 18 Mar 2019 19:05:11 +0000 (19:05 +0000)
Change-Id: I0857a51864558f683bb06df4da5d218bfab1e769
Issue-ID: ACUMOS-2584
Signed-off-by: Andrew Gauld <agauld@att.com>
44 files changed:
docs/release-notes.rst
gateway/pom.xml
gateway/src/main/java/org/acumos/federation/gateway/adapter/onap/sdc/ASDC.java
gateway/src/main/java/org/acumos/federation/gateway/cds/ArtifactTypes.java
gateway/src/main/java/org/acumos/federation/gateway/cds/PeerStatuses.java
gateway/src/main/java/org/acumos/federation/gateway/cds/PeerSubscription.java
gateway/src/main/java/org/acumos/federation/gateway/config/LocalConfiguration.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/PeerServiceImpl.java
gateway/src/test/java/org/acumos/federation/gateway/test/AsdcTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/CatalogServiceTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/ContentServiceTest.java [new file with mode: 0644]
gateway/src/test/java/org/acumos/federation/gateway/test/ControllerTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/LocalControllerTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/PeerGatewayTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/PeerServiceTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/ServiceTest.java
gateway/src/test/java/org/acumos/federation/gateway/test/UtilsTest.java
gateway/src/test/resources/mockCDSCreateArtifactResponse.json
gateway/src/test/resources/mockCDSCreateDocumentResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSCreateRevisionDescriptionResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSCreateRevisionDocumentResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSCreateSolutionResponse.json
gateway/src/test/resources/mockCDSCreateSolutionRevisionResponse.json
gateway/src/test/resources/mockCDSPeerResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSPeerSearchAllResponse.json
gateway/src/test/resources/mockCDSPeerSubscriptionResponse.json
gateway/src/test/resources/mockCDSPeerSubscriptionsResponse.json
gateway/src/test/resources/mockCDSSolutionRevisionArtifactResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSSolutionRevisionArtifactsResponse.json
gateway/src/test/resources/mockCDSSolutionRevisionDescriptionResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSSolutionRevisionDocumentResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSSolutionRevisionDocumentsResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockCDSSolutionRevisionResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockPeerArtifactContent.txt [new file with mode: 0644]
gateway/src/test/resources/mockPeerDocumentContent.txt [new file with mode: 0644]
gateway/src/test/resources/mockPeerRegisterResponse.json [new file with mode: 0644]
gateway/src/test/resources/mockPeerSolutionRevisionArtifactsResponse.json
gateway/src/test/resources/mockPeerSolutionRevisionResponse.json
gateway/src/test/resources/mockPeerSolutionRevisionsResponse.json
gateway/src/test/resources/mockPeerSolutionsResponse.json
gateway/src/test/resources/onap/sdc/BytesResponse.tgz [new file with mode: 0644]
gateway/src/test/resources/onap/sdc/EmptyArrayResponse.json [new file with mode: 0644]
gateway/src/test/resources/onap/sdc/EmptyObjectResponse.json [new file with mode: 0644]
gateway/src/test/resources/test-catalog.json

index 4498860..30f63b9 100644 (file)
@@ -23,6 +23,10 @@ Federation Gateway Release Notes
 This server is available as a Docker image in a Docker registry at the Linux Foundation.
 The image name is "federation-gateway" and the tag is a version string as shown below. 
 
+Version 2.1.2, 2019-03-15
+-------------------------
+* Add JUnit test cases to reach 50% or better code coverage (`ACUMOS-2584 <https://jira.acumos.org/browse/ACUMOS-2584>`_)
+
 Version 2.1.1, 2019-03-07
 -------------------------
 * Solution picture should be copied (`ACUMOS-2570 <https://jira.acumos.org/browse/ACUMOS-2570>`_)
index 2bc4f48..9f4835b 100644 (file)
@@ -25,7 +25,7 @@
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.acumos.federation</groupId>
        <artifactId>gateway</artifactId>
-       <version>2.1.1-SNAPSHOT</version>
+       <version>2.1.2-SNAPSHOT</version>
        <name>Federation Gateway</name>
        <description>Federated Acumos Interface for inter-acumos and ONAP communication</description>
 
index a528bd6..b6a6261 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
@@ -29,6 +29,7 @@ import java.util.Collections;
 import java.util.List;
 import java.util.UUID;
 import java.util.function.UnaryOperator;
+import java.util.function.Supplier;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 
@@ -99,6 +100,16 @@ public class ASDC {
        private String user, passwd;
        private String instanceId;
 
+       private Supplier<AsyncRestTemplate> artfactory = () -> new AsyncRestTemplate();
+
+       public void setARTFactory(Supplier<AsyncRestTemplate> factory) {
+               artfactory = factory;
+       }
+
+       public Supplier<AsyncRestTemplate> getARTFactory() {
+               return artfactory;
+       }
+
        public void setUri(URI theUri) {
                String userInfo = theUri.getUserInfo();
                if (userInfo != null) {
@@ -887,7 +898,7 @@ public class ASDC {
        public <T> Future<T> exchange(String theRef, HttpMethod theMethod, HttpEntity theRequest,
                        Class<T> theResponseType) {
 
-               AsyncRestTemplate restTemplate = new AsyncRestTemplate();
+               AsyncRestTemplate restTemplate = artfactory.get();
 
                List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
                converters.add(0, new JSONHttpMessageConverter());
index 31fcaf0..510e354 100644 (file)
@@ -27,21 +27,21 @@ import java.util.List;
 public class ArtifactTypes extends CodeNames<ArtifactType> {
 
        //these are the artifact type codes that we expect to find in all deployments.
-  public static ArtifactType Blueprint = forCode("BP");
-  public static ArtifactType Cdump = forCode("CD");
-  public static ArtifactType DockerImage = forCode("DI");
-  public static ArtifactType DataSource = forCode("DS");
-  public static ArtifactType Metadata = forCode("MD");
-  public static ArtifactType ModelH2O = forCode("MH");
-  public static ArtifactType ModelImage = forCode("MI");
-  public static ArtifactType ModelR = forCode("MR");
-  public static ArtifactType ModelScikit = forCode("MS");
-  public static ArtifactType ModelTensorflow = forCode("MT");
-  public static ArtifactType ToscaTemplate = forCode("TE");
-  public static ArtifactType ToscaGenerator = forCode("TG");
-  public static ArtifactType ToscaSchema = forCode("TS");
-  public static ArtifactType ToscaTranslate = forCode("TT");
-  public static ArtifactType ProtobufFile = forCode("PJ");
+  public static final ArtifactType Blueprint = forCode("BP");
+  public static final ArtifactType Cdump = forCode("CD");
+  public static final ArtifactType DockerImage = forCode("DI");
+  public static final ArtifactType DataSource = forCode("DS");
+  public static final ArtifactType Metadata = forCode("MD");
+  public static final ArtifactType ModelH2O = forCode("MH");
+  public static final ArtifactType ModelImage = forCode("MI");
+  public static final ArtifactType ModelR = forCode("MR");
+  public static final ArtifactType ModelScikit = forCode("MS");
+  public static final ArtifactType ModelTensorflow = forCode("MT");
+  public static final ArtifactType ToscaTemplate = forCode("TE");
+  public static final ArtifactType ToscaGenerator = forCode("TG");
+  public static final ArtifactType ToscaSchema = forCode("TS");
+  public static final ArtifactType ToscaTranslate = forCode("TT");
+  public static final ArtifactType ProtobufFile = forCode("PJ");
 
 
        public static ArtifactType forCode(String theCode) {
index 489de84..d77d79a 100644 (file)
@@ -25,12 +25,12 @@ import java.util.List;
  */
 public class PeerStatuses extends CodeNames<PeerStatus> {
 
-       public static PeerStatus Active = forCode("AC");
-       public static PeerStatus Inactive = forCode("IN");
-       public static PeerStatus Requested = forCode("RQ");
-       public static PeerStatus Renounced = forCode("RN");
-       public static PeerStatus Declined = forCode("DC");
-       public static PeerStatus Unknown = forCode("UK");
+       public static final PeerStatus Active = forCode("AC");
+       public static final PeerStatus Inactive = forCode("IN");
+       public static final PeerStatus Requested = forCode("RQ");
+       public static final PeerStatus Renounced = forCode("RN");
+       public static final PeerStatus Declined = forCode("DC");
+       public static final PeerStatus Unknown = forCode("UK");
 
        public PeerStatuses() {
        }
index 4d9b338..0d54526 100644 (file)
@@ -84,7 +84,7 @@ public class PeerSubscription extends MLPPeerSubscription {
 
        public static class SubscriptionOptions {
        
-               public CatalogUpdateOptions catalogUpdate = CatalogUpdateOptions.onSuccess;
+               public static final CatalogUpdateOptions catalogUpdate = CatalogUpdateOptions.onSuccess;
 
                public boolean alwaysUpdateCatalog() {
                        return this.catalogUpdate.equals(CatalogUpdateOptions.always);
index d7173c3..1727286 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos Apache-2.0
  * ===================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
@@ -25,6 +25,7 @@ import java.lang.invoke.MethodHandles;
 import org.acumos.federation.gateway.controller.PeerCatalogController;
 import org.acumos.federation.gateway.controller.PeerPeersController;
 import org.acumos.federation.gateway.controller.PeerPingController;
+import org.acumos.federation.gateway.controller.PeerRegistrationController;
 import org.acumos.federation.gateway.controller.PeerSubscriptionController;
 import org.apache.http.client.HttpClient;
 import org.slf4j.Logger;
@@ -57,6 +58,11 @@ public class LocalConfiguration {
                return new PeerPingController();
        }
 
+       @Bean
+       public PeerRegistrationController peerRegistrationServer() {
+               return new PeerRegistrationController();
+       }
+
        @Bean
        public PeerCatalogController peerCatalogServer() {
                return new PeerCatalogController();
index 1c18916..27da8b5 100644 (file)
@@ -137,7 +137,7 @@ public class PeerServiceImpl extends AbstractServiceImpl implements PeerService
                log.debug("getPeerById: {}", thePeerId);
                MLPPeer mlpPeer = getClient().getPeer(thePeerId);
                if (mlpPeer != null) {
-                       log.error("getPeerById: {}", mlpPeer.toString());
+                       log.info("getPeerById: {}", mlpPeer);
                }
                return mlpPeer;
        }
index 4869d9f..45d7ce2 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
 package org.acumos.federation.gateway.test;
 
 import java.lang.invoke.MethodHandles;
+import java.io.IOException;
+import java.io.OutputStream;
 import java.net.URI;
 import java.nio.charset.Charset;
+import java.util.UUID;
 
-import org.acumos.federation.gateway.adapter.onap.sdc.ASDC;
-import org.acumos.federation.gateway.adapter.onap.sdc.ASDCException;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.protocol.HttpContext;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpMethod;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.client.AsyncClientHttpRequest;
+import org.springframework.http.client.AsyncClientHttpRequestFactory;
+import org.springframework.http.client.ClientHttpRequest;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.util.concurrent.SettableListenableFuture;
+import org.springframework.web.client.AsyncRestTemplate;
 import org.springframework.web.client.HttpClientErrorException;
 
+import org.acumos.federation.gateway.adapter.onap.sdc.ASDC;
+import org.acumos.federation.gateway.adapter.onap.sdc.ASDCException;
+
 public class AsdcTest {
 
        private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 
+       private static class RequestAsyncWrapper implements AsyncClientHttpRequest, ClientHttpRequest {
+               private ClientHttpRequest wrapped;
+
+               public RequestAsyncWrapper(ClientHttpRequest request) {
+                       wrapped = request;
+               }
+
+               public ListenableFuture<ClientHttpResponse> executeAsync() throws IOException {
+                       SettableListenableFuture<ClientHttpResponse> future = new SettableListenableFuture<>();
+                       try {
+                               future.set(wrapped.execute());
+                       } catch (Exception e) {
+                               future.setException(e);
+                       }
+                       return future;
+               }
+
+               public ClientHttpResponse execute() throws IOException {
+                       ClientHttpResponse ret = wrapped.execute();
+                       return ret;
+               }
+
+               public String getMethodValue() {
+                       return wrapped.getMethodValue();
+               }
+
+               public URI getURI() {
+                       return wrapped.getURI();
+               }
+
+               public OutputStream getBody() throws IOException {
+                       return wrapped.getBody();
+               }
+
+               public HttpHeaders getHeaders() {
+                       return wrapped.getHeaders();
+               }
+       }
+
+       private static class RequestFactoryAsyncWrapper implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
+               private ClientHttpRequestFactory wrapped;
+
+               public RequestFactoryAsyncWrapper(ClientHttpRequestFactory factory) {
+                       wrapped = factory;
+               }
+
+               public AsyncClientHttpRequest createAsyncRequest(URI uri, HttpMethod httpMethod) throws IOException {
+                       return new RequestAsyncWrapper(wrapped.createRequest(uri, httpMethod));
+               }
+
+               public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
+                       return wrapped.createRequest(uri, httpMethod);
+               }
+       }
+
+       private MockAnswer asdcAnswer = new MockAnswer();
+
+       @Mock
+       private CloseableHttpClient asdcClient;
+
+       private UUID someuuid = UUID.randomUUID();
+
+       private AsyncRestTemplate mockTemplate() {
+               AsyncRestTemplate ret = new AsyncRestTemplate();
+               ret.setAsyncRequestFactory(new RequestFactoryAsyncWrapper(new HttpComponentsClientHttpRequestFactory(asdcClient)));
+               return ret;
+       }
+
+       @Before
+       public void initTest() throws IOException {
+               MockitoAnnotations.initMocks(this);
+
+               // todo set up answers
+               asdcAnswer
+                       .mockResponse(info -> info.getPath().startsWith("/arraycontext/"), MockResponse.success("onap/sdc/EmptyArrayResponse.json"))
+                       .mockResponse(info -> info.getPath().startsWith("/objectcontext/"), MockResponse.success("onap/sdc/EmptyObjectResponse.json"))
+                       .mockResponse(info -> info.getPath().startsWith("/bytescontext/"), MockResponse.success("onap/sdc/BytesResponse.tgz"))
+                       ;
+
+               when(
+                   asdcClient.execute(any(HttpUriRequest.class), any(HttpContext.class))
+               ).thenAnswer(asdcAnswer);
+       }
+
        @Test
        public void testASDC() throws Exception {
                for (ASDC.AssetType e : ASDC.AssetType.values())
@@ -47,6 +158,10 @@ public class AsdcTest {
                for (ASDC.LifecycleState e : ASDC.LifecycleState.values())
                        log.info("lifecycle state {}, code {}", e);
                ASDC asdc = new ASDC();
+               asdc.checkForUpdates();
+               asdc.initASDC();
+               asdc.getARTFactory();
+               asdc.setARTFactory(() -> mockTemplate());
                URI uriNoFrag = new URI("http://user:pass@host:443/context/path");
                try {
                        asdc.setUri(uriNoFrag);
@@ -54,9 +169,113 @@ public class AsdcTest {
                } catch (Exception ex) {
                        log.info("Caught exception as expected");
                }
-               URI uri = new URI("http://user:pass@host:443/context/path#fragment");
+               URI uri = new URI("http://user:pass@host:443/arraycontext/path#fragment");
                asdc.setUri(uri);
                Assert.assertNotNull(asdc.getUri());
+               Assert.assertEquals("user", asdc.getUser());
+               Assert.assertEquals("pass", asdc.getPassword());
+               Assert.assertEquals("fragment", asdc.getInstanceId());
+               asdc.setInstanceId("somethingelse");
+               Assert.assertEquals("somethingelse", asdc.getInstanceId());
+               Assert.assertEquals("/asdc/", asdc.getRootPath());
+               asdc.setRootPath("/cdsa/");
+               Assert.assertEquals("/cdsa/", asdc.getRootPath());
+               asdc.setRootPath("/asdc/");
+               try {
+                       // lists
+                       asdc.getResources().waitForResult();
+                       asdc.getResources(JSONArray.class).waitForResult();
+                       asdc.getResources("category", "subcategory").waitForResult();
+                       asdc.getResources(JSONArray.class, "category", "subcategory").waitForResult();
+                       asdc.getServices().waitForResult();
+                       asdc.getServices(JSONArray.class).waitForResult();
+                       asdc.getServices("category", "subcategory").waitForResult();
+                       asdc.getServices(JSONArray.class, "category", "subcategory").waitForResult();
+                       asdc.getAssetsAction(ASDC.AssetType.service, JSONArray.class).execute().waitForResult();
+                       asdc.getAssetsAction(ASDC.AssetType.service, JSONArray.class, "category", "subcategory", "resourcetype").execute().waitForResult();
+                       // objects
+                       asdc.setUri(new URI("http://user:pass@host:443/objectcontext/path#fragment"));
+                       asdc.getResource(someuuid).waitForResult();
+                       asdc.getResource(someuuid, JSONObject.class).waitForResult();
+                       asdc.getService(someuuid).waitForResult();
+                       asdc.getService(someuuid, JSONObject.class).waitForResult();
+                       asdc.getAssetAction(ASDC.AssetType.service, someuuid, JSONObject.class).execute().waitForResult();
+                       asdc.checkoutResource(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.checkoutService(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.checkinResource(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.checkinService(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.certifyResource(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.certifyService(someuuid, "someuser", "somemessage").waitForResult();
+                       asdc.createResourceArtifact(someuuid)
+                               .withEncodedContent("AAAA")
+                               .withContent("xx".getBytes())
+                               .withLabel("abc")
+                               .withName("def")
+                               .withDisplayName("Displaydef")
+                               .withType(ASDC.ArtifactType.DCAE_JSON)
+                               .withGroupType(ASDC.ArtifactGroupType.INFORMATIONAL)
+                               .withDescription("xyz")
+                               .withOperator("them")
+                               .execute().waitForResult();
+                       asdc.createServiceArtifact(someuuid);
+                       asdc.createResourceInstanceArtifact(someuuid, "instance");
+                       asdc.createServiceInstanceArtifact(someuuid, "instance");
+                       JSONObject xobj = new JSONObject();
+                       xobj.put("artifactUUID", someuuid.toString());
+                       xobj.put("artifactType", "DCAE_JSON");
+                       xobj.put("artifactGroupType", "INFORMATIONAL");
+                       xobj.put("artifactLabel", "abc");
+                       asdc.updateResourceArtifact(someuuid, xobj)
+                               .withEncodedContent("AAAA")
+                               .withContent("xx".getBytes())
+                               .withDescription("xyz")
+                               .withName("def")
+                               .withOperator("them")
+                               .execute().waitForResult();
+                       asdc.updateServiceArtifact(someuuid, new JSONObject());
+                       asdc.updateResourceInstanceArtifact(someuuid, "instance", new JSONObject());
+                       asdc.updateServiceInstanceArtifact(someuuid, "instance", new JSONObject());
+                       asdc.deleteResourceArtifact(someuuid, someuuid)
+                               .withOperator("them")
+                               .execute().waitForResult();
+                       asdc.deleteResourceInstanceArtifact(someuuid, "instance", someuuid);
+                       asdc.deleteServiceArtifact(someuuid, someuuid);
+                       asdc.deleteServiceInstanceArtifact(someuuid, "instance", someuuid);
+                       asdc.createVFCMT()
+                               .withName("abc")
+                               .withDescription("xyz")
+                               .withVendorName("AAA")
+                               .withVendorRelease("1.0")
+                               .withTags("tag1", "tag2")
+                               .withIcon("iconic")
+                               .withOperator("them")
+                               .execute().waitForResult();
+                       asdc.createVF()
+                               .withCategory("cat5")
+                               .withSubCategory("e")
+                               .withName("abc")
+                               .withDescription("xyz")
+                               .withVendorName("AAA")
+                               .withVendorRelease("1.0")
+                               .withTags("tag1")
+                               .withIcon("ball")
+                               .withOperator("them")
+                               .execute().waitForResult();
+                       // raw bytes
+                       asdc.setUri(new URI("http://user:pass@host:443/bytescontext/path#fragment"));
+                       asdc.getResourceArchive(someuuid).waitForResult();
+                       asdc.getServiceArchive(someuuid).waitForResult();
+                       asdc.getAssetArchiveAction(ASDC.AssetType.resource, someuuid).execute().waitForResult();
+                       asdc.getResourceArtifact(someuuid, someuuid, byte[].class).waitForResult();
+                       asdc.getServiceArtifact(someuuid, someuuid, byte[].class).waitForResult();
+                       asdc.getResourceInstanceArtifact(someuuid, someuuid, "instance", byte[].class).waitForResult();
+                       asdc.getServiceInstanceArtifact(someuuid, someuuid, "instance", byte[].class).waitForResult();
+                       asdc.getAssetArtifactAction(ASDC.AssetType.resource, someuuid, someuuid, byte[].class).execute().waitForResult();
+                       asdc.getAssetInstanceArtifactAction(ASDC.AssetType.resource, someuuid, "instance", someuuid, byte[].class).execute().waitForResult();
+               } catch (Exception e) {
+                       e.printStackTrace();
+                       throw e;
+               }
        }
 
        @Test
index 2f4a799..e078ef7 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
@@ -32,7 +32,10 @@ import org.acumos.cds.domain.MLPArtifact;
 import org.acumos.cds.domain.MLPPeer;
 import org.acumos.cds.domain.MLPSolution;
 import org.acumos.cds.domain.MLPSolutionRevision;
+import org.acumos.federation.gateway.cds.Artifact;
+import org.acumos.federation.gateway.cds.Document;
 import org.acumos.federation.gateway.cds.Solution;
+import org.acumos.federation.gateway.cds.SolutionRevision;
 import org.acumos.federation.gateway.security.Peer;
 import org.acumos.federation.gateway.security.Role;
 import org.acumos.federation.gateway.service.CatalogService;
@@ -100,8 +103,15 @@ public class CatalogServiceTest extends ServiceTest {
                registerMockResponse("GET /ccds/solution/search/date?atc=PB&inst=1531747662000&active=true&page=1&size=100", MockResponse.success("mockCDSDateSolutionsResponsePage1.json"));
                registerMockResponse("GET /ccds/solution/10101010-1010-1010-1010-101010101010", MockResponse.success("mockCDSSolutionResponse.json"));
                registerMockResponse("GET /ccds/solution/10101010-1010-1010-1010-101010101010/revision", MockResponse.success("mockCDSSolutionRevisionsResponse.json"));
+               registerMockResponse("GET /ccds/solution/38efeef1-e4f4-4298-9f68-6f0052d6ade9/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341", MockResponse.success("mockCDSSolutionRevisionResponse.json"));
+               registerMockResponse("GET /ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341", MockResponse.success("mockCDSSolutionRevisionResponse.json"));
                registerMockResponse("GET /ccds/solution/10101010-1010-1010-1010-101010101010/pic", MockResponse.success("mockCDSSolutionPicResponse.tgz"));
                registerMockResponse("GET /ccds/revision/a0a0a0a0-a0a0-a0a0-a0a0-a0a0a0a0a0a0/artifact", MockResponse.success("mockCDSSolutionRevisionArtifactsResponse.json"));
+               registerMockResponse("GET /ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/artifact", MockResponse.success("mockCDSSolutionRevisionArtifactsResponse.json"));
+               registerMockResponse("GET /ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/access/PB/document", MockResponse.success("mockCDSSolutionRevisionDocumentsResponse.json"));
+               registerMockResponse("GET /ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/access/PB/descr", MockResponse.success("mockCDSSolutionRevisionDescriptionResponse.json"));
+               registerMockResponse("GET /ccds/artifact/2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b341", MockResponse.success("mockCDSSolutionRevisionArtifactResponse.json"));
+               registerMockResponse("GET /ccds/document/2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342", MockResponse.success("mockCDSSolutionRevisionDocumentResponse.json"));
                registerMockResponse("GET /ccds/solution/f0f0f0f0-f0f0-f0f0-f0f0-f0f0f0f0f0f0", new MockResponse(400, "Error", "mockCDSNoEntryWithIDResponse.json"));
                registerMockResponse("GET /ccds/solution/f0f0f0f0-f0f0-f0f0-f0f0-f0f0f0f0f0f0/revision", new MockResponse(400, "Error", "mockCDSNoEntryWithIDResponse.json"));
                registerMockResponse("GET /ccds/revision/f0f0f0f0-f0f0-f0f0-f0f0-f0f0f0f0f0f0/artifact", new MockResponse(400, "Error", "mockCDSNoEntryWithIDResponse.json"));
@@ -134,6 +144,9 @@ public class CatalogServiceTest extends ServiceTest {
                        assertTrue("Unexpected solutions count: " + solutions.size(), solutions.size() == 2);
                        solutions = catalog.getSolutions(selector("catalogId", "mycatalog", "solutionId", "38efeef1-e4f4-4298-9f68-6f0052d6ade9"), selfService);
                        assertTrue("Unexpected solutions count: " + solutions.size(), solutions.size() == 1);
+                       SolutionRevision rev = catalog.getSolutionRevision("38efeef1-e4f4-4298-9f68-6f0052d6ade9", "2c7e4481-6e6f-47d9-b7a4-c4e674d2b341");
+                       Artifact art = catalog.getSolutionRevisionArtifact("2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b341");
+                       Document doc = catalog.getSolutionRevisionDocument("2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342");
                        try {
                                catalog.getSolutions(selector("catalogId", "mycatalog", "name", new CopyOnWriteArrayList(new String[] { "A", "B" })), selfService);
                                assertTrue("Expected service exception, got none", 1 == 0);
diff --git a/gateway/src/test/java/org/acumos/federation/gateway/test/ContentServiceTest.java b/gateway/src/test/java/org/acumos/federation/gateway/test/ContentServiceTest.java
new file mode 100644 (file)
index 0000000..5d906a5
--- /dev/null
@@ -0,0 +1,325 @@
+/*-
+ * ===============LICENSE_START=======================================================
+ * Acumos
+ * ===================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * ===================================================================================
+ * This Acumos software file is distributed by AT&T and Tech Mahindra
+ * 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
+ *
+ * This file 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.acumos.federation.gateway.test;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.invocation.InvocationOnMock;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.when;
+import org.junit.Before;
+import org.junit.FixMethodOrder;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+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.mock.mockito.MockBean;
+import org.springframework.core.io.InputStreamResource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.RequestEntity;
+import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.ContextHierarchy;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.client.RestTemplate;
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.async.ResultCallback;
+import com.github.dockerjava.api.model.AuthConfig;
+import com.github.dockerjava.api.model.Image;
+import com.github.dockerjava.api.model.PushResponseItem;
+import com.github.dockerjava.api.command.ListImagesCmd;
+import com.github.dockerjava.api.command.LoadImageCmd;
+import com.github.dockerjava.api.command.PullImageCmd;
+import com.github.dockerjava.api.command.PushImageCmd;
+import com.github.dockerjava.api.command.RemoveImageCmd;
+import com.github.dockerjava.api.command.SaveImageCmd;
+import com.github.dockerjava.api.command.TagImageCmd;
+import com.github.dockerjava.core.command.PullImageResultCallback;
+
+import org.acumos.federation.gateway.config.DockerConfiguration;
+import org.acumos.federation.gateway.config.LocalInterfaceConfiguration;
+import org.acumos.federation.gateway.config.NexusConfiguration;
+import org.acumos.federation.gateway.service.ContentService;
+import org.acumos.federation.gateway.service.ServiceException;
+import org.acumos.federation.gateway.cds.Artifact;
+import org.acumos.federation.gateway.cds.Document;
+
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(
+    classes = org.acumos.federation.gateway.Application.class,
+    webEnvironment = WebEnvironment.RANDOM_PORT,
+    properties = {
+       "spring.main.allow-bean-definition-overriding=true",
+       "federation.instance=gateway",
+       "federation.instance.name=test",
+       "federation.operator=admin",
+       "codes-local.source=classpath:test-codes.json",
+       "peers-local.source=classpath:test-peers.json",
+       "catalog-local.source=classpath:test-catalog.json",
+       "federation.ssl.key-store=classpath:acumosa.pkcs12",
+       "federation.ssl.key-store-password=acumosa",
+       "federation.ssl.key-store-type=PKCS12",
+       "federation.ssl.key-password = acumosa",
+       "federation.ssl.trust-store=classpath:acumosTrustStore.jks",
+       "federation.ssl.trust-store-password=acumos",
+       "federation.ssl.client-auth=need",
+       "local.addr=127.0.0.1",
+       "local.server.port=9011",
+       "local.ssl.key-store=classpath:acumosa.pkcs12",
+       "local.ssl.key-store-password=acumosa",
+       "local.ssl.key-store-type=PKCS12",
+       "local.ssl.key-password=acumosa",
+       "cdms.client.url=http://localhost:8000/ccds",
+       "cdms.client.username=username",
+       "cdms.client.password=password"
+})
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class ContentServiceTest        extends ServiceTest {
+
+       @MockBean
+       private NexusConfiguration nexusConfig;
+
+       @Mock
+       private RestTemplate nexusClient;
+
+       @MockBean
+       private DockerConfiguration dockerConfig;
+
+       @Autowired
+       private LocalInterfaceConfiguration localIfConfig;
+
+       @Autowired
+       private ContentService contentService;
+
+       @Mock
+       private DockerClient dockerClient;
+
+       @Mock
+       private ListImagesCmd listImagesCmd;
+
+       @Mock
+       private LoadImageCmd loadImageCmd;
+
+       @Mock
+       private PullImageCmd pullImageCmd;
+
+       @Mock
+       private PushImageCmd pushImageCmd;
+
+       @Mock
+       private RemoveImageCmd removeImageCmd;
+
+       @Mock
+       private SaveImageCmd saveImageCmd;
+
+       @Mock
+       private TagImageCmd tagImageCmd;
+
+       private String dockerRegistryUrl = "dockerhost.example.com";
+
+       private static Image makeImage(String id, String... tags) {
+               Image ret = new Image();
+               ReflectionTestUtils.setField(ret, "id", id);
+               ReflectionTestUtils.setField(ret, "repoTags", tags);
+               return(ret);
+       }
+
+       private List<Image> dockerImages = Arrays.asList(new Image[] {
+           makeImage("abc", "repo2.example.org/name:1.0"),
+           makeImage("def", "repo1.example.org/thatone:latest", "repo1.example.org/thatone:1.0")
+       });
+       private AuthConfig dockerAuthConfig = new AuthConfig()
+           .withUsername("username")
+           .withPassword("password")
+           .withEmail("someone@example.com")
+           .withRegistryAddress("http://" + dockerRegistryUrl + "/v2/");
+
+       protected void initMockResponses() throws IOException {
+               registerMockResponse("GET /ccds/peer/search?self=true&_j=a&page=0&size=100", MockResponse.success("mockCDSPeerSearchSelfResponse.json"));
+               registerMockResponse("GET /ccds/code/pair/ARTIFACT_TYPE", MockResponse.success("mockCDSArtifactTypeResponse.json"));
+
+               when(dockerConfig.getAuthConfig()).thenReturn(dockerAuthConfig);
+               when(dockerConfig.getRegistryUrl()).thenReturn(dockerRegistryUrl);
+
+               when(dockerConfig.getDockerClient()).thenReturn(dockerClient);
+                 when(dockerClient.listImagesCmd()).thenReturn(listImagesCmd);
+                   when(listImagesCmd.exec()).thenReturn(dockerImages);
+                 when(dockerClient.loadImageCmd(any(InputStream.class))).thenReturn(loadImageCmd);
+                   //when(loadImageCmd.exec()).doNothing();
+                 when(dockerClient.pullImageCmd(any(String.class))).thenReturn(pullImageCmd);
+                   when(pullImageCmd.exec(any(PullImageResultCallback.class))).thenAnswer(invoke -> {
+                       PullImageResultCallback cb = (PullImageResultCallback)invoke.getArguments()[0];
+                       cb.onStart(null);
+                       cb.onComplete();
+                       return(null);
+                   });
+                 when(dockerClient.pushImageCmd(any(String.class))).thenReturn(pushImageCmd);
+                   when(pushImageCmd.withAuthConfig(any(AuthConfig.class))).thenReturn(pushImageCmd);
+                   when(pushImageCmd.withTag(any(String.class))).thenReturn(pushImageCmd);
+                   when(pushImageCmd.exec(any(ResultCallback.class))).thenAnswer(invoke -> {
+                       ResultCallback cb = (ResultCallback)invoke.getArguments()[0];
+                       cb.onStart(null);
+                       PushResponseItem pri = new PushResponseItem();
+                       cb.onNext(pri);
+                       cb.onComplete();
+                       return(cb);
+                   });
+                 when(dockerClient.removeImageCmd(any(String.class))).thenReturn(removeImageCmd);
+                   when(removeImageCmd.withForce(any(Boolean.class))).thenReturn(removeImageCmd);
+                   // when(removeImageCmd.exec()) do nothing
+                 when(dockerClient.saveImageCmd(any(String.class))).thenAnswer(invoke -> {
+                       String uri = (String)invoke.getArguments()[0];
+                       if (uri.contains("Rainy_Day_Case")) {
+                               throw new IOException("Rainy Day Case");
+                       }
+                       return(saveImageCmd);
+                   });
+                   when(saveImageCmd.exec()).thenAnswer(invoke -> new ByteArrayInputStream("Hello World".getBytes()));
+                 when(dockerClient.tagImageCmd(any(String.class), any(String.class), any(String.class))).thenReturn(tagImageCmd);
+                   // when(tagImageCmd.exec()) do nothing
+       
+               when(nexusConfig.getNexusClient()).thenReturn(nexusClient);
+               when(nexusConfig.getGroupId()).thenReturn("com.artifact");
+               when(nexusConfig.getNameSeparator()).thenReturn(".");
+               when(nexusConfig.getUrl()).thenReturn("http://somehost.example.org/");
+               when(nexusClient.exchange(any(RequestEntity.class),any(Class.class))).thenReturn(new ResponseEntity<Resource>(new InputStreamResource(new ByteArrayInputStream("hello".getBytes())), HttpStatus.OK));
+       }
+
+       @Test
+       public void testNexusArtifacts() throws Exception {
+               Artifact artifact = new Artifact();
+               artifact.setUri("com/artifact/6793411f-c7a1-4e93-85bc-f91d267541d8/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/artifact/1.0/artifact-1.0.log");
+               artifact.setArtifactTypeCode("DS");
+               contentService.getArtifactContent("sid", "rid", artifact).getInputStream().close();
+               artifact = new Artifact();
+               artifact.setArtifactTypeCode("DS");
+               artifact.setName("artifact.log");
+               artifact.setVersion("1.0");
+               contentService.putArtifactContent("sid", "rid", artifact, new InputStreamResource(new ByteArrayInputStream("xxx".getBytes())));
+       }
+
+
+       @Test
+       public void testDockerArtifacts() throws Exception {
+               System.out.println(contentService);
+               Artifact artifact = new Artifact();
+               artifact.setArtifactTypeCode("DI");
+               try {
+                       contentService.getArtifactContent("sid", "rid", artifact).getInputStream().close();
+                       fail("Expected ServiceException");
+               } catch (ServiceException se) {
+                       // We want this
+               }
+               try {
+                       artifact.setUri("Rainy_Day_Case");
+                       contentService.getArtifactContent("sid", "rid", artifact).getInputStream().close();
+                       fail("Expected ServiceException");
+               } catch (ServiceException se) {
+                       // We want this
+               }
+               artifact.setUri("com/artifact/6793411f-c7a1-4e93-85bc-f91d267541d8/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/artifact/1.0/artifact-1.0.log");
+               contentService.getArtifactContent("sid", "rid", artifact).getInputStream().close();
+               artifact = new Artifact();
+               artifact.setArtifactTypeCode("DI");
+               artifact.setName("thatone");
+               artifact.setVersion("1.0");
+               artifact.setDescription("repo1.example.org/thatone:1.0");
+               contentService.putArtifactContent("sid", "rid", artifact, new InputStreamResource(new ByteArrayInputStream("xxx".getBytes())));
+               assertEquals("dockerhost.example.com/thatone_sid:1.0", artifact.getUri());
+               try {
+                       artifact.setDescription("repo1.example.org/notthere:9.9");
+                       contentService.putArtifactContent("sid", "rid", artifact, new InputStreamResource(new ByteArrayInputStream("xxx".getBytes())));
+                       fail("Expected ServiceException");
+               } catch (ServiceException se) {
+                       // We want this
+               }
+       }
+
+
+       @Test
+       public void testDocuments() throws Exception {
+               Document document = new Document();
+               try {
+                       contentService.getDocumentContent("sid", "rid", document).getInputStream().close();
+                       fail("Expected ServiceException");
+               } catch (ServiceException se) {
+                       // We want this
+               }
+               document.setUri("com/artifact/6793411f-c7a1-4e93-85bc-f91d267541d8/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/document/PB/document-PB.txt");
+               contentService.getDocumentContent("sid", "rid", document).getInputStream().close();
+               document = new Document();
+               document.setName("thatone");
+               contentService.putDocumentContent("sid", "rid", document, new InputStreamResource(new ByteArrayInputStream("xxx".getBytes())));
+               assertEquals("com/artifact/sid/rid/thatone/PB/thatone-PB.", document.getUri());
+       }
+
+       @Test
+       public void testDockerConfig() throws Exception {
+               DockerConfiguration dc = new DockerConfiguration();
+               dc.setHost("tcp://dockerhost.example.com:4243");
+               dc.setApiVersion("v2");
+               dc.setRegistryUsername("username");
+               dc.getRegistryUsername();
+               dc.setRegistryPassword("password");
+               dc.setRegistryEmail("username@example.com");
+               dc.setRegistryUrl("someregistry:1234");
+               dc.getRegistryUrl();
+               dc.setDockerCertPath(null);
+               dc.setDockerConfig(null);
+               dc.setDockerTlsVerify(false);
+               dc.getAuthConfig();
+               dc.getDockerClient();
+       }
+
+       @Test
+       public void testNexusConfig() throws Exception {
+               NexusConfiguration nc = new NexusConfiguration();
+               ReflectionTestUtils.setField(nc, "localIfConfig", localIfConfig);
+               nc.setId("someid");
+               nc.setUrl("https://somenexus.example.org");
+               assertEquals("https://somenexus.example.org/", nc.getUrl());
+               nc.setUrl("https://somenexus.example.org/");
+               assertEquals("https://somenexus.example.org/", nc.getUrl());
+               nc.setUrl("https://somenexus.example.org//");
+               assertEquals("https://somenexus.example.org/", nc.getUrl());
+               nc.setUrl("https://somenexus.example.org///");
+               assertEquals("https://somenexus.example.org/", nc.getUrl());
+               nc.setUsername("somename");
+               nc.setPassword("pw");
+               nc.setProxy("deprecated");
+               nc.setGroupId("a.b");
+               nc.getGroupId();
+               nc.setNameSeparator(".");
+               nc.getNameSeparator();
+               nc.getNexusClient();
+       }
+}
index bd90396..56d5c08 100644 (file)
@@ -22,12 +22,14 @@ package org.acumos.federation.gateway.test;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
 import java.util.Collections;
 import java.util.List;
 import java.util.Scanner;
 
 import org.acumos.cds.domain.MLPArtifact;
+import org.acumos.cds.domain.MLPDocument;
 import org.acumos.cds.domain.MLPPeer;
 import org.acumos.cds.domain.MLPSolution;
 import org.acumos.cds.domain.MLPSolutionRevision;
@@ -88,118 +90,138 @@ import org.springframework.test.context.junit4.SpringRunner;
 public class ControllerTest {
 
        private final Logger log = LoggerFactory.getLogger(getClass().getName());
+       private static final String SELFID = "acumosa";
+       private static final String PEERID = "acumosb";
+       private static final String UNREGISTEREDID = "acumosc";
+
        @Autowired
        private TestRestTemplate restTemplate;
+
        @Value("${local.server.port}")
-       int port;
+       private int port;
+
+       public void setClient(String id) {
+               ((HttpComponentsClientHttpRequestFactory)this.restTemplate.getRestTemplate().getRequestFactory()).setHttpClient(prepareHttpClient(id));
+       }
+
+       private <T> void assertGoodResponse(String testname, ResponseEntity<T> response) {
+               if (response != null)   {
+                       log.info("{}: {}", testname, response.getBody());
+                       log.info("{}: {}", testname, response);
+               }
+               assertNotNull(response);
+               assertEquals(200, response.getStatusCodeValue());
+       }
+
+       private <T> void assertGoodResponseWith(String testname, ResponseEntity<JsonResponse<T>> response, java.util.function.Predicate<T> fcn) {
+               assertGoodResponse(testname, response);
+               assertTrue(fcn.test(response.getBody().getContent()));
+       }
 
        @Test
-       public void testSolutions() {
+       public void testPeers() {
+               setClient(SELFID);
+
+               ResponseEntity<JsonResponse<List<MLPPeer>>> response =
+                       this.restTemplate.exchange("https://localhost:" + this.port + "/peers", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPPeer>>>() {});
+               
+               assertGoodResponse("testPeers", response);
+       }
+
+       @Test
+       public void testPing() {
+               setClient(PEERID);
 
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               ResponseEntity<JsonResponse<MLPPeer>> response =
+                       this.restTemplate.exchange("https://localhost:" + this.port + "/ping", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {});
+               
+               assertGoodResponse("testPing", response);
+       }
+
+       @Test
+       public void testSolutions() {
+               setClient(PEERID);
                
                ResponseEntity<JsonResponse<List<MLPSolution>>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/solutions", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPSolution>>>() {});
                
-               if (response != null)   {
-                       log.info("testSolutions: {}", response.getBody());
-                       log.info("testSolutions: {}", response);
-               }
-               
-               assertNotNull(response);
-               assertEquals(200, response.getStatusCodeValue());
-               assertEquals(1, response.getBody().getContent().size());
+               assertGoodResponseWith("testSolutions", response, content -> content.size() == 1);
        }
 
 
        @Test
        public void testSolutionSuccess() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<MLPSolution>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPSolution>>() {} );
        
-               if (response != null)   {
-                       log.info("testSolution: {}", response.getBody());
-                       log.info("testSolution: {}", response);
-               }
-
-               assertNotNull(response);
-               assertEquals(200, response.getStatusCodeValue());
-               assertEquals("CL", response.getBody().getContent().getModelTypeCode()); //no errors
+               assertGoodResponseWith("testSolutionSuccess", response, content -> content.getModelTypeCode().equals("CL"));
        }
 
        @Test
        public void testSolutionRevisionsSuccess() {
-    
-               ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<List<MLPSolutionRevision>>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPSolutionRevision>>>() {});
                
-               if (response != null)   {
-                       log.info("testSolutionRevisions: {}", response.getBody());
-                       log.info("testSolutionRevisions: {}", response);
-               }
-
-               assertNotNull(response);
-               assertEquals(200, response.getStatusCodeValue());
-               assertEquals(1, response.getBody().getContent().size()); //no errors
+               assertGoodResponseWith("testSolutionRevisionSuccess", response, content ->content.size() == 1);
        }
 
        @Test
        public void testSolutionRevisionSuccess() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<MLPSolution>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions/01010101-0101-0101-0101-010101010101", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPSolution>>() {} );
        
-               if (response != null)   {
-                       log.info("testSolutionRevision: {}", response.getBody());
-                       log.info("testSolutionRevision: {}", response);
-               }
-
-               assertNotNull(response);
-               assertEquals(200, response.getStatusCodeValue());
-               assertEquals("admin", response.getBody().getContent().getUserId()); //no errors
+               assertGoodResponseWith("testSolutionRevision", response, content -> content.getUserId().equals("admin"));
        }
 
        @Test
        public void testSolutionRevisionArtifactsSuccess() {
-    
-               ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<List<MLPArtifact>>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions/01010101-0101-0101-0101-010101010101/artifacts", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPArtifact>>>() {});
                
-               if (response != null)   {
-                       log.info("testSolutionRevisionArtifacts: {}", response.getBody());
-                       log.info("testSolutionRevisionArtifacts: {}", response);
-               }
+               assertGoodResponseWith("testSolutionRevisionArtifacts", response, content -> content.size() == 1);
+       }
 
-               Assert.assertNotNull(response);
-               Assert.assertEquals(200, response.getStatusCodeValue());
-               Assert.assertEquals(1, response.getBody().getContent().size()); //no errors
+       @Test
+       public void testSolutionRevisionArtifactContentSuccess() {
+               setClient(PEERID);
+
+               ResponseEntity<byte[]> response =
+                       this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions/01010101-0101-0101-0101-010101010101/artifacts/a0a0a0a0-a0a0-a0a0-a0a0-a0a0a0a0a0a0/content", HttpMethod.GET, prepareBinaryRequest(), new ParameterizedTypeReference<byte[]>() {});
+               
+               assertGoodResponse("testSolutionRevisionArtifact", response);
+       }
+
+       @Test
+       public void testSolutionRevisionDocumentsSuccess() {
+               setClient(PEERID);
+
+               ResponseEntity<JsonResponse<List<MLPDocument>>> response =
+                       this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions/01010101-0101-0101-0101-010101010101/documents", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPDocument>>>() {});
+               
+               assertGoodResponseWith("testSolutionRevisionDocuments", response, content -> content.size() == 1);
+       }
+
+       @Test
+       public void testSolutionRevisionDocumentContentSuccess() {
+               setClient(PEERID);
+
+               ResponseEntity<byte[]> response =
+                       this.restTemplate.exchange("https://localhost:" + this.port + "/solutions/00000000-0000-0000-0000-000000000000/revisions/01010101-0101-0101-0101-010101010101/documents/2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342/content", HttpMethod.GET, prepareBinaryRequest(), new ParameterizedTypeReference<byte[]>() {});
+               
+               assertGoodResponse("testSolutionRevisionDocumentContent", response);
        }
        
        @Test
        public void testRegister() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient("acumosc"));
+               setClient(UNREGISTEREDID);
 
                ResponseEntity<JsonResponse<MLPPeer>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/peer/register", HttpMethod.POST, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {} );
@@ -225,10 +247,7 @@ public class ControllerTest {
 
        @Test
        public void testUnregister() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient("acumosb"));
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<MLPPeer>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/peer/unregister", HttpMethod.POST, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {} );
@@ -243,10 +262,7 @@ public class ControllerTest {
 
        @Test
        public void testUnregisterNonExistent() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient("acumosc"));
+               setClient("acumosc");
 
                ResponseEntity<JsonResponse<MLPPeer>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/peer/unregister", HttpMethod.POST, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {} );
@@ -262,10 +278,7 @@ public class ControllerTest {
 
        @Test
        public void testPeersForbidden() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRestTemplate().getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               setClient(PEERID);
 
                ResponseEntity<JsonResponse<List<MLPPeer>>> response =
                        this.restTemplate.exchange("https://localhost:" + this.port + "/peers", HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPPeer>>>() {} );
@@ -295,9 +308,12 @@ public class ControllerTest {
                headers.setContentType(MediaType.APPLICATION_JSON);
                return new HttpEntity<String>(headers);
        }
-
-       private HttpClient prepareHttpClient() {
-               return prepareHttpClient("acumosb");
+       
+       private HttpEntity prepareBinaryRequest() {
+               HttpHeaders headers = new HttpHeaders();
+               headers.setAccept(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
+               headers.setContentType(MediaType.APPLICATION_JSON);
+               return new HttpEntity<String>(headers);
        }
 
        private HttpClient prepareHttpClient(String theIdentity) {
@@ -305,7 +321,6 @@ public class ControllerTest {
                                                                .withSSL(new SSLBuilder()
                                                                                                                        .withKeyStore("classpath:/" + theIdentity + ".pkcs12")
                                                                                                                        .withKeyStorePassword(theIdentity)
-                                                                                                                       //.withKeyPassword("acumosb")
                                                                                                                        .withTrustStore("classpath:/acumosTrustStore.jks")
                                                                                                                        .withTrustStoreType("JKS")
                                                                                                                        .withTrustStorePassword("acumos")
index d84b189..39fa258 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos Apache-2.0
  * ===================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
  */
 package org.acumos.federation.gateway.test;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.when;
 
 import java.io.IOException;
+import java.net.URI;
 import java.util.List;
+import java.util.HashMap;
 import java.util.Scanner;
 
 import org.acumos.cds.domain.MLPPeer;
 import org.acumos.cds.domain.MLPSolution;
+import org.acumos.federation.gateway.common.API;
 import org.acumos.federation.gateway.common.Clients;
 import org.acumos.federation.gateway.common.FederationClient;
+import org.acumos.federation.gateway.common.FederationException;
 import org.acumos.federation.gateway.common.JsonResponse;
+import org.acumos.federation.gateway.common.JsonRequest;
+import org.acumos.federation.gateway.common.PeerException;
 import org.acumos.federation.gateway.config.InterfaceConfigurationBuilder;
 import org.acumos.federation.gateway.config.InterfaceConfigurationBuilder.SSLBuilder;
+import org.acumos.federation.gateway.config.InterfaceConfiguration;
+import org.acumos.federation.gateway.service.PeerService;
 import org.apache.http.HttpResponse;
 import org.apache.http.ProtocolVersion;
 import org.apache.http.client.HttpClient;
@@ -53,21 +64,25 @@ import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
 import org.springframework.boot.test.mock.mockito.MockBean;
 import org.springframework.core.ParameterizedTypeReference;
 import org.springframework.core.io.ClassPathResource;
+import org.springframework.core.io.Resource;
 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.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.test.context.ContextConfiguration;
 import org.springframework.test.context.ContextHierarchy;
 import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.client.HttpStatusCodeException;
 import org.springframework.web.client.HttpClientErrorException;
 import org.springframework.web.client.RestTemplate;
 
@@ -112,8 +127,21 @@ import org.springframework.web.client.RestTemplate;
 public class LocalControllerTest {
 
        private final Logger log = LoggerFactory.getLogger(getClass().getName());
-//     @Autowired
-//     private TestRestTemplate restTemplate;
+
+       private static class XFederationClient extends FederationClient {
+
+               public XFederationClient(String theTarget, HttpClient theClient) {
+                       super(theTarget, theClient);
+               }
+
+               public Resource xdownload(URI theUri) throws FederationException {
+                       return download(theUri);
+               }
+               public void xsetTarget(String theTarget) {
+                       setTarget(theTarget);
+               }
+       }
+
 
        private RestTemplate    restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
        
@@ -126,101 +154,33 @@ public class LocalControllerTest {
        @MockBean(name = "clients")
        private Clients clients;
 
+       @Autowired
+       private PeerService peerService;
+
+       private MockAnswer peerAnswer = new MockAnswer();
+
        @Before
        public void initLocalTests() throws IOException {
 
                MockitoAnnotations.initMocks(this);
 
-               BasicHttpResponse mockSolutionsResponse = 
-                       new BasicHttpResponse(
-                               new BasicStatusLine(
-                                       new ProtocolVersion("HTTP",1,1), 200, "Success"));
-               ClassPathResource mockSolutions =
-                       new ClassPathResource("mockPeerSolutionsResponse.json");
-               mockSolutionsResponse.setEntity(
-                       new InputStreamEntity(mockSolutions.getInputStream()));
-               mockSolutionsResponse
-                       .addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
-               mockSolutionsResponse
-                       .addHeader("Content-Length", String.valueOf(mockSolutions.contentLength()));
-
-               BasicHttpResponse mockSolutionResponse = 
-                       new BasicHttpResponse(
-                               new BasicStatusLine(
-                                       new ProtocolVersion("HTTP",1,1), 200, "Success"));
-               ClassPathResource mockSolution =
-                       new ClassPathResource("mockPeerSolutionResponse.json");
-               mockSolutionResponse.setEntity(
-                       new InputStreamEntity(mockSolution.getInputStream()));
-               mockSolutionResponse
-                       .addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
-               mockSolutionResponse
-                       .addHeader("Content-Length", String.valueOf(mockSolution.contentLength()));
-
-               BasicHttpResponse mockPingResponse = 
-                       new BasicHttpResponse(
-                               new BasicStatusLine(
-                                       new ProtocolVersion("HTTP",1,1), 200, "Success"));
-               ClassPathResource mockPing =
-                       new ClassPathResource("mockPeerPingResponse.json");
-               mockPingResponse.setEntity(
-                       new InputStreamEntity(mockPing.getInputStream()));
-               mockPingResponse
-                       .addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
-               mockPingResponse
-                       .addHeader("Content-Length", String.valueOf(mockPing.contentLength()));
-
-               BasicHttpResponse mockPeersResponse = 
-                       new BasicHttpResponse(
-                               new BasicStatusLine(
-                                       new ProtocolVersion("HTTP",1,1), 200, "Success"));
-               ClassPathResource mockPeers =
-                       new ClassPathResource("mockPeerPeersResponse.json");
-               mockPeersResponse.setEntity(
-                       new InputStreamEntity(mockPeers.getInputStream()));
-               mockPeersResponse
-                       .addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
-               mockPeersResponse
-                       .addHeader("Content-Length", String.valueOf(mockPeers.contentLength()));
-
-               BasicHttpResponse mockSubscriptionResponse = 
-                       new BasicHttpResponse(
-                               new BasicStatusLine(
-                                       new ProtocolVersion("HTTP",1,1), 200, "Success"));
-               ClassPathResource mockSubscription =
-                       new ClassPathResource("mockPeerSubscriptionResponse.json");
-               mockSubscriptionResponse.setEntity(
-                       new InputStreamEntity(mockSubscription.getInputStream()));
-               mockSubscriptionResponse
-                       .addHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
-               mockSubscriptionResponse
-                       .addHeader("Content-Length", String.valueOf(mockSubscription.contentLength()));
+               peerAnswer
+                       .mockResponse(info -> info.getPath().equals("/solutions"), MockResponse.success("mockPeerSolutionsResponse.json"))
+                       .mockResponse(info -> info.getPath().contains("/solutions/") && !info.getPath().contains("/revisions"), MockResponse.success("mockPeerSolutionResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/revisions"), MockResponse.success("mockPeerSolutionRevisionsResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/artifacts"), MockResponse.success("mockPeerSolutionRevisionArtifactsResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/documents"), MockResponse.success("mockPeerSolutionRevisionDocumentsResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/download"), MockResponse.success("mockPeerDownload.tgz"))
+                       .mockResponse(info -> info.getPath().endsWith("/ping"), MockResponse.success("mockPeerPingResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/peer/register"), MockResponse.success("mockPeerRegisterResponse.json"))
+                       .mockResponse(info -> info.getPath().endsWith("/peers"), MockResponse.success("mockPeerPeersResponse.json"))
+                       .mockResponse(info -> info.getPath().contains("/subscription/"), MockResponse.success("mockPeerSubscriptionResponse.json"));
 
                when(
                        this.federationClient.execute(
                                any(HttpUriRequest.class), any(HttpContext.class)
                        )
-               ).thenAnswer(new Answer<HttpResponse>() {
-                               public HttpResponse answer(InvocationOnMock theInvocation) {
-                                       HttpUriRequest req = (HttpUriRequest)
-                                               theInvocation.getArguments()[0];
-                                       String path = req.getURI().getPath();
-                                       log.warn("Mock path " + path);
-                                       if (path.equals("/solutions"))
-                                               return mockSolutionsResponse;
-                                       if (path.endsWith("/ping"))
-                                               return mockPingResponse;
-                                       if (path.endsWith("/peers"))
-                                               return mockPeersResponse;
-                                       if (path.contains("/solutions/"))
-                                               return mockSolutionResponse;
-                                       if (path.contains("/subscription/"))
-                                               return mockSubscriptionResponse;
-
-                                       log.warn(" *** Mock unhandled path " + path);
-                                       return null;
-                               }
-                       });
+               ).thenAnswer(peerAnswer);
 
                when(
                        this.clients.getFederationClient(
@@ -231,148 +191,188 @@ public class LocalControllerTest {
                        public FederationClient answer(InvocationOnMock theInvocation) {
                                //this should end up providing a client based on the mocked http
                                //client
-                               log.warn("Mock client for " + theInvocation.getArguments()[0]);
-                         return new FederationClient(
+                               log.warn("Mock client for {}", theInvocation.getArguments()[0]);
+                         return new XFederationClient(
                   (String)theInvocation.getArguments()[0]/*the URI*/,
                   federationClient);
                        }
                });
+               ((HttpComponentsClientHttpRequestFactory)this.restTemplate.getRequestFactory()).setHttpClient(prepareHttpClient());
+       }
+
+       private <T> void assertGoodResponse(String testname, ResponseEntity<JsonResponse<T>> response) {
+               if (response != null)   {
+                       log.info("{}: {}", testname, response.getBody());
+                       log.info("{}: {}", testname, response);
+               }
+               assertNotNull(response);
+               assertEquals(200, response.getStatusCodeValue());
+       }
+
+       private <T> void assertGoodResponseWith(String testname, ResponseEntity<JsonResponse<T>> response, java.util.function.Predicate<T> fcn) {
+               assertGoodResponse(testname, response);
+               assertTrue(fcn.test(response.getBody().getContent()));
+       }
+
+       private <T> void verifyFail(String url, HttpMethod meth, ParameterizedTypeReference<T> rtype, int code) {
+               try {
+                       log.info("testPeerNoSuch: {}", url);
+                       this.restTemplate.exchange(url, meth, prepareRequest(), rtype);
+                       fail("expected to fail");
+               } catch (HttpStatusCodeException httpx) {
+                       assertEquals(code, httpx.getStatusCode().value());
+               }
        }
 
        @Test
        public void testPeerSolutions() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
-               
                String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/solutions";
 
                log.info("testPeerSolutions: {}", url);
                ResponseEntity<JsonResponse<List<MLPSolution>>> response =
                        this.restTemplate.exchange(url, HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPSolution>>>() {});
                
-               if (response != null)   {
-                       log.info("testPeerSolutions: {}", response.getBody());
-                       log.info("testPeerSolutions: {}", response);
-               }
-               
-               assertTrue(response != null);
-               assertTrue(response.getStatusCodeValue() == 200);
-               assertTrue(response.getBody().getContent().size() == 1);
+               assertGoodResponseWith("testPeerSolutions", response, content -> content.size() == 1);
        }
 
 
        @Test
        public void testPeerSolution() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
-
                String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/solutions/00000000-0000-0000-0000-000000000000";
 
                log.info("testPeerSolution: {}", url);
                ResponseEntity<JsonResponse<MLPSolution>> response =
                        this.restTemplate.exchange(url, HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPSolution>>() {} );
        
-               if (response != null)   {
-                       log.info("testSolution: {}", response.getBody());
-                       log.info("testSolution: {}", response);
-               }
-
-               assertTrue(response != null);
-               assertTrue(response.getStatusCodeValue() == 200);
-               assertTrue(response.getBody().getContent().getModelTypeCode().equals("CL")); //no errors
+               assertGoodResponseWith("testPeerSolution", response, content -> content.getModelTypeCode().equals("CL"));
        }
 
        @Test
        public void testPeerPing() {
-    
-               ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
-
                String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/ping";
 
                log.info("testPeerPing: {}", url);
                ResponseEntity<JsonResponse<MLPPeer>> response =
                        this.restTemplate.exchange(url, HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {});
                
-               if (response != null)   {
-                       log.info("testPing: {}", response.getBody());
-                       log.info("testPing: {}", response);
-               }
-
-               assertTrue(response != null);
-               assertTrue(response.getStatusCodeValue() == 200);
-               assertTrue(response.getBody().getContent().getPeerId().equals("11111111-1111-1111-1111-111111111111")); //no errors
+               assertGoodResponseWith("testPeerPing", response, content -> content.getPeerId().equals("11111111-1111-1111-1111-111111111111"));
        }
 
        @Test
        public void testPeerPeers() {
-
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
-
                String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/peers";
                
                log.info("testPeerPeers: {}", url);
                ResponseEntity<JsonResponse<List<MLPPeer>>> response =
                        this.restTemplate.exchange(url, HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<List<MLPPeer>>>() {} );
        
-               if (response != null)   {
-                       log.info("testPeerPeers: {}", response.getBody());
-                       log.info("testPeerPeers: {}", response);
-               }
-
-               assertTrue(response != null);
-               assertTrue(response.getStatusCodeValue() == 200);
-               assertTrue(response.getBody().getContent().get(0).getName().startsWith("acumos")); //no errors
+               assertGoodResponseWith("testPeerPeers", response, content -> content.get(0).getName().startsWith("acumos"));
        }
 
        @Test
        public void testPeerSubscription() {
-    
-               ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
-
                String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/subscription/1";
 
                log.info("testPeerSubscription: {}", url);
                ResponseEntity<JsonResponse<String>> response =
                        this.restTemplate.exchange(url, HttpMethod.POST, prepareRequest(), new ParameterizedTypeReference<JsonResponse<String>>() {});
                
-               if (response != null)   {
-                       log.info("testPeerSubscription: {}", response.getBody());
-                       log.info("testPeerSubscription: {}", response);
-               }
-
-               assertTrue(response != null);
-               assertTrue(response.getStatusCodeValue() == 200);
+               assertGoodResponse("testPeerSubscription", response);
        }
 
        @Test
-       public void testPeerNoSuch() {
+       public void testPeerRegistration() {
+               String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111111/peer/register";
+               log.info("testPeerRegistration: {}", url);
+               ResponseEntity<JsonResponse<MLPPeer>> response =
+                       this.restTemplate.exchange(url, HttpMethod.POST, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {});
 
-    ((HttpComponentsClientHttpRequestFactory)
-                       this.restTemplate.getRequestFactory())
-                               .setHttpClient(prepareHttpClient());
+               assertGoodResponse("testPeerRegistration", response);
+       }
 
-               String url = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111112/ping";
+       @Test
+       public void testPeerNoSuch() {
+               String badpeer = "https://localhost:" + this.localPort + "/peer/11111111-1111-1111-1111-111111111112";
        
-               log.info("testPeerNoSuch: {}", url);
+               verifyFail(badpeer + "/ping", HttpMethod.GET, new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {}, 404);
+               verifyFail(badpeer + "/peers", HttpMethod.GET, new ParameterizedTypeReference<JsonResponse<List<MLPPeer>>>() {}, 500);
+               verifyFail(badpeer + "/solutions?selector=e30K", HttpMethod.GET, new ParameterizedTypeReference<JsonResponse<List<MLPSolution>>>() {}, 500);
+               verifyFail(badpeer + "/solutions/00000000-0000-0000-0000-000000000000", HttpMethod.GET, new ParameterizedTypeReference<JsonResponse<MLPSolution>>() {}, 500);
+       }
+
+       @Test
+       public void testFederationClient() throws Exception {
+               XFederationClient fedcli = (XFederationClient)clients.getFederationClient(peerService.getPeerById("11111111-1111-1111-1111-111111111111").getApiUrl());
+               fedcli.getSolutionRevisions("00000000-0000-0000-0000-000000000000");
+               fedcli.getArtifacts("00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000");
+               fedcli.getDocuments("00000000-0000-0000-0000-000000000000", "00000000-0000-0000-0000-000000000000");
+               fedcli.xdownload(new URI("https://localhost:" + this.localPort + "/download"));
                try {
-                       this.restTemplate.exchange(url, HttpMethod.GET, prepareRequest(), new ParameterizedTypeReference<JsonResponse<MLPPeer>>() {} );
-                       assertTrue("expected to fail", true);
+                       fedcli.xsetTarget(null);
+                       fail("Expected IllegalArgumentException");
+               } catch (IllegalArgumentException iae) {
+                       // We want this
                }
-               catch (HttpClientErrorException httpx) {
-                       assertTrue(httpx.getStatusCode().value() == 404);
+               try {
+                       fedcli.xsetTarget("a b c");
+                       fail("Expected IllegalArgumentException");
+               } catch (IllegalArgumentException iae) {
+                       // We want this
                }
        }
 
+       @Test
+       public void testAPI() {
+               assertEquals("/solutions", API.SOLUTIONS.path());
+               assertEquals("/solutions", API.SOLUTIONS.toString());
+               assertEquals(1, API.SOLUTIONS.query().length);
+               assertEquals(1, API.SOLUTIONS.queryParams(new HashMap()).size());
+               API.SOLUTIONS.uriBuilder("https://localhost");
+       }
+
+       @Test
+       public void testJsonRequest() {
+               JsonRequest<String> jr = new JsonRequest<String>();
+               jr.setRequestId("abc");
+               jr.setBody("def");
+               jr.setRequestFrom("ghi");
+               assertEquals("abc", jr.getRequestId());
+               assertEquals("def", jr.getBody());
+               assertEquals("ghi", jr.getRequestFrom());
+       }
+
+       @Test
+       public void testFederationException() throws Exception {
+               new FederationException("A string");
+               new FederationException(new URI("https://localhost"));
+       }
+
+       @Test
+       public void testPeerException() throws Exception {
+               HttpStatusCodeException hsce = new HttpClientErrorException(HttpStatus.BAD_REQUEST);
+
+               new PeerException(new URI("https://localhost"), hsce);
+               new PeerException("https://localhost", hsce);
+       }
+
+       @Test
+       public void testInterfaceConfiguration() throws Exception {
+               InterfaceConfiguration.Client cli = new InterfaceConfiguration.Client();
+               cli.setUsername("username");
+               cli.setPassword("password");
+               cli = new InterfaceConfiguration.Client(cli.getUsername(), cli.getPassword());
+               assertEquals("username", cli.getUsername());
+               assertEquals("password", cli.getPassword());
+               cli.toString();
+               InterfaceConfiguration ic = new InterfaceConfiguration();
+               ic.setAddress("localhost");
+               assertEquals("localhost", ic.getAddress());
+               ic.setClient(cli);
+               assertEquals(cli, ic.getClient());
+               assertTrue(ic.getSubjectName() == null);
+               ic.setSSL(new SSLBuilder().build());
+               assertEquals("need", ic.getSSL().getClientAuth());
+       }
 
        private HttpEntity prepareRequest(String theResourceName) {
                String content = new Scanner(
@@ -391,17 +391,18 @@ public class LocalControllerTest {
        }
 
        private HttpClient prepareHttpClient() {
-               return new InterfaceConfigurationBuilder()
+               return InterfaceConfigurationBuilder.buildFrom(new InterfaceConfigurationBuilder()
                                                                .withSSL(new SSLBuilder()
+                                                                                                                       .withKeyStoreType("JKS")
+                                                                                                                       .withKeyAlias(null)
                                                                                                                        .withKeyStore("classpath:/acumosa.pkcs12")
                                                                                                                        .withKeyStorePassword("acumosa")
-                                                                                                                       //.withKeyPassword("acumosa")
                                                                                                                        .withTrustStore("classpath:/acumosTrustStore.jks")
                                                                                                                        .withTrustStoreType("JKS")
                                                                                                                        .withTrustStorePassword("acumos")
                                                                                                                        .build())
+                                                               .buildConfig())
                                                                .buildConfig()
                                                                .buildClient();
        }
 }
-
index 577e57f..e414715 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
@@ -20,6 +20,7 @@
 package org.acumos.federation.gateway.test;
 
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.when;
 
@@ -28,9 +29,12 @@ import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Consumer;
 
+import org.acumos.federation.gateway.cds.Artifact;
+import org.acumos.federation.gateway.cds.Document;
 import org.acumos.federation.gateway.config.FederationInterfaceConfiguration;
 import org.acumos.federation.gateway.config.LocalInterfaceConfiguration;
 import org.acumos.federation.gateway.config.NexusConfiguration;
+import org.acumos.federation.gateway.service.ContentService;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpUriRequest;
 import org.apache.http.impl.client.CloseableHttpClient;
@@ -44,6 +48,8 @@ import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
@@ -56,10 +62,6 @@ import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.web.client.RestTemplate;
 
 
-/**
- */
-
-//@RunWith(SpringJUnit4ClassRunner.class)
 @RunWith(SpringRunner.class)
 @SpringBootTest(classes = org.acumos.federation.gateway.Application.class,
                                                                webEnvironment = WebEnvironment.RANDOM_PORT,
@@ -82,17 +84,18 @@ import org.springframework.web.client.RestTemplate;
                                                                })
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class PeerGatewayTest {
+       private final Logger log = LoggerFactory.getLogger(getClass().getName());
 
        @MockBean //(name = "local-org.acumos.federation.gateway.config.LocalInterfaceConfiguration")
        private LocalInterfaceConfiguration     localConfig;
 
-       @MockBean(name = "localClient")
+       @Mock
        private CloseableHttpClient     localClient;
 
        @MockBean //(name = "federation-org.acumos.federation.gateway.config.FederationInterfaceConfiguration")
        private FederationInterfaceConfiguration federationConfig;
 
-       @MockBean(name = "federationClient")
+       @Mock
        private CloseableHttpClient     federationClient;
 
        @Mock
@@ -101,16 +104,16 @@ public class PeerGatewayTest {
        @MockBean
        private NexusConfiguration nexusConfig;
 
-       //@MockBean(name = "clients")
-       //private Clients       clients;
-
        @Autowired
        private ApplicationContext context;
 
+       @Autowired
+       private ContentService content;
+
        private MockAnswer peerAnswer = new MockAnswer();       
        private MockAnswer cdsAnswer = new MockAnswer();        
        //initialize with the number of checkpoints
-       private CountDownLatch stepLatch = new CountDownLatch(5);
+       private CountDownLatch stepLatch = new CountDownLatch(8);
 
        @Before
        public void initTest() throws IOException {
@@ -130,6 +133,9 @@ public class PeerGatewayTest {
                                .mockResponse(info -> info.getMethod().equals("GET") && info.getPath().equals("/ccds/solution/6793411f-c7a1-4e93-85bc-f91d267541d8/revision"), MockResponse.success("mockCDSNoSuchSolutionRevisionsResponse.json"))
                                .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/solution/6793411f-c7a1-4e93-85bc-f91d267541d8/revision"), MockResponse.success("mockCDSCreateSolutionRevisionResponse.json", stepTrack))
                                .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/artifact"), MockResponse.success("mockCDSCreateArtifactResponse.json", stepTrack))
+                               .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/document"), MockResponse.success("mockCDSCreateDocumentResponse.json", stepTrack))
+                               .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/access/PB/descr"), MockResponse.success("mockCDSCreateRevisionDescriptionResponse.json", stepTrack))
+                               .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/access/PB/document/2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342"), MockResponse.success("mockCDSCreateRevisionDocumentResponse.json", stepTrack))
                                .mockResponse(info -> info.getMethod().equals("POST") && info.getPath().equals("/ccds/revision/2c7e4481-6e6f-47d9-b7a4-c4e674d2b341/artifact/2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b341"), MockResponse.success("mockCDSCreateRevisionArtifactResponse.json", stepTrack))
                                .mockResponse(info -> info.getPath().equals("/ccds/code/pair/PEER_STATUS"), MockResponse.success("mockCDSPeerStatusResponse.json"))
                                .mockResponse(info -> info.getPath().equals("/ccds/code/pair/ARTIFACT_TYPE"), MockResponse.success("mockCDSArtifactTypeResponse.json"));
@@ -170,7 +176,9 @@ public class PeerGatewayTest {
                                        .mockResponse(info -> info.getPath().endsWith("/artifacts"), MockResponse.success("mockPeerSolutionRevisionArtifactsResponse.json"))
                                        .mockResponse(info -> info.getPath().endsWith("/documents"), MockResponse.success("mockPeerSolutionRevisionDocumentsResponse.json"))
                                        .mockResponse(info -> info.getPath().endsWith("/download"), MockResponse.success("mockPeerDownload.tgz"))
-                                       .mockResponse(info -> info.getPath().contains("/solutions/") && info.getPath().contains("/revisions/"), MockResponse.success("mockPeerSolutionRevisionResponse.json"));
+                                       .mockResponse(info -> info.getPath().contains("/solutions/") && info.getPath().contains("/revisions/") && !info.getPath().endsWith("/content"), MockResponse.success("mockPeerSolutionRevisionResponse.json"))
+                                       .mockResponse(info -> info.getPath().contains("/artifacts/") && info.getPath().endsWith("/content"), MockResponse.success("mockPeerArtifactContent.txt"))
+                                       .mockResponse(info -> info.getPath().contains("/documents/") && info.getPath().endsWith("/content"), MockResponse.success("mockPeerDocumentContent.txt"));
 
                        when(
                                this.federationClient.execute(
@@ -201,6 +209,20 @@ public class PeerGatewayTest {
                        )
                        .thenReturn(nexusClient);
 
+                       when(
+                               this.nexusConfig.getGroupId()
+                       )
+                       .thenReturn("com.artifact");
+                       when(
+                               this.nexusConfig.getNameSeparator()
+                       )
+                       .thenReturn(".");
+                       when(
+                               this.nexusConfig.getUrl()
+                       )
+                       .thenReturn("http://somehost.example.org/");
+
+
                        when(
                                this.nexusClient.exchange(
                                        any(RequestEntity.class),any(Class.class)
@@ -210,9 +232,8 @@ public class PeerGatewayTest {
 
                }
                catch(Exception x) {
-                       System.out.println(" *** Failed to setup mock : " + x);
-                       x.printStackTrace();
-                       assertTrue(1 == 0);
+                       log.error("Failed to setup mock", x);
+                       fail();
                }
 
                //let the test wait for a few seconds so that the expected
@@ -222,13 +243,17 @@ public class PeerGatewayTest {
                        completed = stepLatch.await(10, TimeUnit.SECONDS);
                }
                catch (InterruptedException ix) {
-                       assertTrue(1 == 0);
+                       fail();
+               }
+               if (!completed) {
+                       log.error("Failed to complete {} steps left", stepLatch.getCount());
                }
-               if (!completed)
-                       System.out.println(" *** Failed to complete,  " + stepLatch.getCount() + " steps left");
-                       
                //if we are here is that all steps that we expected took place
                assertTrue(completed);
        }
 
+       @Test
+       public void testContentService() throws Exception {
+               log.info("Content: {}", content);
+       }
 }
index 105ef4f..5e6ea30 100644 (file)
@@ -82,6 +82,8 @@ public class PeerServiceTest extends ServiceTest {
                registerMockResponse("GET /ccds/peer/search?subjectName=gateway.acumosc.org&_j=a", MockResponse.success("mockCDSSearchEmptyResponse.json"));
                registerMockResponse("PUT /ccds/peer/b0b0b0b0-b0b0-b0b0-b0b0-b0b0b0b0b0b0", MockResponse.success("mockCDSPeerUpdateResponse.json"));
                registerMockResponse("POST /ccds/peer", MockResponse.success("mockCDSPeerCreateResponse.json"));
+               registerMockResponse("GET /ccds/peer/b0b0b0b0-b0b0-b0b0-b0b0-b0b0b0b0b0b0", MockResponse.success("mockCDSPeerResponse.json"));
+               registerMockResponse("GET /ccds/code/pair/PEER_STATUS", MockResponse.success("mockCDSPeerStatusResponse.json"));
        }
 
 
@@ -101,6 +103,7 @@ public class PeerServiceTest extends ServiceTest {
 
                        List<MLPPeer> peersn = peerService.getPeerBySubjectName("gateway.acumosb.org");
                        assertTrue("Expected one peer to be found", peersn.size() == 1);
+                       peerService.getPeerById(peersn.get(0).getPeerId());
 
                        try {
                                peerService.registerPeer(new MLPPeer("acumosc", "gateway.acumosc.org", "https://gateway.acumosc.org:9084", false, false, "admin@acumosc.org", "AC"));
index efe5051..0c17b63 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
@@ -58,7 +58,7 @@ public abstract class ServiceTest {
        /**
         * Derived classes should use this to register mock responses.
         */
-       protected abstract void initMockResponses();
+       protected abstract void initMockResponses() throws IOException;
 
        /**
         * Use to register a mocked http request/response.
index 52d4783..01647f2 100644 (file)
@@ -2,7 +2,7 @@
  * ===============LICENSE_START=======================================================
  * Acumos
  * ===================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
  * ===================================================================================
  * This Acumos software file is distributed by AT&T and Tech Mahindra
  * under the Apache License, Version 2.0 (the "License");
 package org.acumos.federation.gateway.test;
 
 import java.lang.invoke.MethodHandles;
+import java.util.AbstractMap;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
+import java.util.HashSet;
+import java.util.concurrent.CountDownLatch;
 
+import org.acumos.federation.gateway.util.Future;
+import org.acumos.federation.gateway.util.Futures;
+import org.acumos.federation.gateway.util.ListBuilder;
+import org.acumos.federation.gateway.util.MapBuilder;
 import org.acumos.federation.gateway.util.Utils;
 import org.junit.Assert;
 import org.junit.Test;
@@ -70,4 +77,81 @@ public class UtilsTest {
                
        }
 
+       @Test
+       public void testMapBuilder() {
+               MapBuilder<String, String> mb = new MapBuilder<String, String>();
+
+               Assert.assertTrue(mb.isEmpty());
+               Assert.assertNull(mb.buildOpt());
+               mb.putOpt("A", null)
+                       .putOpt("B", "x")
+                       .put(new AbstractMap.SimpleEntry<String, String>("C", "y"))
+                       .putOpt(null)
+                       .putAll(new MapBuilder<String, String>().build().entrySet())
+                       .putAll(new MapBuilder<String, String>().putOpt("E", "z").build().entrySet())
+                       .forceAll(new MapBuilder<String, String>().putOpt("B", "w").build().entrySet(), x -> x.getKey() + "_1")
+                       .putOpt(new AbstractMap.SimpleEntry<String, String>("F", "v"))
+                       .putAll(new MapBuilder<String, String>().build())
+                       .put("G", "u");
+               Assert.assertEquals("w", mb.build().get("B_1"));
+               Assert.assertEquals("x", mb.build().get("B"));
+       }
+
+       @Test
+       public void testListBuilder() {
+               ListBuilder<String> lb = new ListBuilder<String>();
+               HashSet<String> hs = new HashSet();
+
+               hs.add("xyzzy");
+               Assert.assertTrue(lb.isEmpty());
+               Assert.assertNull(lb.buildOpt());
+               lb.add("A").addAll(new String[] { "B", "C" }).addAll(new ListBuilder<String>().build()).addAll(hs).build();
+               Assert.assertNull(ListBuilder.asListOpt(new String[]{}));
+               Assert.assertNotNull(ListBuilder.asList(new String[]{}));
+       }
+
+       @Test
+       public void testFutures() throws Exception {
+               Future<String> f = Futures.future();
+               Assert.assertFalse(f.complete());
+               f = Futures.succeededFuture("yes");
+               Assert.assertEquals("yes", f.waitForResult());
+               f = Futures.failedFuture(new IllegalArgumentException());
+               Assert.assertFalse(f.succeeded());
+               Assert.assertTrue(f.failed());
+               f.waitForCompletion();
+               try {
+                       f.waitForResult();
+                       Assert.fail("Expected IllegalArgumentException");
+               } catch (IllegalArgumentException iae) {
+                       // we want this
+               }
+               Future<Integer> g = Futures.future();
+               f = Futures.advance(g, x -> x.toString());
+               Assert.assertFalse(f.complete());
+               g.result(new Integer(29));
+               Assert.assertEquals("29", f.waitForResult());
+               g = Futures.future();
+               f = Futures.advance(g, x -> x.toString(), e -> new IllegalArgumentException(e));
+               Assert.assertFalse(f.complete());
+               g.cause(new Exception());
+               Assert.assertTrue(f.failed());
+               try {
+                       f.waitForResult();
+                       Assert.fail("Expected IllegalArgumentException");
+               } catch (IllegalArgumentException iae) {
+                       // we want this
+               }
+               Futures.Accumulator<String> ac = new Futures.Accumulator();
+               f = Futures.future();
+               Future<String> f2 = Futures.future();
+               Futures.Accumulator<String> ac2 = new Futures.Accumulator();
+               ac2.add(f2);
+               ac.add(f);
+               ac.addAll(ac2);
+               Future<List<String>> a = ac.accumulate();
+               f.result("x");
+               f2.cause(new Exception());
+               a.waitForResult();
+       }
 }
index d71cfcc..6b401dc 100644 (file)
@@ -3,6 +3,6 @@
  "artifactTypeCode":"dk",
  "size":0,
  "metadata":"mock artifact",
- "created":"1550013200",
- "modified":"1550013200"
+ "created":"2019-02-12T23:13:20Z",
+ "modified":"2019-02-12T23:13:20Z"
 }
diff --git a/gateway/src/test/resources/mockCDSCreateDocumentResponse.json b/gateway/src/test/resources/mockCDSCreateDocumentResponse.json
new file mode 100644 (file)
index 0000000..2a0e377
--- /dev/null
@@ -0,0 +1,10 @@
+{
+  "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
+  "documentId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342",
+  "name":"document.txt",
+  "version": "1.0",
+  "uri":"somewhere/document.txt",
+  "size":0,
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z"
+}
diff --git a/gateway/src/test/resources/mockCDSCreateRevisionDescriptionResponse.json b/gateway/src/test/resources/mockCDSCreateRevisionDescriptionResponse.json
new file mode 100644 (file)
index 0000000..fea7f67
--- /dev/null
@@ -0,0 +1,7 @@
+{
+  "revisionId":"2c7e4481-6e6f-47d9-b7a4-c4e674d2b341",
+  "accessTypeCode": "PB",
+  "description": "mock description",
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z"
+}
diff --git a/gateway/src/test/resources/mockCDSCreateRevisionDocumentResponse.json b/gateway/src/test/resources/mockCDSCreateRevisionDocumentResponse.json
new file mode 100644 (file)
index 0000000..2c63c08
--- /dev/null
@@ -0,0 +1,2 @@
+{
+}
index 4dbd1bc..9ac27f2 100644 (file)
@@ -6,6 +6,6 @@
  "modelTypeCode":"CL",
  "toolkitTypeCode":"",
  "metadata":"acumosa",
- "created":"1550012925",
- "modified":"1550012925"
+ "created":"2019-02-12T23:08:45Z",
+ "modified":"2019-02-12T23:08:45Z"
 }
index 24f67f6..a20d7af 100644 (file)
@@ -5,6 +5,6 @@
  "metadata":"acumosa",
  "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
  "accessTypeCode": "PB",
- "created":"1550013200",
- "modified":"1550013200"
+ "created":"2019-02-12T23:13:20Z",
+ "modified":"2019-02-12T23:13:20Z"
 }
diff --git a/gateway/src/test/resources/mockCDSPeerResponse.json b/gateway/src/test/resources/mockCDSPeerResponse.json
new file mode 100644 (file)
index 0000000..35b3d7f
--- /dev/null
@@ -0,0 +1,14 @@
+{
+  "created": 1532025563000,
+  "modified": 1532025563000,
+  "peerId": "a0a0a0a0-a0a0-a0a0-a0a0-a0a0a0a0a0a0",
+  "name": "acumosa",
+  "subjectName": "gateway.acumosa.org",
+  "description": "test",
+  "apiUrl": "https://gateway.acumosa.org:9084",
+  "webUrl": "https://gateway.acumosa.org:9084",
+  "contact1": "admin@acumosa.org",
+  "statusCode": "AC",
+  "local": false,
+  "self": true
+}
index 87af7b2..151b370 100644 (file)
@@ -1,8 +1,8 @@
 {
   "content": [
      {
-      "created": 1532025563000,
-      "modified": 1532025563000,
+      "created": "2018-07-19T18:39:23Z",
+      "modified": "2018-07-19T18:39:23Z",
       "peerId": "b0b0b0b0-b0b0-b0b0-b0b0-b0b0b0b0b0b0",
       "name": "acumosb",
       "subjectName": "gateway.acumosb.org",
@@ -15,8 +15,8 @@
       "self": true
     },
     {
-      "created": 1532025563000,
-      "modified": 1532025563000,
+      "created": "2018-07-19T18:39:23Z",
+      "modified": "2018-07-19T18:39:23Z",
       "peerId": "a0a0a0a0-a0a0-a0a0-a0a0-a0a0a0a0a0a0",
       "name": "acumosa",
       "subjectName": "gateway.acumosa.org",
index 82b8025..f8dea4d 100644 (file)
@@ -4,6 +4,8 @@
        "selector":"{\"modelTypeCode\":[\"CL\",\"PR\"]}",
        "refreshInterval":"120",
        "maxArtifactSize":"2048",
-       "created":1549401637,
-       "modified":1549401637
+       "created":"2019-02-05T21:20:37Z",
+       "processed":"1970-01-01T00:00:01Z",
+       "scopeType":"FL",
+       "modified":"2019-02-05T21:20:37Z"
 }
index ba73798..0e2a261 100644 (file)
@@ -5,8 +5,10 @@
                "selector":"{\"modelTypeCode\":[\"CL\",\"PR\"]}",
                "refreshInterval":"120",
                "maxArtifactSize":"2048",
-               "created":1549401637,
-               "modified":1549401637
+               "created":"2019-02-05T21:20:37Z",
+               "processed":"1970-01-01T00:00:01Z",
+               "scopeType":"FL",
+               "modified":"2019-02-05T21:20:37Z"
        }
 ]
 
diff --git a/gateway/src/test/resources/mockCDSSolutionRevisionArtifactResponse.json b/gateway/src/test/resources/mockCDSSolutionRevisionArtifactResponse.json
new file mode 100644 (file)
index 0000000..eebbefd
--- /dev/null
@@ -0,0 +1,13 @@
+{
+  "created": "2018-04-25T12:54:43Z",
+  "modified": "2018-04-25T12:57:21Z",
+  "artifactId": "2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b341",
+  "version": "1.1",
+  "artifactTypeCode": "CD",
+  "name": "acumos-cdump-f0424d94-1bc1-47f9-86b2-13d41e0f3374",
+  "description": "Cdump File for : acumos-cdump-f0424d94-1bc1-47f9-86b2-13d41e0f3374 for SolutionID : f0424d94-1bc1-47f9-86b2-13d41e0f3374 with version : 1.1",
+  "uri": "com/artifact/f0424d94-1bc1-47f9-86b2-13d41e0f3374_ACUMOS-CDUMP-F0424D94-1BC1-47F9-86B2-13D41E0F3374/1.1/f0424d94-1bc1-47f9-86b2-13d41e0f3374_ACUMOS-CDUMP-F0424D94-1BC1-47F9-86B2-13D41E0F3374-1.1.json",
+  "size": 249,
+  "metadata": null,
+  "userId": "d1e838c8-d8be-4ca4-968c-2ba5c6c04e55"
+}
index 57032b7..84a5d8d 100644 (file)
@@ -1,7 +1,7 @@
 [
   {
-    "created": 1524660883000,
-    "modified": 1524661041000,
+    "created": "2018-04-25T12:54:43Z",
+    "modified": "2018-04-25T12:57:21Z",
     "artifactId": "7f83159c-13b3-4ee8-ba1e-38199fca4f75",
     "version": "1.1",
     "artifactTypeCode": "CD",
diff --git a/gateway/src/test/resources/mockCDSSolutionRevisionDescriptionResponse.json b/gateway/src/test/resources/mockCDSSolutionRevisionDescriptionResponse.json
new file mode 100644 (file)
index 0000000..c281b9a
--- /dev/null
@@ -0,0 +1,7 @@
+{
+  "revisionId":"2c7e4481-6e6f-47d9-b7a4-c4e674d2b341",
+  "accessTypeCode":"PB",
+  "description":"mock description",
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z"
+}
diff --git a/gateway/src/test/resources/mockCDSSolutionRevisionDocumentResponse.json b/gateway/src/test/resources/mockCDSSolutionRevisionDocumentResponse.json
new file mode 100644 (file)
index 0000000..e0ba03c
--- /dev/null
@@ -0,0 +1,11 @@
+{
+  "filename": "document.txt",
+  "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
+  "documentId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342",
+  "name":"document.txt",
+  "version": "1.0",
+  "uri":"somewhere/document.txt",
+  "size":0,
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z"
+}
diff --git a/gateway/src/test/resources/mockCDSSolutionRevisionDocumentsResponse.json b/gateway/src/test/resources/mockCDSSolutionRevisionDocumentsResponse.json
new file mode 100644 (file)
index 0000000..03cf01a
--- /dev/null
@@ -0,0 +1,13 @@
+[
+  {
+    "filename": "document.txt",
+    "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
+    "documentId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342",
+    "name":"document.txt",
+    "version": "1.0",
+    "uri":"somewhere/document.txt",
+    "size":0,
+    "created":"2019-02-12T23:13:20Z",
+    "modified":"2019-02-12T23:13:20Z"
+  }
+]
diff --git a/gateway/src/test/resources/mockCDSSolutionRevisionResponse.json b/gateway/src/test/resources/mockCDSSolutionRevisionResponse.json
new file mode 100644 (file)
index 0000000..3bdc87a
--- /dev/null
@@ -0,0 +1,12 @@
+{
+  "created": "2018-04-25T12:52:50Z",
+  "modified": "2018-04-25T12:55:32Z",
+  "revisionId": "2c7e4481-6e6f-47d9-b7a4-c4e674d2b341",
+  "version": "1",
+  "metadata": null,
+  "origin": null,
+  "accessTypeCode": "OR",
+  "solutionId": "10101010-1010-1010-1010-101010101010",
+  "userId": "d1e838c8-d8be-4ca4-968c-2ba5c6c04e55",
+  "sourceId": null
+}
diff --git a/gateway/src/test/resources/mockPeerArtifactContent.txt b/gateway/src/test/resources/mockPeerArtifactContent.txt
new file mode 100644 (file)
index 0000000..b0af757
--- /dev/null
@@ -0,0 +1,18 @@
+===============LICENSE_START=======================================================
+Acumos
+===================================================================================
+Copyright (C) 2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+===================================================================================
+This Acumos software file is distributed by AT&T and Tech Mahindra
+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
+
+This file 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=========================================================
+Mock Content of an Artifact
diff --git a/gateway/src/test/resources/mockPeerDocumentContent.txt b/gateway/src/test/resources/mockPeerDocumentContent.txt
new file mode 100644 (file)
index 0000000..de3bcc1
--- /dev/null
@@ -0,0 +1,18 @@
+===============LICENSE_START=======================================================
+Acumos
+===================================================================================
+Copyright (C) 2019 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
+===================================================================================
+This Acumos software file is distributed by AT&T and Tech Mahindra
+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
+
+This file 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=========================================================
+Mock Content of a Document
diff --git a/gateway/src/test/resources/mockPeerRegisterResponse.json b/gateway/src/test/resources/mockPeerRegisterResponse.json
new file mode 100644 (file)
index 0000000..f4b1a69
--- /dev/null
@@ -0,0 +1,12 @@
+{
+ "message": "Success",
+ "content": {
+  "peerId":"11111111-1111-1111-1111-111111111111",
+  "name":"acumosb",
+       "subjectName":"gateway.acumosb.org",
+       "description":"acumosb",
+  "statusCode": "AC",
+  "self": "false",
+       "apiUrl":"https://localhost:9002"
+ }
+}
index 17aad87..8b681bd 100644 (file)
@@ -6,7 +6,7 @@
   "artifactTypeCode":"dk",
   "size":0,
   "metadata":"mock artifact",
-  "created":"1550013200",
-  "modified":"1550013200"
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z"
  }]
 }
index 4d89374..0ba90eb 100644 (file)
@@ -8,8 +8,8 @@
   "metadata":"acumosa",
   "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
   "accessTypeCode": "PB",
-  "created":"1550013200",
-  "modified":"1550013200",
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z",
   "artifacts":[{
     "artifactId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b341",
     "artifactTypeCode":"dk",
     "description":"mock artifact",
     "size":0,
     "metadata":"mock artifact",
-    "created":"1550013200",
-    "modified":"1550013200",
-               "uri":"/somewhere/artifact.log"
+    "created":"2019-02-12T23:13:20Z",
+    "modified":"2019-02-12T23:13:20Z",
+               "filename":"artifact.log",
+               "uri":"somewhere/artifact.log"
    }],
- "documents":[]
+  "documents":[{
+    "filename": "document.txt",
+    "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
+    "documentId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342",
+    "name":"document.txt",
+    "version": "1.0",
+    "uri":"somewhere/document.txt",
+    "size":0,
+    "created":"2019-02-12T23:13:20Z",
+    "modified":"2019-02-12T23:13:20Z"
+  }],
+  "revisionDescription":{
+    "revisionId":"2c7e4481-6e6f-47d9-b7a4-c4e674d2b341",
+    "accessTypeCode":"PB",
+    "description":"mock description",
+    "created":"2019-02-12T23:13:20Z",
+    "modified":"2019-02-12T23:13:20Z"
+  }
  }
 }
index ff79f8d..c69de41 100644 (file)
@@ -8,7 +8,7 @@
   "metadata":"acumosa",
   "userId":"admin",
   "accessTypeCode": "PB",
-  "created":"1550012925",
-  "modified":"1550012925"
+  "created":"2019-02-12T23:08:45Z",
+  "modified":"2019-02-12T23:08:45Z"
  }]
 }
index 2fa12f2..92d74f6 100644 (file)
@@ -8,7 +8,7 @@
   "modelTypeCode":"CL",
   "toolkitTypeCode":"",
   "metadata":"acumosa",
-  "created":"1550012925",
-  "modified":"1550012925"
+  "created":"2019-02-12T23:08:45Z",
+  "modified":"2019-02-12T23:08:45Z"
  }]
 }
diff --git a/gateway/src/test/resources/onap/sdc/BytesResponse.tgz b/gateway/src/test/resources/onap/sdc/BytesResponse.tgz
new file mode 100644 (file)
index 0000000..217122c
--- /dev/null
@@ -0,0 +1 @@
+Here are the bytes
diff --git a/gateway/src/test/resources/onap/sdc/EmptyArrayResponse.json b/gateway/src/test/resources/onap/sdc/EmptyArrayResponse.json
new file mode 100644 (file)
index 0000000..fe51488
--- /dev/null
@@ -0,0 +1 @@
+[]
diff --git a/gateway/src/test/resources/onap/sdc/EmptyObjectResponse.json b/gateway/src/test/resources/onap/sdc/EmptyObjectResponse.json
new file mode 100644 (file)
index 0000000..0967ef4
--- /dev/null
@@ -0,0 +1 @@
+{}
index 9fbc8da..ac698f1 100644 (file)
@@ -6,8 +6,8 @@
   "modelTypeCode":"CL",
   "toolkitTypeCode":"",
   "metadata":"acumosa",
-  "created":1549401637,
-  "modified":1549401637,
+  "created":"2019-02-12T23:13:20Z",
+  "modified":"2019-02-12T23:13:20Z",
   "revisions":[
    {
     "revisionId":"01010101-0101-0101-0101-010101010101",
@@ -16,8 +16,8 @@
     "metadata":"acumosa",
     "accessTypeCode":"PB",
     "userId":"admin",
-       "created":1549401637,
-       "modified":1549401637,
+       "created":"2019-02-12T23:13:20Z",
+       "modified":"2019-02-12T23:13:20Z",
     "artifacts":[
      {
       "artifactId":"a0a0a0a0-a0a0-a0a0-a0a0-a0a0a0a0a0a0",
          "created":1549401637,
          "modified":1549401637
      }
+    ],
+    "documents":[
+     {
+      "filename": "document.txt",
+      "userId":"abcdabcd-abcd-abcd-abcd-abcdabcdabcd",
+      "documentId":"2c2c2c2c-6e6f-47d9-b7a4-c4e674d2b342",
+      "name":"document.txt",
+      "version": "1.0",
+      "uri":"classpath:/application-acumosb.properties",
+      "size":0,
+      "created":"2019-02-12T23:13:20Z",
+      "modified":"2019-02-12T23:13:20Z"
+     }
     ]
    }
   ]