minor reorg and patches 90/690/1
authorSerban Jora <sj2381@att.com>
Tue, 30 Jan 2018 21:17:52 +0000 (16:17 -0500)
committerSerban Jora <sj2381@att.com>
Tue, 30 Jan 2018 21:19:09 +0000 (16:19 -0500)
Add defaults to service interfaces, minor changes regquired by CDS 1.12

Change-Id: I8c107af0f2b01510e62093cf62e76a60f3643494
Signed-off-by: Serban Jora <sj2381@att.com>
18 files changed:
gateway/src/main/java/org/acumos/federation/gateway/adapter/PeerGateway.java
gateway/src/main/java/org/acumos/federation/gateway/controller/CatalogController.java
gateway/src/main/java/org/acumos/federation/gateway/controller/ControllerContext.java [new file with mode: 0644]
gateway/src/main/java/org/acumos/federation/gateway/controller/PeerController.java
gateway/src/main/java/org/acumos/federation/gateway/security/Peer.java
gateway/src/main/java/org/acumos/federation/gateway/security/Role.java
gateway/src/main/java/org/acumos/federation/gateway/security/X509AuthenticationFilter.java
gateway/src/main/java/org/acumos/federation/gateway/service/CatalogService.java
gateway/src/main/java/org/acumos/federation/gateway/service/PeerService.java
gateway/src/main/java/org/acumos/federation/gateway/service/PeerSubscriptionService.java
gateway/src/main/java/org/acumos/federation/gateway/service/ServiceContext.java
gateway/src/main/java/org/acumos/federation/gateway/service/ServiceException.java [new file with mode: 0644]
gateway/src/main/java/org/acumos/federation/gateway/service/impl/CatalogServiceImpl.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/PeerServiceImpl.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/PeerServiceLocalImpl.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/PeerSubscriptionServiceImpl.java
gateway/src/main/java/org/acumos/federation/gateway/task/PeerCommunicationTaskScheduler.java
gateway/src/test/java/org/acumos/federation/gateway/test/PeerGatewayTest.java

index 25a7abc..2ec2451 100644 (file)
@@ -21,6 +21,9 @@
 package org.acumos.federation.gateway.adapter;
 
 import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Collections;
 
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
@@ -119,6 +122,11 @@ public class PeerGateway {
        }
 
 
+       /**
+        * The list of solutions processed here represents the solutions (with 
+        * respect to the subscription filter definition) that were
+        * reported by the peer as being updated since the last check.
+        */
        public class PeerGatewayUpdateTask implements Runnable {
 
                private MLPPeer                                                 peer;
@@ -136,37 +144,31 @@ public class PeerGateway {
 
                public void run() {
 
-                       //list with category and subcategory currently used for onap
-                       //more dynamic mapping to come: based on solution information it will provide sdc assettype, categoty and subcategoty
-                       ICommonDataServiceRestClient cdsClient = PeerGateway.this.clients.getClient();
-                       
                        logger.info(EELFLoggerDelegate.debugLogger, "Received peer " + this.peer + " solutions: " + this.solutions);
-
+                       ICommonDataServiceRestClient cdsClient = PeerGateway.this.clients.getClient();
                        for (MLPSolution peerSolution: this.solutions) {
+                               //Check if the Model already exists in the Local Acumos
+                               MLPSolution localSolution  = null;
                                try {
-                                       //Check if the Model already exists in the Local Acumos
-                                       MLPSolution localSolution  = null;
-                                       try {
-                                               localSolution = cdsClient.getSolution(peerSolution.getSolutionId());
+                                       localSolution = cdsClient.getSolution(peerSolution.getSolutionId());
+                               }
+                               catch (HttpStatusCodeException x) {
+                                       if (!Errors.isCDSNotFound(x)) {
+                                               logger.warn(EELFLoggerDelegate.errorLogger, "Failed to check if solution with id " + peerSolution.getSolutionId() + " exists locally, skipping for now", x);
+                                               continue;
                                        }
-                                       catch (Exception e) {
-                                               logger.info(EELFLoggerDelegate.debugLogger, "Solution Id : " + peerSolution.getSolutionId() + " does not exists locally, Adding it to local catalog ");
+                               }
+
+                               try {
+                                       if (localSolution == null) {    
+                                               logger.info(EELFLoggerDelegate.debugLogger, "Solution Id : " + peerSolution.getSolutionId() + " does not exists locally, adding it to local catalog ");
+                                               localSolution = createMLPSolution(peerSolution, cdsClient);
                                        }
-                       
-                                       //Verify if MLPSolution is not same
-                                       if(localSolution != null &&
-                                                isSameMLPSolution(peerSolution, localSolution)) {
-                                               //if already exists locally then loop through next
-                                               localSolution = updateMLPSolution(peerSolution, localSolution, cdsClient);
-                                               
-                                       } 
                                        else {
-                                               localSolution = createMLPSolution(peerSolution, cdsClient);
+                                               localSolution = updateMLPSolution(peerSolution, localSolution, cdsClient);
                                        }
 
-                                       if (localSolution != null) {    
-                                               updateMLPSolution(localSolution, cdsClient);
-                                       }
+                                       mapSolution(localSolution, cdsClient);
                                }
                                catch (Exception x) {
                                        x.printStackTrace();
@@ -266,8 +268,7 @@ public class PeerGateway {
                        }
                }
                
-               private MLPArtifact updateMLPArtifact(MLPArtifact peerMLPArtifact, MLPArtifact localMLPArtifact, ICommonDataServiceRestClient cdsClient) {
-                       logger.info(EELFLoggerDelegate.debugLogger, "Updating Local MLP Artifact for peer artifact " + peerMLPArtifact);
+               private MLPArtifact copyMLPArtifact(MLPArtifact peerMLPArtifact, MLPArtifact localMLPArtifact) {
                        
                        localMLPArtifact.setArtifactId(peerMLPArtifact.getArtifactId());
                        localMLPArtifact.setArtifactTypeCode(peerMLPArtifact.getArtifactTypeCode());
@@ -277,21 +278,10 @@ public class PeerGateway {
                        localMLPArtifact.setModified(peerMLPArtifact.getModified());
                        localMLPArtifact.setName(peerMLPArtifact.getName());
                        localMLPArtifact.setOwnerId(getOwnerId(this.sub));
-                       localMLPArtifact.setSize(peerMLPArtifact.getSize());;
+                       localMLPArtifact.setSize(peerMLPArtifact.getSize());
                        localMLPArtifact.setUri(peerMLPArtifact.getUri());
                        localMLPArtifact.setVersion(peerMLPArtifact.getVersion());
-                       try {
-                               cdsClient.updateArtifact(localMLPArtifact);
-                               return localMLPArtifact;
-                       }
-                       catch (HttpStatusCodeException restx) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "updateArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
-                               return null;
-                       }
-                       catch (Exception x) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "updateArtifact unexpected failure",  x);
-                               return null;
-                       }
+                       return localMLPArtifact;
                }
                
                private MLPSolution updateMLPSolution(MLPSolution peerMLPSolution, MLPSolution localMLPSolution, ICommonDataServiceRestClient cdsClient) {
@@ -344,29 +334,12 @@ public class PeerGateway {
                        }
                }
                
-               private boolean isSameMLPSolution(MLPSolution peerMLPSolution, MLPSolution localMLPSolution) {
-                       boolean isSame = false;
-                       if(peerMLPSolution != null && localMLPSolution != null) {
-                               
-                               if((!Utils.isEmptyOrNullString(peerMLPSolution.getName()) && !Utils.isEmptyOrNullString(localMLPSolution.getName()) && localMLPSolution.getName().equalsIgnoreCase(peerMLPSolution.getName()))
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getDescription()) && !Utils.isEmptyOrNullString(localMLPSolution.getDescription()) && localMLPSolution.getDescription().equalsIgnoreCase(peerMLPSolution.getDescription()))
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getAccessTypeCode()) && !Utils.isEmptyOrNullString(localMLPSolution.getAccessTypeCode()) && localMLPSolution.getAccessTypeCode().equalsIgnoreCase(peerMLPSolution.getAccessTypeCode()))
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getMetadata()) && !Utils.isEmptyOrNullString(localMLPSolution.getMetadata()) && localMLPSolution.getMetadata().equalsIgnoreCase(peerMLPSolution.getMetadata()))
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getModelTypeCode()) && !Utils.isEmptyOrNullString(localMLPSolution.getModelTypeCode()) && localMLPSolution.getModelTypeCode().equalsIgnoreCase(peerMLPSolution.getModelTypeCode())) 
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getProvider()) && !Utils.isEmptyOrNullString(localMLPSolution.getProvider()) && localMLPSolution.getProvider().equalsIgnoreCase(peerMLPSolution.getProvider())) 
-                                       || (!Utils.isEmptyOrNullString(peerMLPSolution.getToolkitTypeCode()) && !Utils.isEmptyOrNullString(localMLPSolution.getToolkitTypeCode()) && localMLPSolution.getToolkitTypeCode().equalsIgnoreCase(peerMLPSolution.getToolkitTypeCode()))
-                                       || (Utils.isEmptyOrNullString(peerMLPSolution.getMetadata()) && Utils.isEmptyOrNullString(localMLPSolution.getMetadata()))
-                                       || (Utils.isEmptyOrNullString(peerMLPSolution.getDescription()) && Utils.isEmptyOrNullString(localMLPSolution.getDescription()))
-                                       || (Utils.isEmptyOrNullString(peerMLPSolution.getAccessTypeCode()) && Utils.isEmptyOrNullString(localMLPSolution.getAccessTypeCode()))
-                                       || (Utils.isEmptyOrNullString(peerMLPSolution.getModelTypeCode()) && Utils.isEmptyOrNullString(localMLPSolution.getModelTypeCode()))
-                                       || (Utils.isEmptyOrNullString(peerMLPSolution.getToolkitTypeCode()) && Utils.isEmptyOrNullString(localMLPSolution.getToolkitTypeCode()))) {
-                                       isSame = true;
-                               }
-                       }
-                       return isSame;
-               }
-               
-               public void updateMLPSolution(MLPSolution theSolution,  ICommonDataServiceRestClient cdsClient) throws Exception {
+               /**
+                * Here comes the core process of updating a local solution's related
+                * information with what is available from a peer.
+                */             
+               protected void mapSolution(MLPSolution theSolution, ICommonDataServiceRestClient cdsClient) throws Exception {
+
                        FederationClient fedClient =
                                        clients.getFederationClient(this.peer.getApiUrl());
 
@@ -377,7 +350,7 @@ public class PeerGateway {
                                                fedClient.getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
                        }
                        catch (Exception x) {
-                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos revisions", x);
+                               logger.warn(EELFLoggerDelegate.errorLogger, "Failed to retrieve acumos revisions for solution "  + theSolution.getSolutionId() + " from peer " + this.peer, x);
                                throw x;
                        }
 
@@ -391,49 +364,64 @@ public class PeerGateway {
                        //check if we have locally the latest revision available on the peer
                        //TODO: this is just one possible policy regarding the handling of
                        //such a mismatch
-                       MLPSolutionRevision localRevision = null;
+                       List<MLPSolutionRevision> cdsRevisions = Collections.EMPTY_LIST;
                        try {
-                               localRevision =
-                                       cdsClient.getSolutionRevision(
-                                               theSolution.getSolutionId(),
-                                               peerRevisions.get(peerRevisions.size()-1).getRevisionId());
+                               cdsRevisions =
+                                       cdsClient.getSolutionRevisions(theSolution.getSolutionId());
                        }
                        catch (HttpStatusCodeException restx) {
                                if (!Errors.isCDSNotFound(restx)) {
-                                       logger.error(EELFLoggerDelegate.debugLogger, "getSolutionRevision CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
+                                       logger.error(EELFLoggerDelegate.debugLogger, "getSolutionRevisions CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
                                        throw restx;
                                }
                        }
-
-                       if(localRevision == null) {
-                               localRevision = createMLPSolutionRevision(
-                                                                                                       peerRevisions.get(peerRevisions.size()-1), cdsClient);
-                       }
-                       else {
-                               //update the revision information
-                       }
-
-                       //continue to verify that we have the latest version of the artifacts
-                       //for this revision
-                       List<MLPArtifact> peerArtifacts = null;
-                       try {
+                       final List<MLPSolutionRevision> localRevisions = cdsRevisions;
+
+                       //map peer revisions to local ones; new peer revisions have a null mapping
+                       Map<MLPSolutionRevision, MLPSolutionRevision> peerToLocalRevisions =
+                       /*
+                               Elegant but toMap uses map merging which does not allow null values
+                               peerRevisions
+                                       .stream()
+                                       .collect(
+                                               Collectors.toMap(...)
+                       */
+                                               new HashMap<MLPSolutionRevision, MLPSolutionRevision>();
+                       peerRevisions.forEach(
+                               peerRevision -> peerToLocalRevisions.put(
+                                       peerRevision,   localRevisions
+                                                                                                       .stream()
+                                                                                                               .filter(localRevision -> 
+                                                                                                                                                       localRevision.getRevisionId().equals(
+                                                                                                                                                               peerRevision.getRevisionId()))
+                                                                                                               .findFirst()
+                                                                                                               .orElse(null)));
+       
+
+
+                       for (Map.Entry<MLPSolutionRevision, MLPSolutionRevision> revisionEntry:
+                                               peerToLocalRevisions.entrySet()) {
+                               MLPSolutionRevision peerRevision = revisionEntry.getKey(),
+                                                                                                               localRevision = revisionEntry.getValue();
+                               //get peer artifacts
+                               List<MLPArtifact> peerArtifacts = null;
+                               try {
                                        peerArtifacts = (List<MLPArtifact>)
-                                               fedClient.getArtifacts(
-                                                       theSolution.getSolutionId(),
-                                                       peerRevisions.get(peerRevisions.size()-1).getRevisionId())
-                                                               .getResponseBody();
-                       }
-                       catch (Exception x) {
-                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve peer acumos artifacts", x);
-                               throw x;
-                       }
-                       
-                       if(localRevision != null) {
-                               for(MLPArtifact peerArtifact : peerArtifacts) {
-                                       MLPArtifact localArtifact = null;
+                                               fedClient.getArtifacts(theSolution.getSolutionId(), peerRevision.getRevisionId())
+                                                       .getResponseBody();
+                               }
+                               catch (Exception x) {
+                                       logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve peer acumos artifacts", x);
+                                       throw x;
+                               }       
+
+                               List<MLPArtifact>       cdsArtifacts = Collections.EMPTY_LIST;
+                               if (localRevision == null) {
+                                       localRevision = createMLPSolutionRevision(peerRevision, cdsClient);
+                               }
+                               else {
                                        try {
-                                               localArtifact =
-                                                       cdsClient.getArtifact(peerArtifact.getArtifactId());
+                                               cdsArtifacts = cdsClient.getSolutionRevisionArtifacts(theSolution.getSolutionId(), localRevision.getRevisionId());
                                        }
                                        catch (HttpStatusCodeException restx) {
                                                if (!Errors.isCDSNotFound(restx)) {
@@ -441,85 +429,95 @@ public class PeerGateway {
                                                        throw restx;
                                                }
                                        }
+                               }
 
-                                       if(localArtifact == null) {
+                               final List<MLPArtifact> localArtifacts = cdsArtifacts;
+                               //map the artifacts
+                               //TODO: track deleted artifacts
+                               Map<MLPArtifact, MLPArtifact> peerToLocalArtifacts =
+                                               new HashMap<MLPArtifact, MLPArtifact>();
+                               peerArtifacts.forEach(
+                                       peerArtifact -> peerToLocalArtifacts.put(
+                                               peerArtifact, localArtifacts
+                                                                                                               .stream()
+                                                                                                               .filter(localArtifact -> 
+                                                                                                                                                       localArtifact.getArtifactId().equals(
+                                                                                                                                                               peerArtifact.getArtifactId()))
+                                                                                                               .findFirst()
+                                                                                                               .orElse(null)));
+
+                               for (Map.Entry<MLPArtifact, MLPArtifact> artifactEntry:
+                                                       peerToLocalArtifacts.entrySet()) {
+                                       MLPArtifact peerArtifact = artifactEntry.getKey(),
+                                                                                       localArtifact = artifactEntry.getValue();
+                                       boolean doUpdate = false;
+
+                                       if (localArtifact == null) {
                                                localArtifact = createMLPArtifact(
-                                                                                                               theSolution.getSolutionId(),
-                                                                                                               localRevision.getRevisionId(),
-                                                                                                               peerArtifact,
-                                                                                                               cdsClient);
+                                                                                                                       theSolution.getSolutionId(),
+                                                                                                                       localRevision.getRevisionId(),
+                                                                                                                       peerArtifact,
+                                                                                                                       cdsClient);
                                        }
                                        else {
-                                               //check version
                                                if (!peerArtifact.getVersion().equals(localArtifact.getVersion())) {
-                                                       localArtifact = updateMLPArtifact(peerArtifact, localArtifact, cdsClient);
-                                               }
-                                               else {
-                                                       //mark the fact that local artifact does not need an update
-                                                       localArtifact = null;
-                                               }
-                                       }
-
-                                       //TODO: add the delete of those who are not available anymore
-
-                                       if (localArtifact == null) {
-                                               //the artifact does not need an update
-                                               logger.info(EELFLoggerDelegate.debugLogger, "Artifact does not need an update");
-                                               continue;
+                                                       //update local artifact
+                                                       copyMLPArtifact(peerArtifact, localArtifact);
+                                                       doUpdate = true;
+                                               }       
                                        }
 
-                                       if (localArtifact.getUri() == null) {
-                                               //the peer does not want us to gain access to the artifact content      
-                                               logger.info(EELFLoggerDelegate.debugLogger, "Artifact uri not available");
-                                               continue;
-                                       }
-
-                                       //TODO: we are trying to access the artifact by its identifier which
-                                       //is fine in the common case but the uri specified in the artifact
-                                       //data is a more flexible approach.
-                                       Resource artifactContent = null;
-                                       try {
-                                               artifactContent = fedClient.downloadArtifact(peerArtifact.getArtifactId());
-                                       }
-                                       catch (Exception x) {
-                                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifact content", x);
-                                       }
-
-                                       UploadArtifactInfo uploadInfo = null;
-                                       if (artifactContent != null) {
+                                       //TODO: with CDS 1.13 check the subscription scope to decide if
+                                       //content is to be downloaded
+                                       boolean doContent = true;
+                                       if (doContent) {
+                                               //TODO: we are trying to access the artifact by its identifier which
+                                               //is fine in the common case but the uri specified in the artifact
+                                               //data is a more flexible approach.
+                                               Resource artifactContent = null;
                                                try {
-                                                       uploadInfo = 
-                                                               PeerGateway.this.clients.getNexusClient()
-                                                                       .uploadArtifact(
+                                                       artifactContent = fedClient.downloadArtifact(peerArtifact.getArtifactId());
+                                               }
+                                               catch (Exception x) {
+                                                       logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifact content", x);
+                                               }
+
+                                               UploadArtifactInfo uploadInfo = null;
+                                               if (artifactContent != null) {
+                                                       try {
+                                                               uploadInfo = 
+                                                                       PeerGateway.this.clients.getNexusClient()
+                                                                               .uploadArtifact(
                                                                                        PeerGateway.this.env.getProperty("nexus.groupId"),
                                                                                        localArtifact.getName(), /* probably wrong */
                                                                                        localArtifact.getVersion(),
                                                                                        "", /* should receive this from peer */
                                                                                        artifactContent.contentLength(),
                                                                                        artifactContent.getInputStream());
+                                                       }
+                                                       catch (Exception x) {
+                                                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to push artifact content to local Nexus repo", x);
+                                                       }
                                                }
-                                               catch (Exception x) {
-                                                       logger.warn(EELFLoggerDelegate.debugLogger, "Failed to push artifact content to local Nexus repo", x);
+
+                                               if (uploadInfo != null) {
+                                                       //update artifact with local repo reference
+                                                       localArtifact.setUri(uploadInfo.getArtifactMvnPath());
+                                                       //the artifact info will need to be updated with local content uri
+                                                       doUpdate = true;
                                                }
                                        }
 
-                                       if (uploadInfo != null) {
-                                               //update artifact with local repo reference
-                                               localArtifact.setUri(uploadInfo.getArtifactMvnPath());
+                                       if (doUpdate) {
                                                try {
                                                        cdsClient.updateArtifact(localArtifact);
                                                }
                                                catch (HttpStatusCodeException restx) {
                                                        logger.error(EELFLoggerDelegate.debugLogger, "updateArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
                                                }
-                                               catch (Exception x) {
-                                                       logger.error(EELFLoggerDelegate.debugLogger, "updateArtifact unexpected failure",  x);
-                                               }
                                        }
                                }
-                               
                        }
-                       
-               }
+               } //mapSolution
        }
 }
index 7994640..9400e1e 100644 (file)
@@ -321,10 +321,4 @@ public class CatalogController extends AbstractController {
                return inputStreamResource;
        }
 
-       protected class ControllerContext implements ServiceContext {
-
-               public Peer getPeer() {
-                       return (Peer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
-               }
-       }
 }
diff --git a/gateway/src/main/java/org/acumos/federation/gateway/controller/ControllerContext.java b/gateway/src/main/java/org/acumos/federation/gateway/controller/ControllerContext.java
new file mode 100644 (file)
index 0000000..7fff922
--- /dev/null
@@ -0,0 +1,45 @@
+/*-
+ * ===============LICENSE_START=======================================================
+ * Acumos
+ * ===================================================================================
+ * Copyright (C) 2017 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.controller;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+import org.acumos.federation.gateway.service.ServiceContext;
+import org.acumos.federation.gateway.security.Peer;
+
+
+/**
+ * 
+ *
+ */
+public class ControllerContext implements ServiceContext {
+
+       public Peer getPeer() {
+               return (Peer)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
+       }
+}
+
index b74fba1..1278aa6 100644 (file)
@@ -62,7 +62,7 @@ public class PeerController extends AbstractController {
        @ApiOperation(value = "Invoked by Peer Acumos to get a list of peers from local Acumos Instance .", response = MLPPeer.class, responseContainer = "List")
        @RequestMapping(value = { API.Paths.PEERS }, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
-       public JsonResponse<List<MLPPeer>> getSolutions(
+       public JsonResponse<List<MLPPeer>> getPeers(
                        /* HttpServletRequest theHttpRequest, */
                        HttpServletResponse theHttpResponse) {
 
@@ -96,10 +96,4 @@ public class PeerController extends AbstractController {
                return response;
        }
 
-       protected class ControllerContext implements ServiceContext {
-
-               public Peer getPeer() {
-                       return (Peer) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
-               }
-       }
 }
index 95be787..1db8832 100644 (file)
@@ -24,15 +24,55 @@ import java.util.Collection;
 import org.springframework.security.core.GrantedAuthority;
 import org.springframework.security.core.userdetails.User;
 
+import org.springframework.beans.factory.annotation.Autowired;
+
+import org.acumos.federation.gateway.service.PeerService;
+
+import org.acumos.cds.domain.MLPPeer;
+
 /**
  */
 public class Peer extends User {
 
-       //private MLPPeer       peer;
+       private MLPPeer peerInfo;
+
+       public Peer(MLPPeer thePeerInfo, Role theRole) {
+               this(thePeerInfo, theRole.priviledges());
+       }       
+
+       public Peer(MLPPeer thePeerInfo, Collection<? extends GrantedAuthority> theAuthorities) {
+               super (thePeerInfo.getName(), "", true, true, true, true, theAuthorities);
+               this.peerInfo = thePeerInfo;
+       }
+
+       public MLPPeer getPeerInfo() {
+               return this.peerInfo;
+       }
+
+
+       private static PeerService peerService = null;
+
+       @Autowired
+       public void setPeerService(PeerService thePeerService) {
+               if (peerService != null)
+                       throw new IllegalStateException("Already set");
+
+               peerService = thePeerService;
+       }
+
 
-       public Peer(String theName, Collection<? extends GrantedAuthority> theAuthorities) {
-               super (theName, "", true, true, true, true, theAuthorities);
+       private static Peer self = null;
+       
+       public static Peer self() {
+               if (self == null) {
+                       if (peerService == null) 
+                               throw new IllegalStateException("Initialization not completed");
+                       self = new Peer(peerService.getSelf(), Role.SELF.priviledges());
+               }
+
+               return self;
        }
 
 }
 
+
index b0a80ec..0575e8b 100644 (file)
@@ -39,15 +39,20 @@ public enum Role {
        /**
         * Common peer, grants generic solution catalog access
         */
-       PEER(Arrays.asList(Priviledge.CATALOG_ACCESS)),
+       PEER(Collections.unmodifiableList(
+                               Arrays.asList(Priviledge.CATALOG_ACCESS))),
        /**
    * Enhanced peer, gains (some lovel of) read access to the local peer list
         */
-       PARTNER(Arrays.asList(Priviledge.CATALOG_ACCESS, Priviledge.PEERS_ACCESS)),
+       PARTNER(Collections.unmodifiableList(
+                                               Arrays.asList(Priviledge.CATALOG_ACCESS, Priviledge.PEERS_ACCESS))),
        /**
-        * The actual gateway system, used for local calls, grants all proviledges
+        * The Acumos instance this gateway is serving, including local calls and
+        * calls received through the gateways' private interface from other
+        * components, grants all priviledges
         */
-       SYSTEM(Arrays.asList(Priviledge.class.getEnumConstants()));
+       SELF(Collections.unmodifiableList(
+                                       Arrays.asList(Priviledge.class.getEnumConstants())));
 
 
        private Collection<Priviledge> priviledges;
index 05dc5c8..1b20eda 100644 (file)
@@ -90,15 +90,18 @@ public class X509AuthenticationFilter extends WebSecurityConfigurerAdapter {
        public UserDetailsService userDetailsService() {
                return (username -> {
                        log.info(EELFLoggerDelegate.debugLogger, " X509 subject : " + username);
-                       List<MLPPeer> mlpPeers = peerService.getPeer(username);
+                       List<MLPPeer> mlpPeers = peerService.getPeerBySubjectName(username);
                        log.info(EELFLoggerDelegate.debugLogger, " Peers matching X509 subject : " + mlpPeers);
       if(!Utils.isEmptyList(mlpPeers)) {
                                log.info(EELFLoggerDelegate.debugLogger, " We are providing a matching Use ");
-                               return new Peer(username, Role.PEER.priviledges());
+                               return new Peer(mlpPeers.get(0), Role.PEER);
                        }
                        else    {
-                               return new Peer(username, Role.ANY.priviledges());
-                               //return null;
+                               MLPPeer unknown = new MLPPeer();
+                               //set it up with available info
+                               unknown.setSubjectName(username);
+
+                               return new Peer(unknown, Role.ANY);
                        }
                });
        }
index 504fe24..8d3d904 100644 (file)
  */
 package org.acumos.federation.gateway.service;
 
-import java.util.List;
+import java.io.File;
 import java.util.Map;
+import java.util.List;
+
+import org.springframework.core.io.InputStreamResource;
 
 import org.acumos.cds.domain.MLPArtifact;
 import org.acumos.cds.domain.MLPSolution;
 import org.acumos.cds.domain.MLPSolutionRevision;
-import org.springframework.core.io.InputStreamResource;
+import org.acumos.cds.transport.RestPageResponse;
+
 
 /**
- * Handles access to the solutions catalog
+ * Handles access to the solutions catalog 
  */
 public interface CatalogService {
+       
 
-       /*
-        * 
-        * API to be invoked by Peer Acumos to fetch the Catalog Solutions Information.
-        * Pageable Response allowing Peer Acumos's to Specify the Page Numb\er and the
-        * maximum results of the Solutions list.
-        * 
-        * @param pageNumber : Page Number for the a specific set of the Solution List
-        * 
-        * @param maxSize : Maximum Number of objects returned in the response
+       /**
         * 
-        * @param sortingOrder : Sorting Order Type for the Response
+        *  API to be invoked by Peer Acumos to fetch the Catalog Solutions List.
         * 
-        * @param mlpModelTypes : List of the ML Model Types for which Catalog Solutions
-        * needs to be returned
+        * @param theSelector contains the selection criteria.
         * 
-        * @return Pageable List of the Catalog Solutions
-        */
-       /*
-        * RestPageResponse<MLPSolution> getPeerCatalogSolutions(Integer pageNumber,
-        * Integer maxSize, String sortingOrder, List<String> mlpModelTypes);
+        * @return List of the Catalog Solutions for the specified list of query parameters
         */
+       public List<MLPSolution> getSolutions(Map<String,?> theSelector, ServiceContext theContext);
+       
+       public default List<MLPSolution> getSolutions(Map<String,?> theSelector) {
+               return getSolutions(theSelector, ServiceContext.selfService());
+       }
 
        /**
-        * API to be invoked by Peer Acumos to fetch the Catalog Solutions List.
-        * 
-        * @param theSelector
-        *            Comma Separate value of the ML Model Types for which Catalog
-        *            Solutions needs to be returned
-        * @param theContext
-        *            ServiceContext
-        * @return List of the Catalog Solutions for the specified list of query
-        *         parameters
         */
-       List<MLPSolution> getSolutions(Map<String, ?> theSelector, ServiceContext theContext);
-
-       /**
-        * @param theSolutionId
-        *            SolutionId for which Solution Needs to be returned
-        * @param theContext
-        *            ServiceContext
-        * @return MLPSolution
-        */
-       MLPSolution getSolution(String theSolutionId, ServiceContext theContext);
-
+       public MLPSolution getSolution(String theSolutionId, ServiceContext theContext);
+       
+       public default MLPSolution getSolution(String theSolutionId) {
+               return getSolution(theSolutionId, ServiceContext.selfService());
+       }
+       
+       
        /**
-        * @param theSolutionId
-        *            SolutionId for which Solution Revision Needs to be returned
-        * @param theContext
-        *            ServiceContext
+        * @param solutionId : SolutionId for which Solution Revision Needs to be returned
+        * 
         * @return List of the Solution Revision for the specified solution Id
         */
-       List<MLPSolutionRevision> getSolutionRevisions(String theSolutionId, ServiceContext theContext);
-
+       public List<MLPSolutionRevision> getSolutionRevisions(
+               String theSolutionId, ServiceContext theContext);
+       
+       public default List<MLPSolutionRevision> getSolutionRevisions(String theSolutionId) {
+               return getSolutionRevisions(theSolutionId, ServiceContext.selfService());
+       }
        /**
-        * @param theSolutionId
-        *            SolutionId for which Solution Revision Needs to be returned
-        * @param theRevisionId
-        *            RevisionId of the Solution
-        * @param theContext
-        *            ServiceContext
-        * @return MLPSolutionRevision
         */
-       MLPSolutionRevision getSolutionRevision(String theSolutionId, String theRevisionId, ServiceContext theContext);
+       public MLPSolutionRevision getSolutionRevision(
+               String theSolutionId, String theRevisionId, ServiceContext theContext);
+
+       public default MLPSolutionRevision getSolutionRevision(
+               String theSolutionId, String theRevisionId) {
+               return getSolutionRevision(theSolutionId, theRevisionId, ServiceContext.selfService());
+       }
 
        /**
-        * @param theSolutionId
-        *            SolutionId for which Solution Revision Artifacts Needs to be
-        *            returned
-        * @param theRevisionId
-        *            RevisionId of the Solution for which List of Artifacts are needed.
-        * @param theContext
-        *            ServiceContext
-        * @return List of the Solution Artifacts for the specified solution Id and
-        *         revisionId
+        * @param solutionId : SolutionId for which Solution Revision Artifacts Needs to be returned
+        * 
+        * @param revisionid : RevisionId of the Solution for which List of Artifacts are needed.
+        * 
+        * @return List of the Solution Artifacts for the specified solution Id & revisionId
         */
-       List<MLPArtifact> getSolutionRevisionArtifacts(String theSolutionId, String theRevisionId,
-                       ServiceContext theContext);
-
+       public List<MLPArtifact> getSolutionRevisionArtifacts(
+               String theSolutionId, String theRevisionId, ServiceContext theContext);
+       
+       public default List<MLPArtifact> getSolutionRevisionArtifacts(
+               String theSolutionId, String theRevisionId) {
+               return getSolutionRevisionArtifacts(theSolutionId, theRevisionId, ServiceContext.selfService());
+       }
+       
        /**
-        * @param theArtifactId
-        *            of the File stored in Nexus repository
-        * @param theContext
-        *            ServiceContext
-        * @return Artifact File for the Machine Learning Solution
+        * @param artifactId of the File stored in Nexus repository
+        * @return Artifact File for the Machine Learning Solution 
         */
-       InputStreamResource getSolutionRevisionArtifactContent(String theArtifactId, ServiceContext theContext);
-
+       public InputStreamResource getSolutionRevisionArtifactContent(String theArtifactId, ServiceContext theContext);
+       
 }
index f9a8e06..b69a285 100644 (file)
@@ -25,55 +25,68 @@ import java.util.List;
 import org.acumos.cds.domain.MLPPeer;
 
 /**
- * 
+ * Defines the interface of a service providing local peer information.
  *
  */
 public interface PeerService {
 
        /**
-        * @return List of Peers configured in the Local Acumos Instance
+        * Strictly an internal service call.
+        * Needs to avoid the 'chicken,egg' problem: one needs a context to access
+        * peers, including the 'self' peer.
         */
-       List<MLPPeer> getPeers();
+       public MLPPeer getSelf();
 
        /**
         * Provide the list of locally registered peers to one of our peers
-        * 
-        * @param theContext
-        *            Service context
-        * @return List of peers
+        * It is the responsability of the implementation to decide which peer
+        * information to expose in each case
         */
-       List<MLPPeer> getPeers(ServiceContext theContext);
-
+       public List<MLPPeer> getPeers(ServiceContext theContext);
+       
+       public default List<MLPPeer> getPeers() {
+               return getPeers(ServiceContext.selfService());
+       }
+       
        /**
-        * @param subjectName
-        *            Subject name
         * @return Peer based on the configured Subject Name
         */
-       List<MLPPeer> getPeer(String subjectName);
-
-       MLPPeer getOnePeer(String peerId);
-
+       public List<MLPPeer> getPeerBySubjectName(
+                                                                                                       String theSubjectName, ServiceContext theContext);
+       
+       public default List<MLPPeer> getPeerBySubjectName(String theSubjectName) {
+               return getPeerBySubjectName(theSubjectName, ServiceContext.selfService());
+       }
+       
+       /** */
+       public MLPPeer getPeerById(String thePeerId, ServiceContext theContext);
+       
+       public default MLPPeer getPeerById(String thePeerId) {
+               return getPeerById(thePeerId, ServiceContext.selfService());
+       }
+       
        /**
-        * @param mlpPeer
-        *            MLPPeer Configuration that needs to be created on the Platform
+        * Optional operation allowing the gateway to provision a peer in some
+        * initial state as part of a in-band peer handshake mechanism.
+        * The whole handshake procedure is to be completed elsewhere (portal);
+        * We do not pass a context as this operation is performed with
+        * frespect to 'self' (to reconsider).
+        *
+        * @param mlpPeer MLPPeer New Peer info to be submitted to the platform
         * 
         * @return Peer configuration that has been created.
         */
-       MLPPeer savePeer(MLPPeer mlpPeer);
-
-       /**
-        * @param mlpPeer
-        *            MLPPeer Configuration that needs to be updated on the Platform
-        * 
-        * @return Peer configuration that has been updated.
-        */
-       boolean updatePeer(MLPPeer mlpPeer);
-
+       public void subscribePeer(MLPPeer mlpPeer) throws ServiceException;
+       
        /**
-        * @param mlpPeer
-        *            MLPPeer Configuration that needs to be deleted on the Platform
+        * Optional operation allowing the gateway to update a peer and mark it for
+        * removal as part of a in-band peer handshake mechanism.
+        *
+        * @param mlpPeer MLPPeer New Peer info to be submitted to the platform
         * 
-        * @return true if successfully deleted else false.
+        * @return Peer configuration that has been created.
         */
-       boolean deletePeer(MLPPeer mlpPeer);
+       public void unsubscribePeer(MLPPeer mlpPeer) throws ServiceException;
+       
+       
 }
index d8fe980..a4d5cf4 100644 (file)
@@ -44,14 +44,6 @@ public interface PeerSubscriptionService {
         */
        MLPPeerSubscription getPeerSubscription(Long subId);
 
-       /**
-        * @param mlpPeerSubscription
-        *            MLPPeer Configuration that needs to be created on the Platform
-        * 
-        * @return MLPPeerSubscription configuration that has been created.
-        */
-       MLPPeerSubscription savePeerSubscription(MLPPeerSubscription mlpPeerSubscription);
-
        /**
         * @param mlpPeerSubscription
         *            MLPPeer Configuration that needs to be updated on the Platform
@@ -60,11 +52,4 @@ public interface PeerSubscriptionService {
         */
        boolean updatePeerSubscription(MLPPeerSubscription mlpPeerSubscription);
 
-       /**
-        * @param mlpPeerSubscription
-        *            MLPPeerSubscription that needs to be deleted on the Platform
-        * 
-        * @return true if successfully deleted else false.
-        */
-       boolean deletePeerSubscription(MLPPeerSubscription mlpPeerSubscription);
 }
index 68ed830..c6b2428 100644 (file)
@@ -34,9 +34,22 @@ import org.acumos.federation.gateway.security.Peer;
 public interface ServiceContext {
        
        /*
-        * In who's behalf are we providing the service
+        * In who's behalf are we providing the service.
         */
-       public Peer     getPeer();
+       public  Peer    getPeer(); 
 
+       /*
+        * Is the service to be provided for the benefit of the local Acumos system? 
+        */
+       public default boolean isSelf() {
+               return getPeer().getPeerInfo().isSelf();
+       }
+
+       /*
+        * Only feasible for as long as this interface is down to 'getPeer'
+        */
+       public static ServiceContext selfService() {
+               return () -> Peer.self();
+       }
 }
 
diff --git a/gateway/src/main/java/org/acumos/federation/gateway/service/ServiceException.java b/gateway/src/main/java/org/acumos/federation/gateway/service/ServiceException.java
new file mode 100644 (file)
index 0000000..064405c
--- /dev/null
@@ -0,0 +1,40 @@
+/*-
+ * ===============LICENSE_START=======================================================
+ * Acumos
+ * ===================================================================================
+ * Copyright (C) 2017 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.service;
+
+
+/**
+ *
+ */
+public class ServiceException extends Exception {
+
+       public ServiceException(String theMessage, Exception theCause) {
+               super(theMessage, theCause);
+       }
+
+       public ServiceException(Exception theCause) {
+               super("", theCause);
+       }
+
+       public ServiceException(String theMessage) {
+               super(theMessage);
+       }
+}
index cecce8e..83e64c5 100644 (file)
@@ -84,16 +84,6 @@ public class CatalogServiceImpl
        
        }
 
-       /**
-        * This needs to be implemented for future enhancement where pagination is allowed
-        */
-/*
-       @Override
-       public RestPageResponse<MLPSolution>  getPeerCatalogSolutions(Integer pageNumber, Integer maxSize, String sortingOrder,
-                       List<String> mlpModelTypes) {
-               return null;
-       }
-*/
        @Override
        public List<MLPSolution> getSolutions(
                Map<String,?> theSelector, ServiceContext theContext) {
@@ -101,12 +91,6 @@ public class CatalogServiceImpl
                log.debug(EELFLoggerDelegate.debugLogger, "getSolutions");
                List<MLPSolution> filteredMLPSolutions = null;
                ICommonDataServiceRestClient cdsClient = getClient();
-
-//             String modelTypeSelector = theSelector.get("modelTypeCode");
-//             final List<String> modelTypes =
-//                     modelTypeSelector == null ? null
-//                                                                                                                             : Arrays.asList(modelTypeSelector.split(","));
-               //TODO: revisit this code to pass query parameters to CCDS Service
        
                Map<String, Object> selector =
                                new HashMap<String, Object>(this.baseSelector);
@@ -117,22 +101,6 @@ public class CatalogServiceImpl
                log.debug(EELFLoggerDelegate.debugLogger, "getSolutions: cds solutions " + solutions);
 
                return solutions;
-
-               /*
-               if(mlpSolutions != null && mlpSolutions.size() > 0 && !Utils.isEmptyOrNullString(mlpModelTypes)) {
-                       //Filter List using Lamba to get solutions which matches the ML Model Type
-                       filteredMLPSolutions = mlpSolutions.stream()
-                                                                                                                               .filter(mlpSolution -> { String modelType = mlpSolution.getModelTypeCode();
-                                                                                                                                                                                                                                return modelType == null || //for testing only
-                                                                                                                                                                                                                                                               mlpModelTypes.contains(modelType);      
-                                                                                                                                                                                                                        })
-                                                                                                                               .collect(Collectors.toList());
-               }
-               else {
-                       filteredMLPSolutions = mlpSolutions;
-               }
-               return filteredMLPSolutions;
-               */
        }
 
        @Override
index 2a12b83..0b233d3 100644 (file)
@@ -30,8 +30,10 @@ import java.util.Collections;
 
 import org.acumos.federation.gateway.common.GatewayCondition;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
+import org.acumos.federation.gateway.util.MapBuilder;
 import org.acumos.federation.gateway.service.PeerService;
 import org.acumos.federation.gateway.service.ServiceContext;
+import org.acumos.federation.gateway.service.ServiceException;
 
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
@@ -40,6 +42,7 @@ import org.springframework.context.annotation.Conditional;
 
 import org.acumos.cds.client.ICommonDataServiceRestClient;
 import org.acumos.cds.domain.MLPPeer;
+import org.acumos.cds.transport.RestPageResponse;
 
 /**
  * 
@@ -53,14 +56,38 @@ public class PeerServiceImpl extends AbstractServiceImpl implements PeerService
         * 
         */
        public PeerServiceImpl() {
-               // TODO Auto-generated constructor stub
        }
 
+  @Override
+  public MLPPeer getSelf() {
+    return (MLPPeer)
+            getClient().searchPeers(
+                        new MapBuilder()
+                          .put("isSelf", Boolean.TRUE)
+                          .build(),
+                        false)
+                      .get(0);
+  }
+
+
+       /**
+        * ToDo:
+        */
        @Override
-       public List<MLPPeer> getPeers() {
+       public List<MLPPeer> getPeers(ServiceContext theContext) {
                log.debug(EELFLoggerDelegate.debugLogger, "getPeers");
                ICommonDataServiceRestClient cdsClient = getClient();
-               List<MLPPeer> mlpPeers = cdsClient.searchPeers(Collections.EMPTY_MAP,false);
+               List<MLPPeer> mlpPeers = null;
+/*
+                                                                                       cdsClient.searchPeers(
+                                                            new MapBuilder()
+                                                       .put("status", PeerStatus.ACTIVE)
+                                                       .build(),
+                                                       false);
+*/
+               RestPageResponse<MLPPeer> mlpPeersPage = cdsClient.getPeers(null);
+               if (mlpPeersPage != null)
+                       mlpPeers = mlpPeersPage.getContent();
                if(mlpPeers !=null) {
                        log.debug(EELFLoggerDelegate.debugLogger, "getPeers size:{}", mlpPeers.size());
                }
@@ -68,96 +95,90 @@ public class PeerServiceImpl extends AbstractServiceImpl implements PeerService
        }
 
        @Override
-       public List<MLPPeer> getPeers(ServiceContext theContext) {
-               log.debug(EELFLoggerDelegate.debugLogger, "getPeers(ServiceContext)");
-               return getPeers();
-       }
-
-       @Override
-       public List<MLPPeer> getPeer(String subjectName) {
-               log.debug(EELFLoggerDelegate.debugLogger, "savePeer");
-               ICommonDataServiceRestClient cdsClient = getClient();
-               Map<String, Object> queryParameters = new HashMap<String, Object>();
-               queryParameters.put("subjectName", subjectName); //I believe it should be unique
-               List<MLPPeer> existingMLPPeers = null;
-               existingMLPPeers = cdsClient.searchPeers(queryParameters, false);
-               if(existingMLPPeers != null && existingMLPPeers.size() > 0) {
-                       log.debug(EELFLoggerDelegate.debugLogger, "getPeer size:{}", existingMLPPeers.size());
+       public List<MLPPeer> getPeerBySubjectName(String theSubjectName,
+                                                                                                                                                                               ServiceContext theContext) {
+               log.debug(EELFLoggerDelegate.debugLogger, "getPeerBySubjectName");
+               List<MLPPeer> mlpPeers = 
+                       getClient().searchPeers(new MapBuilder()
+                                                                                                                               .put("subjectName", theSubjectName)
+                                                                                                                               .build(),
+                                                                                                                       false);
+               if(mlpPeers != null && mlpPeers.size() > 0) {
+                       log.debug(EELFLoggerDelegate.debugLogger, "getPeerBySubjectName size:{}", mlpPeers.size());
                }
-               return existingMLPPeers;
+               return mlpPeers;
        }
        
        @Override
-       public MLPPeer getOnePeer(String peerId) {
-               log.debug(EELFLoggerDelegate.debugLogger, "getPeer: {}", peerId);
-               ICommonDataServiceRestClient cdsClient = getClient();
-               MLPPeer mlpPeer = cdsClient.getPeer(peerId);
+       public MLPPeer getPeerById(String thePeerId, ServiceContext theContext) {
+               log.debug(EELFLoggerDelegate.debugLogger, "getPeerById: {}", thePeerId);
+               MLPPeer mlpPeer = getClient().getPeer(thePeerId);
                if(mlpPeer !=null) {
-                       log.error(EELFLoggerDelegate.debugLogger, "getOnePeer: {}", mlpPeer.toString());
+                       log.error(EELFLoggerDelegate.debugLogger, "getPeerById: {}", mlpPeer.toString());
                }
                return mlpPeer;
        }
        
        @Override
-       public MLPPeer savePeer(MLPPeer mlpPeer) {
-               log.debug(EELFLoggerDelegate.debugLogger, "savePeer");
+       public void subscribePeer(MLPPeer thePeer) throws ServiceException {
+               log.debug(EELFLoggerDelegate.debugLogger, "subscribePeer");
+
+               String subjectName = thePeer.getSubjectName();
+               if (subjectName == null)
+                       throw new ServiceException("No subject name is available");
+
                ICommonDataServiceRestClient cdsClient = getClient();
-               Map<String, Object> queryParameters = new HashMap<String, Object>();
-               queryParameters.put("subjectName", mlpPeer.getSubjectName()); //I believe it should be unique
-               boolean isPeerExists = false;
-               List<MLPPeer> existingMLPPeers = null;
-               MLPPeer mlpPeerCreated = null;
-               try{
-                       existingMLPPeers = getPeer(mlpPeer.getSubjectName());
-                       if(existingMLPPeers != null && existingMLPPeers.size() > 0) {
-                               isPeerExists = true;
-                               log.error(EELFLoggerDelegate.debugLogger, "savePeer");
-                       }
-               } catch (Exception e) {
-                       isPeerExists = false;
-                       log.error(EELFLoggerDelegate.debugLogger, "savePeer: There is no existing MLPPeer for subjectName:{}, Create a record in DB", mlpPeer.getSubjectName());
+               List<MLPPeer> mlpPeers = 
+                       cdsClient.searchPeers(new MapBuilder()
+                                                                                                                               .put("subjectName", subjectName)
+                                                                                                                               .build(),
+                                                                                                                       false);
+
+               if(mlpPeers != null && mlpPeers.size() > 0) {
+                       throw new ServiceException("Peer with subjectName '" + subjectName + "' already exists: " + mlpPeers);
                }
-               
-               if(!isPeerExists) {
-                       mlpPeerCreated = cdsClient.createPeer(mlpPeer);
-                       if(mlpPeerCreated !=null) {
-                               log.debug(EELFLoggerDelegate.debugLogger, "savePeer :{}", mlpPeer.toString());
-                       }
+
+               log.error(EELFLoggerDelegate.debugLogger, "subscribePeer: new peer with subjectName {}, create CDS record", thePeer.getSubjectName());
+               //waiting on CDS 1.13
+               //thePeer.setStatus(PeerStatus.PENDING);                
+
+               try {
+                       cdsClient.createPeer(thePeer);
+               }
+               catch (Exception x) {
+                       throw new ServiceException("Failed to create peer");
                }
-               return mlpPeerCreated;
        }
 
        @Override
-       public boolean updatePeer(MLPPeer mlpPeer) {
-               log.debug(EELFLoggerDelegate.debugLogger, "updatePeer");
+       public void unsubscribePeer(MLPPeer thePeer) throws ServiceException {
+               log.debug(EELFLoggerDelegate.debugLogger, "unsubscribePeer");
+
+               String subjectName = thePeer.getSubjectName();
+               if (subjectName == null)
+                       throw new ServiceException("No subject name is available");
+
                ICommonDataServiceRestClient cdsClient = getClient();
-               boolean isUpdatedSuccessfully = false;
-               List<MLPPeer> existingMLPPeers = null;
-               try{
-                       existingMLPPeers = getPeer(mlpPeer.getSubjectName());
-                       if(existingMLPPeers != null && existingMLPPeers.size() > 0) {
-                               cdsClient.updatePeer(mlpPeer);
-                               isUpdatedSuccessfully = true;
-                       }
-               } catch (Exception e) {
-                       isUpdatedSuccessfully = false;
-                       log.error(EELFLoggerDelegate.debugLogger, "updatePeer: Exception while deleting the MLPPeer record:", e);
+               List<MLPPeer> mlpPeers = 
+                       cdsClient.searchPeers(new MapBuilder()
+                                                                                                                               .put("subjectName", subjectName)
+                                                                                                                               .build(),
+                                                                                                                       false);
+
+               if(mlpPeers != null && mlpPeers.size() != 1) {
+                       throw new ServiceException("No peer with subjectName '" + subjectName + "' found: " + mlpPeers);
                }
-               return isUpdatedSuccessfully;
-       }
 
-       @Override
-       public boolean deletePeer(MLPPeer mlpPeer) {
-               log.debug(EELFLoggerDelegate.debugLogger, "deletePeer");
-               boolean isDeletedSuccessfully = false;
-               ICommonDataServiceRestClient cdsClient = getClient();
+               log.error(EELFLoggerDelegate.debugLogger, "unsubscribePeer: peer with subjectName {}, update CDS record", thePeer.getSubjectName());
+               //waiting on CDS 1.13
+               //thePeer.setStatus(PeerStatus.PENDING_REMOVE);         
+
                try {
-                       cdsClient.deletePeer(mlpPeer.getPeerId());
-                       isDeletedSuccessfully = true;
-               } catch (Exception e) {
-                       isDeletedSuccessfully = false;
-                       log.error(EELFLoggerDelegate.debugLogger, "deletePeer: Exception while deleting the MLPPeer record:", e);
+                       cdsClient.updatePeer(thePeer);
                }
-               return isDeletedSuccessfully;
-       }
+               catch (Exception x) {
+                       throw new ServiceException("Failed to update peer", x);
+               }
+}
+
 }
index a5a503e..83cc9ae 100644 (file)
@@ -117,9 +117,22 @@ public class PeerServiceLocalImpl
                log.debug(EELFLoggerDelegate.debugLogger, "Local peer info service destroyed");
        }
 
+  /** */
+  @Override
+  public MLPPeer getSelf() {
+    MLPPeer self =
+      this.peers
+            .stream()
+            .filter(peer -> peer.isSelf())
+            .findFirst()
+            .orElse(null);
+
+    return self;
+  }
 
        /** */
-       public List<MLPPeer> getPeers() {
+  @Override
+       public List<MLPPeer> getPeers(ServiceContext theContext) {
                synchronized (this) {
                        return this.peers == null ? null : 
                                                                                                                                this.peers.stream()
@@ -129,12 +142,8 @@ public class PeerServiceLocalImpl
        }
 
        /** */
-       public List<MLPPeer> getPeers(ServiceContext theContext) {
-               return getPeers();      
-       }
-
-       /** */
-       public List<MLPPeer> getPeer(final String theSubjectName) {
+  @Override
+       public List<MLPPeer> getPeerBySubjectName(final String theSubjectName, ServiceContext theContext) {
                log.info(EELFLoggerDelegate.debugLogger, "Looking for peer " + theSubjectName);
                return 
                        this.peers
@@ -146,7 +155,8 @@ public class PeerServiceLocalImpl
        }
        
        /** */
-       public MLPPeer getOnePeer(final String thePeerId) {
+  @Override
+       public MLPPeer getPeerById(final String thePeerId, ServiceContext theContext) {
                MLPPeer apeer =
                        this.peers
                                                .stream()
@@ -160,20 +170,19 @@ public class PeerServiceLocalImpl
        }
        
        /** */
-       public MLPPeer savePeer(MLPPeer mlpPeer) {
+  @Override
+       public void subscribePeer(MLPPeer mlpPeer) {
                throw new UnsupportedOperationException();
        }
                
        /** */
-       public boolean updatePeer(MLPPeer mlpPeer) {
+  @Override
+       public void unsubscribePeer(MLPPeer mlpPeer) {
                throw new UnsupportedOperationException();
        }
 
        /** */
-       public boolean deletePeer(MLPPeer mlpPeer) {
-               throw new UnsupportedOperationException();
-       }
-
+  @Override
        public List<MLPPeerSubscription> getPeerSubscriptions(final String thePeerId) {
                FLPPeer peer =
                        this.peers
@@ -186,6 +195,7 @@ public class PeerServiceLocalImpl
        }
 
        /** */
+  @Override
        public MLPPeerSubscription getPeerSubscription(Long theSubId) {
                for (FLPPeer peer: this.peers) {
                        for (MLPPeerSubscription peerSub: peer.getSubscriptions()) {
@@ -197,21 +207,12 @@ public class PeerServiceLocalImpl
        }
 
        /** */
-       public MLPPeerSubscription savePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
-               throw new UnsupportedOperationException();
-       }
-       
-       /** */
-       public boolean updatePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
+  @Override
+       public boolean updatePeerSubscription(MLPPeerSubscription theSub) {
                throw new UnsupportedOperationException();
        }
 
        /** */
-       public boolean deletePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
-               throw new UnsupportedOperationException();
-       }
-
-         /** */
   public static class FLPPeer extends MLPPeer {
 
                @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
index a2b5b51..b09c034 100644 (file)
@@ -84,18 +84,6 @@ public class PeerSubscriptionServiceImpl extends AbstractServiceImpl implements
                return existingMLPPeerSubscription;
        }
        
-       @Override
-       public MLPPeerSubscription savePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
-               log.debug(EELFLoggerDelegate.debugLogger, "savePeerSubscription");
-               ICommonDataServiceRestClient cdsClient = getClient();
-               MLPPeerSubscription mlPeerSubscriptionCreated = null;
-               mlPeerSubscriptionCreated = cdsClient.createPeerSubscription(mlpPeerSubscription);
-               if(mlPeerSubscriptionCreated !=null) {
-                       log.debug(EELFLoggerDelegate.debugLogger, "savePeerSubscription :{}", mlPeerSubscriptionCreated.toString());
-               }
-               return mlPeerSubscriptionCreated;
-       }
-
        @Override
        public boolean updatePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
                log.debug(EELFLoggerDelegate.debugLogger, "updatePeerSubscription");
@@ -116,18 +104,4 @@ public class PeerSubscriptionServiceImpl extends AbstractServiceImpl implements
                return isUpdatedSuccessfully;
        }
 
-       @Override
-       public boolean deletePeerSubscription(MLPPeerSubscription mlpPeerSubscription) {
-               log.debug(EELFLoggerDelegate.debugLogger, "deletePeerSubscription");
-               boolean isDeletedSuccessfully = false;
-               ICommonDataServiceRestClient cdsClient = getClient();
-               try {
-                       cdsClient.deletePeerSubscription(mlpPeerSubscription.getSubId());
-                       isDeletedSuccessfully = true;
-               } catch (Exception e) {
-                       isDeletedSuccessfully = false;
-                       log.error(EELFLoggerDelegate.debugLogger, "deletePeerSubscription: Exception while deleting the MLPPeerSubscription record:", e);
-               }
-               return isDeletedSuccessfully;
-       }
 }
index 22e7328..6f5e880 100644 (file)
@@ -133,7 +133,7 @@ public class PeerCommunicationTaskScheduler implements      ApplicationContextAware
                        logger.info(EELFLoggerDelegate.debugLogger, "checkPeer : no peers from " + peerService);
                        return;
                }
-               
+       
                for(MLPPeer mlpPeer : mlpPeers){
                        logger.info(EELFLoggerDelegate.debugLogger, "checkPeer : " + mlpPeer);
 
index cd114ee..70f241d 100644 (file)
@@ -98,6 +98,8 @@ import org.acumos.cds.domain.MLPSolution;
 import org.acumos.cds.domain.MLPSolutionRevision;
 import org.acumos.cds.domain.MLPArtifact;
 import org.acumos.cds.client.ICommonDataServiceRestClient;
+import org.acumos.cds.transport.RestPageRequest;
+import org.acumos.cds.transport.RestPageResponse;
 
 import org.acumos.nexus.client.NexusArtifactClient;
 import org.acumos.nexus.client.data.UploadArtifactInfo;
@@ -282,6 +284,26 @@ public class PeerGatewayTest {
                                        }
                                });
                
+                       when(
+                               this.cdsClient.getPeers(
+                                       any(RestPageRequest.class)
+                               )
+                       )
+                       .thenAnswer(new Answer<RestPageResponse<MLPPeer>>() {
+                                       public RestPageResponse<MLPPeer>
+                                               answer(InvocationOnMock theInvocation) {
+                                               MLPPeer peer = new MLPPeer();
+                                               peer.setPeerId("1");
+                                               peer.setName("testPeer");
+                                               peer.setSubjectName("test.org");
+                                               peer.setActive(true);
+                                               peer.setSelf(false);
+                                               peer.setApiUrl("https://localhost:1111");
+
+                                               return new RestPageResponse(Collections.singletonList(peer));
+                                       }
+                               });
+       
                        when(
                                this.cdsClient.getPeerSubscriptions(
                                        any(String.class)
@@ -326,16 +348,16 @@ public class PeerGatewayTest {
                        //the gateway should attempt to get the revisions from the peer and
                        //compare them against locally available ones (based on the last one)
                        when(
-                               this.cdsClient.getSolutionRevision(
-                                       any(String.class), any(String.class)
+                               this.cdsClient.getSolutionRevisions(
+                                       any(String.class)
                                )
                        ) 
-                       .thenAnswer(new Answer<MLPSolutionRevision>() {
-                                       public MLPSolutionRevision answer(InvocationOnMock theInvocation) {
+                       .thenAnswer(new Answer<List<MLPSolutionRevision>>() {
+                                       public List<MLPSolutionRevision> answer(InvocationOnMock theInvocation) {
                                                stepLatch.countDown();
                                                //pretend we do not have a local match so that we trigger
                                                //an insert
-                                               return null; //Collections.EMPTY_LIST;
+                                               return Collections.EMPTY_LIST;
                                        }
                                });