Convert project from AJSC to Spring Boot
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / service / ModelLoaderService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed 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  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.service;
22
23 import java.io.FileInputStream;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Base64;
27 import java.util.Date;
28 import java.util.List;
29 import java.util.Properties;
30 import java.util.Timer;
31 import java.util.TimerTask;
32 import javax.annotation.PostConstruct;
33 import javax.ws.rs.core.Response;
34 import org.onap.aai.cl.api.Logger;
35 import org.onap.aai.cl.eelf.LoggerFactory;
36 import org.onap.aai.modelloader.config.ModelLoaderConfig;
37 import org.onap.aai.modelloader.entity.Artifact;
38 import org.onap.aai.modelloader.notification.ArtifactDeploymentManager;
39 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
40 import org.onap.aai.modelloader.notification.EventCallback;
41 import org.onap.aai.modelloader.restclient.BabelServiceClientFactory;
42 import org.onap.sdc.api.IDistributionClient;
43 import org.onap.sdc.api.notification.IArtifactInfo;
44 import org.onap.sdc.api.notification.INotificationData;
45 import org.onap.sdc.api.results.IDistributionClientResult;
46 import org.onap.sdc.impl.DistributionClientFactory;
47 import org.onap.sdc.utils.DistributionActionResultEnum;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.web.bind.annotation.PathVariable;
50 import org.springframework.web.bind.annotation.RequestBody;
51 import org.springframework.web.bind.annotation.RequestMapping;
52 import org.springframework.web.bind.annotation.RestController;
53
54 /**
55  * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
56  */
57 @RestController
58 @RequestMapping("/services/model-loader/v1/model-service")
59 public class ModelLoaderService implements ModelLoaderInterface {
60
61     static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
62
63     protected static final String FILESEP =
64             (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
65
66     @Value("${CONFIG_HOME}")
67     private String configDir;
68     private IDistributionClient client;
69     private ModelLoaderConfig config;
70
71     /**
72      * Responsible for loading configuration files and calling initialization.
73      */
74     @PostConstruct
75     protected void start() {
76         // Load model loader system configuration
77         logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
78         ModelLoaderConfig.setConfigHome(configDir);
79         Properties configProperties = new Properties();
80         try {
81             configProperties.load(new FileInputStream(configDir + FILESEP + "model-loader.properties"));
82             config = new ModelLoaderConfig(configProperties);
83             if (!config.getASDCConnectionDisabled()) {
84                 initSdcClient();
85             }
86         } catch (IOException e) {
87             String errorMsg = "Failed to load configuration: " + e.getMessage();
88             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
89         }
90     }
91
92     /**
93      * Responsible for stopping the connection to the distribution client before the resource is destroyed.
94      */
95     protected void preShutdownOperations() {
96         logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
97         if (client != null) {
98             client.stop();
99         }
100     }
101
102     /**
103      * Responsible for loading configuration files, initializing model distribution clients, and starting them.
104      */
105     protected void initSdcClient() {
106         // Initialize distribution client
107         logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
108         client = DistributionClientFactory.createDistributionClient();
109         EventCallback callback = new EventCallback(client, config);
110
111         IDistributionClientResult initResult = client.init(config, callback);
112
113         if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
114             String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
115             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
116
117             // Kick off a timer to retry the SDC connection
118             Timer timer = new Timer();
119             TimerTask task = new SdcConnectionJob(client, config, callback, timer);
120             timer.schedule(task, new Date(), 60000);
121         } else {
122             // Start distribution client
123             logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
124             IDistributionClientResult startResult = client.start();
125             if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
126                 String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
127                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
128
129                 // Kick off a timer to retry the SDC connection
130                 Timer timer = new Timer();
131                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
132                 timer.schedule(task, new Date(), 60000);
133             } else {
134                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
135             }
136         }
137         Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
138     }
139
140     /**
141      * (non-Javadoc)
142      *
143      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
144      */
145     @Override
146     public Response loadModel(@PathVariable String modelid) {
147         return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
148     }
149
150     /**
151      * (non-Javadoc)
152      *
153      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
154      */
155     @Override
156     public Response saveModel(@PathVariable String modelid, @PathVariable String modelname) {
157         return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
158     }
159
160     @Override
161     public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
162             @RequestBody String payload) throws IOException {
163         boolean success;
164
165         if (config.getIngestSimulatorEnabled()) {
166             try {
167                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
168
169                 List<Artifact> catalogArtifacts = new ArrayList<>();
170                 List<Artifact> modelArtifacts = new ArrayList<>();
171
172                 IArtifactInfo artifactInfo = new ArtifactInfoImpl();
173                 ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
174                 ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
175
176                 byte[] csarFile = Base64.getDecoder().decode(payload);
177
178                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating xml models from test artifact");
179
180                 new ArtifactDownloadManager(client, config, new BabelServiceClientFactory()).processToscaArtifacts(
181                         modelArtifacts, catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
182
183                 List<IArtifactInfo> artifacts = new ArrayList<>();
184                 artifacts.add(artifactInfo);
185                 INotificationData notificationData = new NotificationDataImpl();
186                 ((NotificationDataImpl) notificationData).setDistributionID("TestDistributionID");
187
188                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifact");
189
190                 success = new ArtifactDeploymentManager(client, config).deploy(notificationData, artifacts,
191                         modelArtifacts, catalogArtifacts);
192
193             } catch (Exception e) {
194                 return Response.serverError().entity(e).build();
195             }
196         } else {
197             logger.debug("Simulation interface disabled");
198             success = false;
199         }
200
201         Response response;
202         if (success) {
203             response = Response.ok().build();
204         } else {
205             response = Response.serverError().build();
206         }
207
208         return response;
209     }
210 }