b0081cb927c8c60a143b66544bd3ab53c0cdf095
[federation.git] / gateway / src / main / java / org / acumos / federation / gateway / controller / FederationController.java
1 /*-
2  * ===============LICENSE_START=======================================================
3  * Acumos
4  * ===================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
6  * ===================================================================================
7  * This Acumos software file is distributed by AT&T and Tech Mahindra
8  * under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *  
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *  
14  * This file is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ===============LICENSE_END=========================================================
19  */
20
21 package org.acumos.federation.gateway.controller;
22
23 import java.util.List;
24
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.springframework.beans.factory.annotation.Autowired;
29 import org.springframework.core.io.InputStreamResource;
30 import org.springframework.http.HttpEntity;
31 import org.springframework.http.MediaType;
32 import org.springframework.http.ResponseEntity;
33 import org.springframework.security.access.prepost.PreAuthorize;
34 import org.springframework.stereotype.Controller;
35 import org.springframework.web.util.UriComponentsBuilder;
36 import org.springframework.web.bind.annotation.CrossOrigin;
37 import org.springframework.web.bind.annotation.PathVariable;
38 import org.springframework.web.bind.annotation.RequestMapping;
39 import org.springframework.web.bind.annotation.RequestMethod;
40 import org.springframework.web.bind.annotation.RequestParam;
41 import org.springframework.web.bind.annotation.ResponseBody;
42
43 import org.acumos.cds.domain.MLPArtifact;
44 import org.acumos.cds.domain.MLPSolution;
45 import org.acumos.cds.domain.MLPSolutionRevision;
46 import org.acumos.federation.gateway.common.JSONTags;
47 import org.acumos.federation.gateway.common.JsonResponse;
48 import org.acumos.federation.gateway.config.APINames;
49 import org.acumos.federation.gateway.config.EELFLoggerDelegate;
50 import org.acumos.federation.gateway.service.FederationService;
51
52 import io.swagger.annotations.ApiOperation;
53
54 /**
55  * 
56  *
57  */
58 @Controller
59 @RequestMapping("/")
60 public class FederationController extends AbstractController {
61         
62         private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FederationController.class);
63         
64         @Autowired
65         FederationService federationService;
66         
67         
68 //      /**
69 //       * @param request
70 //       *            HttpServletRequest
71 //       * @param response
72 //       *                      HttpServletResponse
73 //       * @return List of Published ML Solutions in JSON format.
74 //       */
75 //      @CrossOrigin
76 //      @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")
77 //      @RequestMapping(value = {APINames.PEER_SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
78 //      @ResponseBody
79 //      public JsonResponse<RestPageResponse<MLPSolution>> getSolutionsListFromPeer(HttpServletRequest request, HttpServletResponse response,
80 //                      @RequestParam("pageNumber") Integer pageNumber, @RequestParam("maxSize") Integer maxSize, 
81 //                      @RequestParam(required = false) String sortingOrder, @RequestParam(required = false) String mlpModelTypes) {
82 //              JsonResponse<RestPageResponse<MLPSolution>> data = null;
83 //              RestPageResponse<MLPSolution> peerCatalogSolutions = null;
84 //              try {
85 //                      data = new JsonResponse<RestPageResponse<MLPSolution>>();
86 //                      peerCatalogSolutions = federationGatewayService.getPeerCatalogSolutions(pageNumber, maxSize, sortingOrder, null);
87 //                      if(peerCatalogSolutions != null) {
88 //                              data.setResponseBody(peerCatalogSolutions);
89 //                              logger.debug(EELFLoggerDelegate.debugLogger, "getSolutionsListFromPeer: size is {} ");
90 //                      }
91 //              } catch (Exception e) {
92 //                      logger.error(EELFLoggerDelegate.errorLogger, "Exception Occurred Fetching Solutions for Market Place Catalog", e);
93 //              }
94 //              return data;
95 //      }
96         
97         /**
98          * @param request
99          *            HttpServletRequest
100          * @param response
101          *                      HttpServletResponse
102          * @return List of Published ML Solutions in JSON format.
103          */
104         @CrossOrigin
105         @PreAuthorize("hasAuthority('PEER')")
106         @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")
107         @RequestMapping(value = {APINames.PEER_SOLUTIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
108         @ResponseBody
109         public JsonResponse<List<MLPSolution>> getSolutionsListFromPeer(HttpServletRequest request, HttpServletResponse response, 
110                         @RequestParam(value = "modelTypeCode", required = false) String mlpModelTypes) {
111                 JsonResponse<List<MLPSolution>> data = null;
112                 List<MLPSolution> peerCatalogSolutions = null;
113                 logger.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTIONS);
114                 try {
115                         data = new JsonResponse<List<MLPSolution>>();
116                         logger.debug(EELFLoggerDelegate.debugLogger, "getSolutionsListFromPeer: model types " + mlpModelTypes);
117                         peerCatalogSolutions = federationService.getPeerCatalogSolutionsList(mlpModelTypes);
118                         if(peerCatalogSolutions != null) {
119                                 data.setResponseBody(peerCatalogSolutions);
120                                 data.setResponseCode(String.valueOf(HttpServletResponse.SC_OK));
121                                 data.setResponseDetail(JSONTags.TAG_STATUS_SUCCESS);
122                                 data.setStatus(true);
123                                 response.setStatus(HttpServletResponse.SC_OK);
124                                 logger.debug(EELFLoggerDelegate.debugLogger, "getSolutionsListFromPeer: size is " + peerCatalogSolutions.size());
125                         }
126                 } catch (Exception e) {
127                         data.setResponseCode(String.valueOf(HttpServletResponse.SC_BAD_REQUEST));
128                         data.setResponseDetail(JSONTags.TAG_STATUS_FAILURE);
129                         data.setStatus(false);
130                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
131                         logger.error(EELFLoggerDelegate.errorLogger, "Exception Occurred Fetching Solutions for Market Place Catalog", e);
132                 }
133                 return data;
134         }
135         
136         /**
137          * @param request
138          *            HttpServletRequest
139          * @param response
140          *                      HttpServletResponse
141          * @return List of Published ML Solutions in JSON format.
142          */
143         @CrossOrigin
144         @PreAuthorize("hasAuthority('PEER')")
145         @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")
146         @RequestMapping(value = {APINames.PEER_SOLUTIONS_REVISIONS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
147         @ResponseBody
148         public JsonResponse<List<MLPSolutionRevision>> getSolutionsRevisionListFromPeer(HttpServletRequest request, HttpServletResponse response, 
149                         @PathVariable("solutionId") String solutionId) {
150                 JsonResponse<List<MLPSolutionRevision>> data = null;
151                 List<MLPSolutionRevision> peerCatalogSolutionRevisions= null;
152                 logger.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTIONS_REVISIONS);
153                 try {
154                         data = new JsonResponse<List<MLPSolutionRevision>>();
155                         peerCatalogSolutionRevisions = federationService.getPeerCatalogSolutionRevision(solutionId);
156                         if(peerCatalogSolutionRevisions != null) {
157                                 data.setResponseBody(peerCatalogSolutionRevisions);
158                                 data.setResponseCode(String.valueOf(HttpServletResponse.SC_OK));
159                                 data.setResponseDetail(JSONTags.TAG_STATUS_SUCCESS);
160                                 data.setStatus(true);
161                                 response.setStatus(HttpServletResponse.SC_OK);
162                                 logger.debug(EELFLoggerDelegate.debugLogger, "getSolutionsRevisionListFromPeer: size is {} ", peerCatalogSolutionRevisions.size());
163                         }
164                 } catch (Exception e) {
165                         data.setResponseCode(String.valueOf(HttpServletResponse.SC_BAD_REQUEST));
166                         data.setResponseDetail(JSONTags.TAG_STATUS_FAILURE);
167                         data.setStatus(false);
168                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
169                         logger.error(EELFLoggerDelegate.errorLogger, "Exception Occurred Fetching Solution Revisions for Market Place Catalog", e);
170                 }
171                 return data;
172         }
173         
174         /**
175          * @param request
176          *            HttpServletRequest
177          * @param response
178          *                      HttpServletResponse
179          * @return List of Published ML Solutions in JSON format.
180          */
181         @CrossOrigin
182         @PreAuthorize("hasAuthority('PEER')")
183         @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")
184         @RequestMapping(value = {APINames.PEER_SOLUTIONS_REVISIONS_ARTIFACTS}, method = RequestMethod.GET, produces = APPLICATION_JSON)
185         @ResponseBody
186         public JsonResponse<List<MLPArtifact>> getSolutionsRevisionArtifactListFromPeer(HttpServletRequest request, HttpServletResponse response, 
187                         @PathVariable("solutionId") String solutionId, @PathVariable("revisionId") String revisionId) {
188                 JsonResponse<List<MLPArtifact>> data = null;
189                 List<MLPArtifact> peerSolutionArtifacts= null;
190                 logger.debug(EELFLoggerDelegate.debugLogger, APINames.PEER_SOLUTIONS_REVISIONS_ARTIFACTS);
191                 try {
192                         data = new JsonResponse<List<MLPArtifact>>();
193                         peerSolutionArtifacts = federationService.getPeerSolutionArtifacts(solutionId, revisionId);
194                         if(peerSolutionArtifacts != null) {
195                                 //re-encode the artifact uri
196                                 {
197                       UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(request.getRequestURL().toString());
198
199                                         for (MLPArtifact artifact: peerSolutionArtifacts) {
200                                                 artifact.setUri(uriBuilder.replacePath("/artifacts/" + artifact.getArtifactId() + "/download")
201                                                                                                                                                         .toUriString());
202                                         }
203                                 }
204
205                                 data.setResponseBody(peerSolutionArtifacts);
206                                 data.setResponseCode(String.valueOf(HttpServletResponse.SC_OK));
207                                 data.setResponseDetail(JSONTags.TAG_STATUS_SUCCESS);
208                                 data.setStatus(true);
209                                 response.setStatus(HttpServletResponse.SC_OK);
210                                 logger.debug(EELFLoggerDelegate.debugLogger, "getSolutionsRevisionArtifactListFromPeer: size is {} ", peerSolutionArtifacts.size());
211                         }
212                 } catch (Exception e) {
213                         data.setResponseCode(String.valueOf(HttpServletResponse.SC_BAD_REQUEST));
214                         data.setResponseDetail(JSONTags.TAG_STATUS_FAILURE);
215                         data.setStatus(false);
216                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
217                         logger.error(EELFLoggerDelegate.errorLogger, "Exception Occurred Fetching Solution Revisions Artifacts for Market Place Catalog", e);
218                 }
219                 return data;
220         }
221         
222         /**
223          * @param request
224          *            HttpServletRequest
225          * @param response
226          *                      HttpServletResponse
227          * @return Archive file of the Artifact for the Solution.
228          */
229         @CrossOrigin
230         @PreAuthorize("hasAuthority('PEER')")
231         @ApiOperation(value = "API to download the Machine Learning Artifact of the Machine Learning Solution", response = InputStreamResource.class, code = 200)
232         @RequestMapping(value = {APINames.PEER_ARTIFACT_download}, method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
233         @ResponseBody
234         public InputStreamResource downloadSolutionArtifact(@PathVariable("artifactId") String artifactId,
235                 HttpServletRequest request, HttpServletResponse response) {
236                 InputStreamResource inputStreamResource = null;
237                 try {
238                         inputStreamResource = federationService.getPeerSolutionArtifactFile(artifactId);
239                         //TODO : Need to Implement a logic to download a Artifact or Docker Image from Nexus
240                         response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
241                         response.setHeader("Pragma", "no-cache");
242                         response.setHeader("Expires", "0");
243                         response.setStatus(HttpServletResponse.SC_OK);
244                 } catch (Exception e) {
245                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
246                         logger.error(EELFLoggerDelegate.errorLogger, "Exception Occurred downloading a artifact for a Solution in Market Place Catalog", e);
247                 }
248                 return inputStreamResource;
249         }
250 }
251