cleanup, lots of it 88/388/1
authorSerban Jora <sj2381@att.com>
Mon, 8 Jan 2018 06:31:16 +0000 (01:31 -0500)
committerSerban Jora <sj2381@att.com>
Mon, 8 Jan 2018 06:31:31 +0000 (01:31 -0500)
Change-Id: I5f8ed1a5b8bfee2b4a11ad9f7092381c5b3b3662
Signed-off-by: Serban Jora <sj2381@att.com>
20 files changed:
gateway/pom.xml
gateway/src/main/java/org/acumos/federation/gateway/adapter/Ghost.java
gateway/src/main/java/org/acumos/federation/gateway/adapter/PeerGateway.java
gateway/src/main/java/org/acumos/federation/gateway/adapter/onap/ONAP.java
gateway/src/main/java/org/acumos/federation/gateway/common/API.java [new file with mode: 0644]
gateway/src/main/java/org/acumos/federation/gateway/config/APIConstants.java [deleted file]
gateway/src/main/java/org/acumos/federation/gateway/config/APINames.java [deleted file]
gateway/src/main/java/org/acumos/federation/gateway/controller/CatalogController.java
gateway/src/main/java/org/acumos/federation/gateway/controller/PeerController.java
gateway/src/main/java/org/acumos/federation/gateway/service/CatalogService.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/AbstractClient.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/CatalogServiceImpl.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/CatalogServiceLocalImpl.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/FederationClient.java
gateway/src/main/java/org/acumos/federation/gateway/service/impl/FederationDataClient.java
gateway/src/main/java/org/acumos/federation/gateway/task/PeerCommunicationTask.java
gateway/src/main/java/org/acumos/federation/gateway/util/Utils.java
gateway/src/test/java/org/acumos/federation/gateway/test/PeerGatewayTest.java
gateway/src/test/resources/acumosa-catalog.json
gateway/src/test/resources/acumosb-catalog.json

index b9acaca..3e7404e 100644 (file)
                                                                <!-- This is the same CMD used in a Dockerfile -->
                                                                <cmd>
                                                                        <shell>cd /maven; java -cp ${project.artifactId}-${project.version}.${project.packaging}:${project.artifactId}-${project.version}-tests.${project.packaging}:/libs/* -Djavax.net.debug=ssl:handshake -Djavax.net.ssl.trustStore=/app/certs/acumosTrustStore.jks -Djavax.net.ssl.trustStorePassword=acumos -Djava.security.egd=file:/dev/./urandom org.springframework.boot.loader.PropertiesLauncher</shell>
+
+<!--
+                                                                       <shell>cd /maven; java -cp ${project.artifactId}-${project.version}.${project.packaging}:${project.artifactId}-${project.version}-tests.${project.packaging}:/libs/* -Djavax.net.debug=ssl:handshake -Djavax.net.ssl.trustStore=acumosTrustStore.jks -Djavax.net.ssl.trustStorePassword=acumos -Djava.security.egd=file:/dev/./urandom org.springframework.boot.loader.PropertiesLauncher</shell>
+-->
                                                                </cmd>
                                                        </build>
                                                </image>
index ba7fec9..0446a54 100644 (file)
@@ -20,6 +20,9 @@
 
 package org.acumos.federation.gateway.gateway.adapter;
 
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
 import java.net.URI;
 
 import java.util.List;
@@ -28,6 +31,7 @@ import java.util.Map;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.UUID;
+import java.util.stream.Collectors;
 
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
@@ -35,7 +39,9 @@ import javax.annotation.PreDestroy;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.client.HttpClientErrorException;
 
+import org.springframework.core.io.Resource;
 import org.springframework.stereotype.Component;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Scope;
 import org.springframework.context.annotation.Conditional;
 //import org.springframework.scheduling.annotation.Scheduled;
@@ -49,6 +55,8 @@ import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.acumos.federation.gateway.common.GhostAdapterCondition;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.acumos.federation.gateway.event.PeerSubscriptionEvent;
+import org.acumos.federation.gateway.service.impl.FederationClient;
+import org.acumos.federation.gateway.service.impl.Clients;
 
 import org.acumos.cds.domain.MLPPeer;
 import org.acumos.cds.domain.MLPArtifact;
@@ -72,6 +80,8 @@ public class Ghost {
 
        private Map<String, Map<String, MLPSolution>>   imports = 
                                                new HashMap<String, Map<String, MLPSolution>>();
+       @Autowired
+       private Clients clients;
 
        
        @PostConstruct
@@ -136,6 +146,43 @@ public class Ghost {
                                                        logger.debug(EELFLoggerDelegate.debugLogger, "Has updates");
                                                }
                                        }
+
+                                       FederationClient fedClient =
+                                               clients.getFederationClient(this.peer.getApiUrl());
+
+                                       List<MLPSolutionRevision> revisions = null;
+                                       try {
+                                               revisions = (List<MLPSolutionRevision>)
+                                                       fedClient.getSolutionRevisions(solution.getSolutionId()).getResponseBody();
+                                       }
+                                       catch (Exception x) {
+                                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve revisions", x);
+                                               continue;
+                                       }
+                                       logger.debug(EELFLoggerDelegate.debugLogger, "Received " + revisions.size() + " revisions " + revisions);
+                       
+                                       List<MLPArtifact> artifacts = null;
+                                       try {
+                                               artifacts = (List<MLPArtifact>)
+                                                       fedClient.getArtifacts(solution.getSolutionId(), revisions.get(revisions.size()-1).getRevisionId())
+                                                               .getResponseBody();
+                                       }
+                                       catch (Exception x) {
+                                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve artifacts", x);
+                                               continue;
+                                       }
+                                       logger.debug(EELFLoggerDelegate.debugLogger, "Received " + artifacts.size() + " artifacts " + artifacts);
+
+                                       for (MLPArtifact artifact: artifacts) {
+                                               Resource artifactContent = null;
+                                               try {
+                                                       artifactContent = fedClient.downloadArtifact(artifact.getArtifactId());
+                                               logger.warn(EELFLoggerDelegate.debugLogger, "Received artifact content: " + new BufferedReader(new InputStreamReader(artifactContent.getInputStream())).lines().collect(Collectors.joining("\n")));
+                                               }
+                                               catch (Exception x) {
+                                                       logger.debug(EELFLoggerDelegate.debugLogger, "Failed to download artifact", x);
+                                               }
+                                       }
                                }
                        }
                }
index 44dc972..bea0038 100644 (file)
 
 package org.acumos.federation.gateway.adapter;
 
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+
 import java.util.List;
+import java.util.stream.Collectors;
 
 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
@@ -43,6 +47,8 @@ import org.springframework.core.task.TaskExecutor;
 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.HttpStatusCodeException;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.core.io.Resource;
 
 import org.acumos.cds.AccessTypeCode;
 import org.acumos.cds.ValidationStatusCode;
@@ -71,7 +77,7 @@ public class PeerGateway {
 
 
        @PostConstruct
-       public void initPeerGateway() {
+       public void initGateway() {
                logger.debug(EELFLoggerDelegate.debugLogger, "initPeerGateway");
 
                /* make sure an operator was specified and that it is a declared user */
@@ -100,7 +106,7 @@ public class PeerGateway {
        }
 
        @PreDestroy
-       public void cleanupOnap() {
+       public void cleanupGateway() {
                logger.debug(EELFLoggerDelegate.debugLogger, "PeerGateway destroyed");
        }
 
@@ -177,7 +183,7 @@ public class PeerGateway {
                private MLPSolution createMLPSolution(
                                                                                                                                MLPSolution peerMLPSolution,
                                                                                                                                ICommonDataServiceRestClient cdsClient) {
-                       logger.info(EELFLoggerDelegate.debugLogger, "Creating Local MLP Solutino for peer solution " + peerMLPSolution);
+                       logger.info(EELFLoggerDelegate.debugLogger, "Creating Local MLP Solution for peer solution " + peerMLPSolution);
                        MLPSolution mlpSolution = new MLPSolution();
                        mlpSolution.setSolutionId(peerMLPSolution.getSolutionId());
                        mlpSolution.setName(peerMLPSolution.getName());
@@ -194,10 +200,16 @@ public class PeerGateway {
                        mlpSolution.setOwnerId(getOwnerId(this.sub)); 
                        try {
                                cdsClient.createSolution(mlpSolution);
-                       } catch (Exception e) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolution  failed for: ",  e);
+                               return mlpSolution;
+                       }
+                       catch (HttpStatusCodeException restx) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
+                               return null;
+                       }
+                       catch (Exception x) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolution unexpected failure",  x);
+                               return null;
                        }
-                       return mlpSolution;
                }
                
                private MLPSolutionRevision createMLPSolutionRevision(
@@ -214,10 +226,16 @@ public class PeerGateway {
                        solutionRevision.setModified(mlpSolutionRevision.getModified());
                        try {
                                cdsClient.createSolutionRevision(solutionRevision);
-                       } catch (Exception e) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolutionRevision  failed for: ",  e);
+                               return solutionRevision;
+                       }
+                       catch (HttpStatusCodeException restx) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createSolutionRevision CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
+                               return null;
+                       }
+                       catch (Exception x) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createSolutionRevision unexpected failure",  x);
+                               return null;
                        }
-                       return solutionRevision;
                }
                
                private MLPArtifact createMLPArtifact(MLPArtifact mlpArtifact, ICommonDataServiceRestClient cdsClient) {
@@ -235,10 +253,16 @@ public class PeerGateway {
                        artifact.setVersion(mlpArtifact.getVersion());
                        try {
                                cdsClient.createArtifact(artifact);
-                       } catch (Exception e) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "createMLPArtifact  failed for: ",  e);
+                               return artifact;
+                       }
+                       catch (HttpStatusCodeException restx) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createArtifact CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
+                               return null;
+                       }
+                       catch (Exception x) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "createArtifact unexpected failure", x);
+                               return null;
                        }
-                       return artifact;
                }
                
                private MLPArtifact updateMLPArtifact(MLPArtifact peerMLPArtifact, MLPArtifact localMLPArtifact, ICommonDataServiceRestClient cdsClient) {
@@ -257,10 +281,16 @@ public class PeerGateway {
                        localMLPArtifact.setVersion(peerMLPArtifact.getVersion());
                        try {
                                cdsClient.updateArtifact(localMLPArtifact);
-                       } catch (Exception e) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "updateMLPArtifact  failed for: ",  e);
+                               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) {
@@ -279,10 +309,16 @@ public class PeerGateway {
 
                        try {
                                cdsClient.updateSolution(localMLPSolution);
-                       } catch (Exception e) {
-                               logger.error(EELFLoggerDelegate.debugLogger, "createMLPSolution  failed for: ",  e);
+                               return localMLPSolution;
+                       }
+                       catch (HttpStatusCodeException restx) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "updateSolution CDS call failed. CDS message is " + restx.getResponseBodyAsString(),  restx);
+                               return null;
+                       }
+                       catch (Exception x) {
+                               logger.error(EELFLoggerDelegate.debugLogger, "updateSolution unexpected failure",  x);
+                               return null;
                        }
-                       return localMLPSolution;
                }
                
                private boolean isSameMLPSolution(MLPSolution peerMLPSolution, MLPSolution localMLPSolution) {
@@ -316,21 +352,21 @@ public class PeerGateway {
                        List<MLPSolutionRevision> acumosRevisions = null;
                        try {
                                acumosRevisions = (List<MLPSolutionRevision>)
-                                               fedClient.getSolutionsRevisionListFromPeer(theSolution.getSolutionId(), null).getResponseBody();
+                                               fedClient.getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
                        }
                        catch (Exception x) {
-                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos revisions: " + x);
+                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos revisions", x);
                                throw x;
                        }
                        
                        List<MLPArtifact> acumosArtifacts = null;
                        try {
                                acumosArtifacts = (List<MLPArtifact>)
-                                               fedClient.getArtifactsListFromPeer(theSolution.getSolutionId(), acumosRevisions.get(acumosRevisions.size()-1).getRevisionId(), null)
+                                               fedClient.getArtifacts(theSolution.getSolutionId(), acumosRevisions.get(acumosRevisions.size()-1).getRevisionId())
                                                .getResponseBody();
                        }
                        catch (Exception x) {
-                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifacts" + x);
+                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifacts", x);
                                throw x;
                        }
                        
@@ -348,11 +384,19 @@ public class PeerGateway {
                                        } else {
                                                updateMLPArtifact(artifact, mlpArtifact, cdsClient);
                                        }
+                                       //artifacts file download and push it to nexus
+                                       Resource artifactContent = null;
+                                       try {
+                                               artifactContent = fedClient.downloadArtifact(artifact.getArtifactId());
+                                               logger.warn(EELFLoggerDelegate.debugLogger, "Received artifact content: " + new BufferedReader(new InputStreamReader(artifactContent.getInputStream())).lines().collect(Collectors.joining("\n")));
+                                       }
+                                       catch (Exception x) {
+                                               logger.warn(EELFLoggerDelegate.debugLogger, "Failed to retrieve acumos artifact content", x);
+                                       }
                                }
                                
                        }
                        
-                       //TODO Artifacts file download and push it to nexus
                }
        }
 }
index fffa1a5..10255a0 100644 (file)
@@ -240,7 +240,7 @@ public class ONAP {
                        List<MLPSolutionRevision> acumosRevisions = null;
                        try {
                                acumosRevisions = (List<MLPSolutionRevision>)
-                                       fedClient.getSolutionsRevisionListFromPeer(theSolution.getSolutionId(), null).getResponseBody();
+                                       fedClient.getSolutionRevisions(theSolution.getSolutionId()).getResponseBody();
                        }
                        catch (Exception x) {
                                logger.warn(EELFLoggerDelegate.errorLogger, "Failed to retrieve acumos revisions: " + x);
@@ -250,7 +250,7 @@ public class ONAP {
                        List<MLPArtifact> acumosArtifacts = null;
                        try {
                                acumosArtifacts = (List<MLPArtifact>)
-                                       fedClient.getArtifactsListFromPeer(theSolution.getSolutionId(), acumosRevisions.get(acumosRevisions.size()-1).getRevisionId(), null)
+                                       fedClient.getArtifacts(theSolution.getSolutionId(), acumosRevisions.get(acumosRevisions.size()-1).getRevisionId())
                                                                                .getResponseBody();
                        }
                        catch (Exception x) {
diff --git a/gateway/src/main/java/org/acumos/federation/gateway/common/API.java b/gateway/src/main/java/org/acumos/federation/gateway/common/API.java
new file mode 100644 (file)
index 0000000..19e372c
--- /dev/null
@@ -0,0 +1,152 @@
+/*-
+ * ===============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.common;
+
+import java.net.URI;
+import java.util.Map;
+import java.util.Collection;
+
+import org.springframework.web.util.UriComponentsBuilder;
+
+/**
+ * Specifies the REST API that makes up the federation interface.
+ * I could add the expected return type and the doc here too.
+ */
+public enum API {
+
+       SOLUTIONS(Paths.SOLUTIONS, Queries.SOLUTIONS),
+       SOLUTION_DETAIL(Paths.SOLUTION_DETAILS),
+       SOLUTION_REVISIONS(Paths.SOLUTION_REVISIONS),
+       SOLUTION_REVISION_DETAILS(Paths.SOLUTION_REVISION_DETAILS),
+       SOLUTION_REVISION_ARTIFACTS(Paths.SOLUTION_REVISION_ARTIFACTS),
+       ARTIFACT_DETAILS(Paths.ARTIFACT_DETAILS),
+       ARTIFACT_DOWNLOAD(Paths.ARTIFACT_DOWNLOAD),
+       PEERS(Paths.PEERS);
+
+
+       private String          path;
+       private String[]        query;
+       
+
+       API(String thePath) {
+               this.path = thePath;
+       }
+       
+       API(String thePath, String[] theQueryParams) {
+               this.path = thePath;
+               this.query = theQueryParams;
+       }
+
+       public String path() {
+               return this.path;
+       }
+
+       public String[] query() {
+               return this.query;
+       }
+
+       public Map<String,?> queryParams(Map<String,?> theParams) {
+               for (String queryParam: this.query) {
+                       if (!theParams.containsKey(queryParam)) {
+                               theParams.put(queryParam, null);
+                       }
+               }
+               return theParams;
+       }
+       
+       public String toString() {
+               return this.path;
+       }
+
+       /**
+        * Prepares a 'full' URI for this API call. It will contain all query
+        * parameters.
+        */
+       public UriComponentsBuilder buildUri(String theHttpUrl) {
+               UriComponentsBuilder builder =
+                               UriComponentsBuilder.fromHttpUrl(theHttpUrl)
+                                                                                                               .path(this.path);
+               if (this.query != null) {
+                       for (String queryParam : this.query) {
+                               builder.queryParam(queryParam, "{" + queryParam + "}");
+                       }
+               }
+               return builder;
+       }
+
+       /**
+        * Prepares a URI containing only the query param present in the given
+        * collection.
+        */
+       public UriComponentsBuilder buildUri(String theHttpUrl, Collection<String> theParams) {
+               UriComponentsBuilder builder =
+                               UriComponentsBuilder.fromHttpUrl(theHttpUrl)
+                                                                                                               .path(this.path);
+               if (this.query != null) {
+                       for (String queryParam : this.query) {
+                               if (theParams.contains(queryParam)) {
+                                       builder.queryParam(queryParam, "{" + queryParam + "}");
+                               }
+                       }
+               }
+               return builder;
+       }
+       /* the params include both path and query params.
+        */
+       public URI buildUri(String theHttpUrl, Map<String,?> theParams) {
+               return buildUri(theHttpUrl, theParams.keySet()).buildAndExpand(theParams).encode().toUri();
+       }
+
+       /**
+        * Order based version. All query params must be present.
+        */
+       public URI buildUri(String theHttpUrl, String... theParams) {
+               return buildUri(theHttpUrl).buildAndExpand(theParams).encode().toUri();
+       }
+
+       public static class Paths {
+               
+    public static final String SOLUTIONS = "/solutions";
+    public static final String SOLUTION_DETAILS = "/solutions/{solutionId}";
+    
+    public static final String SOLUTION_REVISIONS = "/solutions/{solutionId}/revisions";
+    public static final String SOLUTION_REVISION_DETAILS = "/solutions/{solutionId}/revisions/{revisionId}";
+    
+    public static final String SOLUTION_REVISION_ARTIFACTS = "/solutions/{solutionId}/revisions/{revisionId}/artifacts";
+    public static final String ARTIFACT_DETAILS = "/artifacts/{artifactId}";
+    public static final String ARTIFACT_DOWNLOAD = "/artifacts/{artifactId}/download";
+    
+               public static final String PEERS = "/peers";
+               
+               //public static final String PEER_SUBSCRIBE = "/peer/subscribe";
+               //public static final String PEER_UNSUBSCRIBE = "/peer/unsubscribe";
+       }
+
+
+       public static class QueryParameters {
+
+    public static final String SOLUTIONS_SELECTOR = "selector";
+       }
+
+       public static class Queries {
+
+    public static final String[] SOLUTIONS = { QueryParameters.SOLUTIONS_SELECTOR };
+       }
+}
diff --git a/gateway/src/main/java/org/acumos/federation/gateway/config/APIConstants.java b/gateway/src/main/java/org/acumos/federation/gateway/config/APIConstants.java
deleted file mode 100644 (file)
index 844d938..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*-
- * ===============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.config;
-
-public class APIConstants {
-
-    public static final String SOLUTIONS = "solutions";
-    public static final String REVISIONS = "revisions";
-    public static final String ARTIFACTS = "artifacts";
-    public static final String DOWNLOAD= "download";
-
-}
diff --git a/gateway/src/main/java/org/acumos/federation/gateway/config/APINames.java b/gateway/src/main/java/org/acumos/federation/gateway/config/APINames.java
deleted file mode 100644 (file)
index 6a53b63..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ===============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.config;
-
-/**
- * 
- *
- */
-public class APINames {
-        //Solutions APIs for MarketPlace Catalog
-    public static final String PEER_SOLUTIONS = "/solutions";
-    public static final String PEER_SOLUTION_DETAILS = "/solutions/{solutionId}";
-    
-    public static final String PEER_SOLUTION_REVISIONS = "/solutions/{solutionId}/revisions";
-    public static final String PEER_SOLUTION_REVISION_DETAILS = "/solutions/{solutionId}/revisions/{revisionId}";
-    
-    public static final String PEER_SOLUTION_REVISION_ARTIFACTS = "/solutions/{solutionId}/revisions/{revisionId}/artifacts";
-    public static final String PEER_ARTIFACT_DETAILS = "/artifacts/{artifactId}";
-    public static final String PEER_ARTIFACT_DOWNLOAD = "/artifacts/{artifactId}/download";
-    
-               public static final String PEER_PEERS = "/peers";
-               
-               //public static final String PEER_SUBSCRIBE = "/peer/subscribe";
-               //public static final String PEER_UNSUBSCRIBE = "/peer/unsubscribe";
-}
index 5d4e84c..2e846df 100644 (file)
 
 package org.acumos.federation.gateway.controller;
 
+import java.net.URI;
+
+import java.util.Map;
 import java.util.List;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.Resource;
 import org.springframework.core.io.InputStreamResource;
 import org.springframework.http.HttpEntity;
 import org.springframework.http.MediaType;
@@ -40,13 +44,15 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.util.Base64Utils;
 
 import org.acumos.cds.domain.MLPArtifact;
 import org.acumos.cds.domain.MLPSolution;
 import org.acumos.cds.domain.MLPSolutionRevision;
+import org.acumos.federation.gateway.util.Utils;
+import org.acumos.federation.gateway.common.API;
 import org.acumos.federation.gateway.common.JSONTags;
 import org.acumos.federation.gateway.common.JsonResponse;
-import org.acumos.federation.gateway.config.APINames;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.acumos.federation.gateway.service.CatalogService;
 import org.acumos.federation.gateway.service.ServiceContext;
@@ -76,7 +82,7 @@ public class CatalogController extends AbstractController {
 //      */
 //     @CrossOrigin
 //     @ApiOperation(value = "Invoked by Peer Acumos to get a Paginated list of Published Solutions from the Catalog of the local Acumos Instance .", response = MLPSolution.class, responseContainer = "Page")
-//     @RequestMapping(value = {APINames.PEER_SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+//     @RequestMapping(value = {API.Paths.SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
 //     @ResponseBody
 //     public JsonResponse<RestPageResponse<MLPSolution>> getSolutionsListFromPeer(HttpServletRequest request, HttpServletResponse response,
 //                     @RequestParam("pageNumber") Integer pageNumber, @RequestParam("maxSize") Integer maxSize, 
@@ -107,19 +113,25 @@ public class CatalogController extends AbstractController {
 //@PreAuthorize("hasAuthority('PEER')"
        @PreAuthorize("hasAuthority(T(org.acumos.federation.gateway.security.Priviledge).CATALOG_ACCESS)")
        @ApiOperation(value = "Invoked by Peer Acumos to get a list of Published Solutions from the Catalog of the local Acumos Instance .", response = MLPSolution.class, responseContainer = "List")
-       @RequestMapping(value = {APINames.PEER_SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<List<MLPSolution>> getSolutions(
                        /* HttpServletRequest theHttpRequest,*/
                        HttpServletResponse theHttpResponse,
-                       @RequestParam(value = "modelTypeCode", required = false) String mlpModelTypes) {
+                       @RequestParam(value = API.QueryParameters.SOLUTIONS_SELECTOR,
+                                                                               required = false) String theSelector) {
                JsonResponse<List<MLPSolution>> response = null;
                List<MLPSolution> peerCatalogSolutions = null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTIONS);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.SOLUTIONS);
                try {
                        response = new JsonResponse<List<MLPSolution>>();
-                       log.debug(EELFLoggerDelegate.debugLogger, "getSolutionsListFromPeer: model types " + mlpModelTypes);
-                       peerCatalogSolutions = catalogService.getSolutions(mlpModelTypes, new ControllerContext());
+                       log.debug(EELFLoggerDelegate.debugLogger, "getSolutionsListFromPeer: selector " + theSelector);
+                       Map<String,?> selector = null;
+                       if (theSelector != null) 
+                               selector = Utils.jsonStringToMap(new String(Base64Utils.decodeFromString(theSelector), "UTF-8"));
+                               
+                       peerCatalogSolutions =
+                                       catalogService.getSolutions(selector, new ControllerContext());
                        if(peerCatalogSolutions != null) {
                                response.setResponseBody(peerCatalogSolutions);
                                response.setResponseCode(String.valueOf(HttpServletResponse.SC_OK));
@@ -141,14 +153,14 @@ public class CatalogController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('CATALOG_ACCESS')")
        @ApiOperation(value = "Invoked by Peer Acumos to get a list detailed solution information from the Catalog of the local Acumos Instance .", response = MLPSolution.class)
-       @RequestMapping(value = {APINames.PEER_SOLUTION_DETAILS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.SOLUTION_DETAILS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<MLPSolution> getSolutionDetails(
                        HttpServletResponse theHttpResponse,
                        @PathVariable(value="solutionId") String theSolutionId) {
                JsonResponse<MLPSolution> response = null;
                MLPSolution solution = null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTION_DETAILS + ": " + theSolutionId);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.SOLUTION_DETAILS + ": " + theSolutionId);
                try {
                        response = new JsonResponse<MLPSolution>();
                        solution = catalogService.getSolution(theSolutionId, new ControllerContext());
@@ -182,14 +194,14 @@ public class CatalogController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('CATALOG_ACCESS')")
        @ApiOperation(value = "Invoked by Peer Acumos to get a list of Solution Revision from the Catalog of the local Acumos Instance .", response = MLPSolutionRevision.class, responseContainer = "List")
-       @RequestMapping(value = {APINames.PEER_SOLUTION_REVISIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.SOLUTION_REVISIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<List<MLPSolutionRevision>> getSolutionRevisions(
                        HttpServletResponse theHttpResponse,
                        @PathVariable("solutionId") String theSolutionId) {
                JsonResponse<List<MLPSolutionRevision>> response = null;
                List<MLPSolutionRevision> solutionRevisions= null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTION_REVISIONS);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.SOLUTION_REVISIONS);
                try {
                        response = new JsonResponse<List<MLPSolutionRevision>>();
                        solutionRevisions = catalogService.getSolutionRevisions(theSolutionId, new ControllerContext());
@@ -222,7 +234,7 @@ public class CatalogController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('CATALOG_ACCESS')")
        @ApiOperation(value = "Invoked by Peer Acumos to get Solution Revision details from the Catalog of the local Acumos Instance .", response = MLPSolutionRevision.class)
-       @RequestMapping(value = {APINames.PEER_SOLUTION_REVISION_DETAILS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.SOLUTION_REVISION_DETAILS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<MLPSolutionRevision> getSolutionRevisionDetails(
                        HttpServletResponse theHttpResponse,
@@ -230,7 +242,7 @@ public class CatalogController extends AbstractController {
                        @PathVariable("revisionId") String theRevisionId) {
                JsonResponse<MLPSolutionRevision> response = null;
                MLPSolutionRevision solutionRevision= null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTION_REVISION_DETAILS);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.SOLUTION_REVISION_DETAILS + "(" + theSolutionId + "," + theRevisionId + ")");
                try {
                        response = new JsonResponse<MLPSolutionRevision>();
                        solutionRevision = catalogService.getSolutionRevision(theSolutionId, theRevisionId, new ControllerContext());
@@ -262,7 +274,7 @@ public class CatalogController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('CATALOG_ACCESS')")
        @ApiOperation(value = "Invoked by Peer Acumos to get a list of Solution Revision Artifacts from the Catalog of the local Acumos Instance .", response = MLPArtifact.class, responseContainer = "List")
-       @RequestMapping(value = {APINames.PEER_SOLUTION_REVISION_ARTIFACTS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.SOLUTION_REVISION_ARTIFACTS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<List<MLPArtifact>> getSolutionRevisionArtifacts (
                        HttpServletRequest theHttpRequest,
@@ -271,22 +283,24 @@ public class CatalogController extends AbstractController {
                        @PathVariable("revisionId") String theRevisionId) {
                JsonResponse<List<MLPArtifact>> response = null;
                List<MLPArtifact> solutionRevisionArtifacts= null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTION_REVISION_ARTIFACTS + ":" + theSolutionId + ":" + theRevisionId);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.SOLUTION_REVISION_ARTIFACTS + "(" + theSolutionId + "," + theRevisionId + ")");
                try {
                        response = new JsonResponse<List<MLPArtifact>>();
                        solutionRevisionArtifacts = catalogService.getSolutionRevisionArtifacts(theSolutionId, theRevisionId, new ControllerContext());
                        if(solutionRevisionArtifacts != null) {
                                //re-encode the artifact uri
                                {
-                     UriComponentsBuilder uriBuilder = 
-                                               UriComponentsBuilder.fromHttpUrl(theHttpRequest.getRequestURL().toString());
-
                                        for (MLPArtifact artifact: solutionRevisionArtifacts) {
-                                               artifact.setUri(uriBuilder.replacePath("/artifacts/" + artifact.getArtifactId() + "/download")
-                                                                                                                                                       .toUriString());
+                                               //sooo cumbersome
+                                               URI requestUri = new URI(theHttpRequest.getRequestURL().toString());
+                                               URI artifactUri = 
+                                                       API.ARTIFACT_DOWNLOAD.buildUri(
+                                                               new URI(requestUri.getScheme(), null, requestUri.getHost(), requestUri.getPort(), null, null, null).toString(),
+                                                               artifact.getArtifactId());
+                                               log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisionArtifacts: content uri " + artifactUri);
+                                               artifact.setUri(artifactUri.toString());
                                        }
                                }
-
                                response.setResponseBody(solutionRevisionArtifacts);
                                response.setResponseCode(String.valueOf(HttpServletResponse.SC_OK));
                                response.setResponseDetail(JSONTags.TAG_STATUS_SUCCESS);
@@ -300,7 +314,7 @@ public class CatalogController extends AbstractController {
                        response.setResponseDetail(JSONTags.TAG_STATUS_FAILURE);
                        response.setStatus(false);
                        theHttpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
-                       log.error(EELFLoggerDelegate.errorLogger, "Exception Occurred Fetching Solution Revisions Artifacts for Market Place Catalog", e);
+                       log.error(EELFLoggerDelegate.errorLogger, "Failed to fetch solution revision artifacts", e);
                }
                return response;
        }
@@ -315,7 +329,7 @@ public class CatalogController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('CATALOG_ACCESS')")
        @ApiOperation(value = "API to download the Machine Learning Artifact of the Machine Learning Solution", response = InputStreamResource.class, code = 200)
-       @RequestMapping(value = {APINames.PEER_ARTIFACT_DOWNLOAD}, method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
+       @RequestMapping(value = {API.Paths.ARTIFACT_DOWNLOAD}, method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
        @ResponseBody
        public InputStreamResource downloadSolutionArtifact(
                        HttpServletRequest theHttpRequest,
@@ -324,7 +338,6 @@ public class CatalogController extends AbstractController {
                InputStreamResource inputStreamResource = null;
                try {
                        inputStreamResource = catalogService.getSolutionRevisionArtifactContent(theArtifactId, new ControllerContext());
-                       //TODO : Need to Implement a logic to download a Artifact or Docker Image from Nexus
                        theHttpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
                        theHttpResponse.setHeader("Pragma", "no-cache");
                        theHttpResponse.setHeader("Expires", "0");
@@ -337,8 +350,6 @@ public class CatalogController extends AbstractController {
                return inputStreamResource;
        }
 
-       /**
-        */
        protected class ControllerContext implements ServiceContext {
 
                public Peer getPeer() {
index 13220e8..42ab9c1 100644 (file)
@@ -44,7 +44,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
 import org.acumos.cds.domain.MLPPeer;
 import org.acumos.federation.gateway.common.JSONTags;
 import org.acumos.federation.gateway.common.JsonResponse;
-import org.acumos.federation.gateway.config.APINames;
+import org.acumos.federation.gateway.common.API;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.acumos.federation.gateway.service.PeerService;
 import org.acumos.federation.gateway.service.ServiceContext;
@@ -74,7 +74,7 @@ public class PeerController extends AbstractController {
        @CrossOrigin
        @PreAuthorize("hasAuthority('PEERS_ACCESS')")
        @ApiOperation(value = "Invoked by Peer Acumos to get a list of peers from local Acumos Instance .", response = MLPPeer.class, responseContainer = "List")
-       @RequestMapping(value = {APINames.PEER_PEERS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
+       @RequestMapping(value = {API.Paths.PEERS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
        @ResponseBody
        public JsonResponse<List<MLPPeer>> getSolutions(
                        /* HttpServletRequest theHttpRequest,*/
@@ -82,7 +82,7 @@ public class PeerController extends AbstractController {
 
                JsonResponse<List<MLPPeer>> response = null;
                List<MLPPeer> peers = null;
-               log.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_PEERS);
+               log.debug(EELFLoggerDelegate.debugLogger, API.Paths.PEERS);
                try {
                        response = new JsonResponse<List<MLPPeer>>();
                        log.debug(EELFLoggerDelegate.debugLogger, "getPeers");
index 30f063f..95747c2 100644 (file)
@@ -23,8 +23,8 @@
  */
 package org.acumos.federation.gateway.service;
 
-import java.io.File;
 import java.util.List;
+import java.util.Map;
 
 import org.springframework.core.io.InputStreamResource;
 
@@ -68,7 +68,7 @@ public interface CatalogService {
         * 
         * @return List of the Catalog Solutions for the specified list of query parameters
         */
-       List<MLPSolution> getSolutions(String mlpModelTypes, ServiceContext theContext);
+       List<MLPSolution> getSolutions(Map<String,?> theSelector, ServiceContext theContext);
        
 
        /**
index 7ce7572..39d28b6 100644 (file)
@@ -36,8 +36,6 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.acumos.federation.gateway.common.JsonResponse;
-import org.acumos.federation.gateway.config.APIConstants;
-import org.acumos.federation.gateway.config.APINames;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.springframework.core.ParameterizedTypeReference;
 import org.springframework.http.HttpMethod;
index 1e39bd0..7276a7c 100644 (file)
@@ -97,16 +97,29 @@ public class CatalogServiceImpl
 */
        @Override
        public List<MLPSolution> getSolutions(
-               String mlpModelTypes, ServiceContext theContext) {
+               Map<String,?> theSelector, ServiceContext theContext) {
                
                log.debug(EELFLoggerDelegate.debugLogger, "getSolutions");
                List<MLPSolution> filteredMLPSolutions = null;
-               ICommonDataServiceRestClient dataServiceRestClient = getClient();
+               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> queryParameters = new HashMap<String, Object>(this.baseSelector);
-               List<MLPSolution> mlpSolutions = dataServiceRestClient.searchSolutions(queryParameters, false);
-               log.debug(EELFLoggerDelegate.debugLogger, "getSolutions: data service provided solutions " + mlpSolutions);
+       
+               Map<String, Object> selector =
+                               new HashMap<String, Object>(this.baseSelector);
+               if (theSelector != null)
+                       selector.putAll(theSelector);
 
+               List<MLPSolution> solutions = cdsClient.searchSolutions(selector, false);
+               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()
@@ -115,10 +128,12 @@ public class CatalogServiceImpl
                                                                                                                                                                                                                                                                mlpModelTypes.contains(modelType);      
                                                                                                                                                                                                                         })
                                                                                                                                .collect(Collectors.toList());
-               } else {
+               }
+               else {
                        filteredMLPSolutions = mlpSolutions;
                }
                return filteredMLPSolutions;
+               */
        }
 
        @Override
index 647e7fe..72fcc3c 100644 (file)
@@ -126,11 +126,14 @@ public class CatalogServiceLocalImpl extends AbstractServiceLocalImpl
 
        @Override
        public List<MLPSolution> getSolutions(
-               String mlpModelTypes, ServiceContext theContext) {
+               Map<String,?> theSelector, ServiceContext theContext) {
 
                log.debug(EELFLoggerDelegate.debugLogger, "getSolutions");
+               String modelTypeSelector = theSelector == null ? null
+                                                                                                                                                                                                        :(String)theSelector.get("modelTypeCode");
                final List<String> modelTypes =
-                       mlpModelTypes == null ? null : Arrays.asList(mlpModelTypes.split(","));
+                       modelTypeSelector == null ? null
+                                                                                                                               : Arrays.asList(modelTypeSelector.split(","));
                return solutions.stream()
                                                        .filter(solution -> {
                log.debug(EELFLoggerDelegate.debugLogger, "getPeerCatalogSolutionsList: looking for " + modelTypes + ", has " + solution.getModelTypeCode());
@@ -201,8 +204,23 @@ public class CatalogServiceLocalImpl extends AbstractServiceLocalImpl
                String theArtifactId, ServiceContext theContext) {
 
                log.debug(EELFLoggerDelegate.debugLogger, "getSolutionRevisionArtifactContent");
-               //difficult here as we only have the artifact id ..
-       
+               //cumbersome
+               for (FLPSolution solution: this.solutions) {
+                       for (FLPRevision revision: solution.getRevisions()) {
+                               for (MLPArtifact artifact: revision.getArtifacts()) {
+                                       if (artifact.getArtifactId().equals(theArtifactId)) {
+                                               try {
+                                                       return new InputStreamResource(
+                                                                                                       new URI(artifact.getUri()).toURL().openStream());
+                                               }
+                                               catch (Exception x) {
+                                                       log.debug(EELFLoggerDelegate.debugLogger, "failed to load content from " + artifact.getUri(), x);
+                                               }
+                                       }
+                               }
+                       }
+               }
+
                return null;
        }
 
@@ -238,8 +256,25 @@ public class CatalogServiceLocalImpl extends AbstractServiceLocalImpl
                private List<MLPArtifact> artifacts;
 
                //@JsonIgnore
+               //we send a deep clone as the client can modify them and we only have one copy
                public List<MLPArtifact> getArtifacts() {
-                       return this.artifacts;
+                       List<MLPArtifact> copy = new LinkedList<MLPArtifact>();
+                       for (MLPArtifact artifact: this.artifacts) {
+                               MLPArtifact acopy = new MLPArtifact();
+                               acopy.setArtifactId(artifact.getArtifactId());
+                               acopy.setArtifactTypeCode(artifact.getArtifactTypeCode());
+                               acopy.setDescription(artifact.getDescription());
+                               acopy.setUri(artifact.getUri());
+                               acopy.setName(artifact.getName());
+                               acopy.setSize(artifact.getSize());
+                               acopy.setOwnerId(artifact.getOwnerId());
+                               acopy.setCreated(artifact.getCreated());
+                               acopy.setModified(artifact.getModified());
+                               acopy.setMetadata(artifact.getMetadata());
+
+                               copy.add(acopy);
+                       }
+                       return copy;
                }
 
                public void setArtifacts(List<MLPArtifact> theArtifacts) {
index af648b5..0d8910d 100644 (file)
@@ -26,20 +26,27 @@ import java.net.URL;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
+import java.util.HashMap;
+import java.util.Collections;
 
 import org.apache.http.client.HttpClient;
 
 import org.acumos.federation.gateway.common.JsonResponse;
-import org.acumos.federation.gateway.config.APIConstants;
-import org.acumos.federation.gateway.config.APINames;
+import org.acumos.federation.gateway.common.API;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
+import org.acumos.federation.gateway.util.Utils;
+
 import org.springframework.core.ParameterizedTypeReference;
 import org.springframework.http.HttpMethod;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.client.HttpStatusCodeException;
 import org.springframework.web.client.RestTemplate;
 import org.springframework.boot.web.client.RestTemplateBuilder;
-import org.springframework.web.util.UriComponentsBuilder;
+import org.springframework.core.io.Resource;
+
+//import org.springframework.web.util.UriComponentsBuilder;
+import org.springframework.web.util.UriUtils;
+import org.springframework.util.Base64Utils;
 
 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 
@@ -82,11 +89,24 @@ public class FederationClient extends AbstractClient {
         * @throws HttpStatusCodeException
         *              Throws HttpStatusCodeException is remote acumos is not available
         */
-       public JsonResponse<List<MLPSolution>> getSolutionsListFromPeer(Map<String, Object> queryParameters) throws HttpStatusCodeException {
-               URI uri = buildUri(new String[] { APIConstants.SOLUTIONS }, queryParameters,
-                               null);
-               logger.info(EELFLoggerDelegate.debugLogger, "getPeerSubscriptions: uri " + uri);
-               System.out.println("getPeerSubscriptions: uri " + uri);
+       public JsonResponse<List<MLPSolution>> getSolutions(Map<String, Object> theSelection) throws HttpStatusCodeException {
+
+               String selectorParam = null;
+               try {
+                       selectorParam = theSelection == null ? null
+                                                                                                                                                                        //: UriUtils.encodeQueryParam(Utils.mapToJsonString(theSelection),"UTF-8"); 
+                                                                                                                                                                        : Base64Utils.encodeToString(Utils.mapToJsonString(theSelection).getBytes("UTF-8")); 
+               }
+               catch (Exception x) {
+                       throw new IllegalArgumentException("Cannot process the selection argument", x);
+               }
+
+               URI uri =       
+                       API.SOLUTIONS.buildUri(
+                               this.baseUrl,
+                               selectorParam == null ? Collections.EMPTY_MAP
+                                                                                                                       : Collections.singletonMap(API.QueryParameters.SOLUTIONS_SELECTOR, selectorParam));
+               logger.info(EELFLoggerDelegate.debugLogger, "Query for " + uri);
                ResponseEntity<JsonResponse<List<MLPSolution>>> response = null;
                try {
                        response = restTemplate.exchange(
@@ -96,14 +116,14 @@ public class FederationClient extends AbstractClient {
                                                                        new ParameterizedTypeReference<JsonResponse<List<MLPSolution>>>() {});
                }
                catch (HttpStatusCodeException x) {
-               System.out.println("getPeerSubscriptions: error " + x);
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " failed.", x);
                        throw x;
                }
                catch (Throwable t) {
-                       System.out.println("getPeerSubscriptions: error " + t);
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " unexpected failure.", t);
                }
                finally {
-               System.out.println("getPeerSubscriptions: response " + response);
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " response " + response);
                }
                return response == null ? null : response.getBody();
        }
@@ -117,14 +137,31 @@ public class FederationClient extends AbstractClient {
         * @throws HttpStatusCodeException
         *              Throws HttpStatusCodeException is remote acumos is not available
         */
-       public JsonResponse<List<MLPSolutionRevision>> getSolutionsRevisionListFromPeer(String solutinoId, Map<String, Object> queryParameters) throws HttpStatusCodeException {
-               URI uri = buildUri(new String[] { APIConstants.SOLUTIONS, solutinoId, APIConstants.REVISIONS }, queryParameters,
-                               null);
-               logger.info(EELFLoggerDelegate.debugLogger, "getPeerSubscriptions: uri " + uri);
-               ResponseEntity<JsonResponse<List<MLPSolutionRevision>>> response = restTemplate.exchange(uri, HttpMethod.GET,
-                               null, new ParameterizedTypeReference<JsonResponse<List<MLPSolutionRevision>>>() {
+       public JsonResponse<List<MLPSolutionRevision>> getSolutionRevisions(
+               String theSolutionId)   throws HttpStatusCodeException {
+
+               URI uri =       API.SOLUTION_REVISIONS.buildUri(this.baseUrl, theSolutionId);
+               logger.info(EELFLoggerDelegate.debugLogger, "Query for " + uri);
+               ResponseEntity<JsonResponse<List<MLPSolutionRevision>>> response = null;
+               try {
+                       response = restTemplate.exchange(
+                                                                       uri,
+                                                                       HttpMethod.GET,
+                                                                       null,
+                                                                       new ParameterizedTypeReference<JsonResponse<List<MLPSolutionRevision>>>() {
                                });
-               return response.getBody();
+               }
+               catch (HttpStatusCodeException x) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " failed.", x);
+                       throw x;
+               }
+               catch (Throwable t) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " unexpected failure.", t);
+               }
+               finally {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " response " + response);
+               }
+               return response == null ? null : response.getBody();
        }
        
        /**
@@ -136,13 +173,57 @@ public class FederationClient extends AbstractClient {
         * @throws HttpStatusCodeException
         *              Throws HttpStatusCodeException is remote acumos is not available
         */
-       public JsonResponse<List<MLPArtifact>> getArtifactsListFromPeer(String solutinoId, String revisionId, Map<String, Object> queryParameters) throws HttpStatusCodeException {
-               URI uri = buildUri(new String[] { APIConstants.SOLUTIONS, solutinoId, APIConstants.REVISIONS, revisionId }, queryParameters,
-                               null);
-               logger.info(EELFLoggerDelegate.debugLogger, "getPeerSubscriptions: uri " + uri);
-               ResponseEntity<JsonResponse<List<MLPArtifact>>> response = restTemplate.exchange(uri, HttpMethod.GET,
-                               null, new ParameterizedTypeReference<JsonResponse<List<MLPArtifact>>>() {
+       public JsonResponse<List<MLPArtifact>> getArtifacts(
+               String theSolutionId, String theRevisionId) throws HttpStatusCodeException {
+               URI uri =       API.SOLUTION_REVISION_ARTIFACTS.buildUri(this.baseUrl, theSolutionId, theRevisionId);
+               logger.info(EELFLoggerDelegate.debugLogger, "Query for " + uri);
+               ResponseEntity<JsonResponse<List<MLPArtifact>>> response = null;
+               try {
+                       response = restTemplate.exchange(
+                                                                       uri,
+                                                                       HttpMethod.GET,
+                                                                       null,
+                                                                       new ParameterizedTypeReference<JsonResponse<List<MLPArtifact>>>() {
                                });
-               return response.getBody();
+               }
+               catch (HttpStatusCodeException x) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " failed.", x);
+                       throw x;
+               }
+               catch (Throwable t) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " unexpected failure.", t);
+               }
+               finally {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " response " + response);
+               }
+               return response == null ? null : response.getBody();
+       }
+       
+       /**
+        */
+       public Resource downloadArtifact(String theArtifactId) 
+                                                                                                                                                                                               throws HttpStatusCodeException {
+               URI uri =       API.ARTIFACT_DOWNLOAD.buildUri(this.baseUrl, theArtifactId);
+               logger.info(EELFLoggerDelegate.debugLogger, "Query for " + uri);
+               ResponseEntity<Resource> response = null;
+               try {
+                       response = restTemplate.exchange(
+                                                                       uri,
+                                                                       HttpMethod.GET,
+                                                                       null,
+                                                                       Resource.class);
+               }
+               catch (HttpStatusCodeException x) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " failed.", x);
+                       throw x;
+               }
+               catch (Throwable t) {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " unexpected failure.", t);
+               }
+               finally {
+                       logger.info(EELFLoggerDelegate.debugLogger, uri + " response " + response);
+               }
+               return response == null ? null : response.getBody();
        }
+
 }
index 0726732..4dc25b2 100644 (file)
@@ -30,8 +30,6 @@ import java.util.Map;
 import org.apache.http.client.HttpClient;
 
 import org.acumos.federation.gateway.common.JsonResponse;
-import org.acumos.federation.gateway.config.APIConstants;
-import org.acumos.federation.gateway.config.APINames;
 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
 import org.springframework.core.ParameterizedTypeReference;
 import org.springframework.http.HttpMethod;
index f79dd2b..c44bc47 100644 (file)
@@ -105,7 +105,7 @@ public class PeerCommunicationTask implements Runnable {
        logger.info(EELFLoggerDelegate.debugLogger, "Peer Task: filter " + mlpSubscription.getSelector());
                        
        JsonResponse<List<MLPSolution>> jsonResponse = 
-                                               fedClient.getSolutionsListFromPeer(
+                                               fedClient.getSolutions(
                                                        Utils.jsonStringToMap(mlpSubscription.getSelector()));
                        if(jsonResponse != null && jsonResponse.getResponseBody() != null) {
                                List<MLPSolution> mlpSolutions = jsonResponse.getResponseBody();
index da9af74..7f45c7e 100644 (file)
@@ -34,6 +34,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 
 import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
 import com.fasterxml.jackson.databind.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -74,20 +75,23 @@ public class Utils {
                        try {
                                map = objectMapper.readValue(jsonString, new TypeReference<Map< String, Object>>() {
                                });
-                       } catch (JsonParseException e) {
-                               // TODO Auto-generated catch block
-                               e.printStackTrace();
-                       } catch (JsonMappingException e) {
-                               // TODO Auto-generated catch block
-                               e.printStackTrace();
-                       } catch (IOException e) {
-                               // TODO Auto-generated catch block
-                               e.printStackTrace();
+                       }
+                       catch (IOException x) {
+                               throw new IllegalArgumentException("Argument not a map", x);
                        }
                }
                return map;
        }
-       
+
+       public static String mapToJsonString(Map<String,?> theMap) {
+
+               try {
+                       return objectMapper.writeValueAsString(theMap);
+               }
+               catch (JsonProcessingException x) {
+                       throw new IllegalArgumentException("Failed to convert", x);
+               }
+       }       
        
        /**
         * 
index cafbbaf..f5b78fb 100644 (file)
@@ -185,7 +185,7 @@ public class PeerGatewayTest {
                assertTrue(response.getStatusCodeValue() == 200);
                assertTrue(response.getBody().getResponseBody().size() == 1); //no errors
        }
-
+/*
        @Test
        public void testPeersForbidden() {
 
@@ -203,7 +203,7 @@ public class PeerGatewayTest {
 
                assertTrue(response.getStatusCodeValue() == 403);
        }
-
+*/
        private HttpEntity prepareRequest(String theResourceName) {
                String content = new Scanner(
                                                                           Thread.currentThread().getContextClassLoader().getResourceAsStream(theResourceName), "UTF-8")
index 0022122..32c6536 100644 (file)
@@ -24,7 +24,7 @@
      {
       "artifactId":"4fd46d93-e627-473b-a984-be9898ad1123",
       "name":"configuration",
-      "uri":"/home/src/acumos/federation/gateway/application-acumosa.properties",
+      "uri":"classpath:application-acumosa.properties",
       "metadata":"acumosa",
          "created":"2017-08-10",
          "modified":"2017-08-11"
index 3b2911f..3c7b861 100644 (file)
@@ -24,7 +24,7 @@
      {
       "artifactId":"2a0f28e3-ccd9-40e1-a57c-62a57fb46b76",
       "name":"configuration",
-      "uri":"/home/src/acumos/federation/gateway/application-acumosb.properties",
+      "uri":"classpath:application-acumosb.properties",
       "metadata":"acumosb",
          "created":"2017-09-10",
          "modified":"2017-09-11"