Fix sonar issues
[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.IOException;
24 import java.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.Base64;
29 import java.util.Date;
30 import java.util.List;
31 import java.util.Properties;
32 import java.util.Timer;
33 import java.util.TimerTask;
34
35 import javax.annotation.PostConstruct;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.modelloader.config.ModelLoaderConfig;
42 import org.onap.aai.modelloader.entity.Artifact;
43 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
44 import org.onap.aai.modelloader.notification.EventCallback;
45 import org.onap.aai.modelloader.notification.NotificationDataImpl;
46 import org.onap.aai.modelloader.notification.NotificationPublisher;
47 import org.onap.sdc.api.IDistributionClient;
48 import org.onap.sdc.api.notification.IArtifactInfo;
49 import org.onap.sdc.api.results.IDistributionClientResult;
50 import org.onap.sdc.impl.DistributionClientFactory;
51 import org.onap.sdc.utils.DistributionActionResultEnum;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.web.bind.annotation.PathVariable;
55 import org.springframework.web.bind.annotation.RequestBody;
56 import org.springframework.web.bind.annotation.RequestMapping;
57 import org.springframework.web.bind.annotation.RestController;
58
59 /**
60  * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
61  */
62 @RestController
63 @RequestMapping("/services/model-loader/v1/model-service")
64 public class ModelLoaderService implements ModelLoaderInterface {
65
66     private static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
67
68     @Value("${CONFIG_HOME}")
69     private String configDir;
70     private IDistributionClient client;
71     private ModelLoaderConfig config;
72     @Autowired
73     private BabelServiceClientFactory babelClientFactory;
74
75     /**
76      * Responsible for loading configuration files and calling initialization.
77      */
78     @PostConstruct
79     protected void start() {
80         // Load model loader system configuration
81         logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
82         ModelLoaderConfig.setConfigHome(configDir);
83         Properties configProperties = new Properties();
84         try (InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"))) {
85             configProperties.load(configInputStream);
86             config = new ModelLoaderConfig(configProperties);
87             
88             // Set the truststore for SDC Client to connect to Dmaap central bus if applicable (as in case of TI)
89             if (Boolean.TRUE.equals(config.isUseHttpsWithDmaap())) {
90                 String trustStorePath = config.getKeyStorePath();
91                 String trustStorePassword = config.getKeyStorePassword();
92                 if (trustStorePath != null && Paths.get(trustStorePath).toFile().isFile() && trustStorePassword != null
93                         && !trustStorePassword.isEmpty()) {
94                     System.setProperty("javax.net.ssl.trustStore", trustStorePath);
95                     System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
96                 } else {
97                     throw new IllegalArgumentException("Model Loader property ml.distribution.KEYSTORE_FILE "
98                                 + "or ml.distribution.KEYSTORE_PASSWORD not set or invalid");
99                 }
100             }
101             
102             if (!config.getASDCConnectionDisabled()) {
103                 initSdcClient();
104             }
105         } catch (IOException e) {
106             String errorMsg = "Failed to load configuration: " + e.getMessage();
107             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
108         }
109     }
110
111     /**
112      * Responsible for stopping the connection to the distribution client before the resource is destroyed.
113      */
114     public void preShutdownOperations() {
115         logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
116         if (client != null) {
117             client.stop();
118         }
119     }
120
121     /**
122      * Responsible for loading configuration files, initializing model distribution clients, and starting them.
123      */
124     protected void initSdcClient() {
125         // Initialize distribution client
126         logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
127         client = DistributionClientFactory.createDistributionClient();
128         EventCallback callback = new EventCallback(client, config, babelClientFactory);
129
130         IDistributionClientResult initResult = client.init(config, callback);
131
132         if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
133             // Start distribution client
134             logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
135             IDistributionClientResult startResult = client.start();
136             if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
137                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
138             } else {
139                 String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
140                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
141
142                 // Kick off a timer to retry the SDC connection
143                 Timer timer = new Timer();
144                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
145                 timer.schedule(task, new Date(), 60000);
146             }
147         } else {
148             String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
149             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
150
151             // Kick off a timer to retry the SDC connection
152             Timer timer = new Timer();
153             TimerTask task = new SdcConnectionJob(client, config, callback, timer);
154             timer.schedule(task, new Date(), 60000);
155         }
156
157         Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
158     }
159
160     /**
161      * (non-Javadoc)
162      *
163      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
164      */
165     @Override
166     public Response loadModel(@PathVariable String modelid) {
167         return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
168     }
169
170     /**
171      * (non-Javadoc)
172      *
173      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
174      */
175     @Override
176     public Response saveModel(@PathVariable String modelid, @PathVariable String modelname) {
177         return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
178     }
179
180     @Override
181     public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
182             @RequestBody String payload) throws IOException {
183         Response response;
184
185         if (config.getIngestSimulatorEnabled()) {
186             response = processTestArtifact(modelName, modelVersion, payload);
187         } else {
188             logger.debug("Simulation interface disabled");
189             response = Response.serverError().build();
190         }
191
192         return response;
193     }
194
195     private Response processTestArtifact(String modelName, String modelVersion, String payload) {
196         IArtifactInfo artifactInfo = new ArtifactInfoImpl();
197         ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
198         ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
199
200         Response response;
201         try {
202             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact " + modelName + " " + modelVersion);
203
204             byte[] csarFile = Base64.getDecoder().decode(payload);
205
206             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating XML models from test artifact");
207
208             List<Artifact> modelArtifacts = new ArrayList<>();
209             List<Artifact> catalogArtifacts = new ArrayList<>();
210
211             new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
212                     catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
213
214             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
215                     + modelArtifacts.size() + " model(s) and " + catalogArtifacts.size() + " catalog(s)");
216
217             NotificationDataImpl notificationData = new NotificationDataImpl();
218             notificationData.setDistributionID("TestDistributionID");
219             boolean success =
220                     new ArtifactDeploymentManager(config).deploy(notificationData, modelArtifacts, catalogArtifacts);
221             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Deployment success was " + success);
222             response = success ? Response.ok().build() : Response.serverError().build();
223         } catch (Exception e) {
224             String responseMessage = e.getMessage();
225             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Exception handled: " + responseMessage);
226             if (config.getASDCConnectionDisabled()) {
227                 // Make sure the NotificationPublisher logger is invoked as per the standard processing flow.
228                 new NotificationPublisher().publishDeployFailure(client, new NotificationDataImpl(), artifactInfo);
229             } else {
230                 responseMessage += "\nSDC publishing is enabled but has been bypassed";
231             }
232             response = Response.serverError().entity(responseMessage).type(MediaType.APPLICATION_XML).build();
233         }
234         return response;
235     }
236 }