Remove OpenECOMP from license file
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / service / ModelLoaderService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  *
22  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23  */
24 package org.openecomp.modelloader.service;
25
26 import org.openecomp.sdc.api.IDistributionClient;
27 import org.openecomp.sdc.api.results.IDistributionClientResult;
28 import org.openecomp.sdc.impl.DistributionClientFactory;
29 import org.openecomp.sdc.utils.DistributionActionResultEnum;
30
31 import org.openecomp.cl.api.Logger;
32 import org.openecomp.cl.eelf.LoggerFactory;
33 import org.openecomp.modelloader.config.ModelLoaderConfig;
34 import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
35 import org.openecomp.modelloader.notification.EventCallback;
36
37 import java.io.FileInputStream;
38 import java.io.IOException;
39 import java.util.Date;
40 import java.util.Properties;
41 import java.util.Timer;
42 import java.util.TimerTask;
43
44 import javax.servlet.http.HttpServletRequest;
45 import javax.ws.rs.core.Response;
46
47 /**
48  * Service class in charge of managing the negotiating model loading
49  * capabilities between AAI and an ASDC.
50  */
51 public class ModelLoaderService implements ModelLoaderInterface {
52         
53         protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"
54             : System.getProperty("file.separator");
55
56         protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;
57         protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;
58         protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";
59
60         private IDistributionClient client;
61         private ModelLoaderConfig config;
62         private Timer timer = null;
63
64         static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
65
66         /**
67          * Responsible for loading configuration files and calling initialization.
68          */
69         public ModelLoaderService() {
70                 start();
71         }
72
73         protected void start() {
74                 // Load model loader system configuration
75                 logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
76                 Properties configProperties = new Properties();
77                 try {
78                         configProperties.load(new FileInputStream(CONFIG_FILE));
79                 } catch (IOException e) {
80                         String errorMsg = "Failed to load configuration: " + e.getMessage();
81                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
82                         shutdown();
83                 }
84
85                 config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);
86                 init();
87                 
88                 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
89                         public void run() {
90                                 preShutdownOperations();
91                         }
92                 }));
93         }
94         
95         /**
96          * Responsible for stopping the connection to the distribution client before
97          * the resource is destroyed.
98          */
99         protected void preShutdownOperations() {
100                 logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
101                 if (client != null) {
102                         client.stop();
103                 }
104         }
105
106         /**
107          * Responsible for loading configuration files, initializing model
108          * distribution clients, and starting them.
109          */
110         protected void init() {
111                 // Initialize distribution client
112                 logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
113                 client = DistributionClientFactory.createDistributionClient();
114                 EventCallback callback = new EventCallback(client, config);
115                 
116                 IDistributionClientResult initResult = client.init(config, callback);
117
118                 if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
119                         String errorMsg = "Failed to initialize distribution client: "
120                                         + initResult.getDistributionMessageResult();
121                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
122                         
123                         // Kick off a timer to retry the SDC connection
124                         timer = new Timer();
125                         TimerTask task = new SdcConnectionJob(client, config, callback, timer);
126                         timer.schedule(task, new Date(), 60000);
127                 }
128                 else {
129                         // Start distribution client
130                         logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
131                         IDistributionClientResult startResult = client.start();
132                         if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
133                                 String errorMsg = "Failed to start distribution client: "
134                                                 + startResult.getDistributionMessageResult();
135                                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
136
137                                 // Kick off a timer to retry the SDC connection
138                                 timer = new Timer();
139                                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
140                                 timer.schedule(task, new Date(), 60000);
141                         }
142                         else {
143                                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
144                         }
145                 }
146         }
147
148         /**
149          * Shut down the process.
150          */
151         private void shutdown() {
152                 preShutdownOperations();
153
154                 // TODO: Find a better way to shut down the model loader.
155                 try {
156                         // Give logs time to write to file
157                         Thread.sleep(2000);
158                 } catch (InterruptedException e) {
159                         // Nothing we can do at this point
160                 }
161
162                 Runtime.getRuntime().halt(1);
163         }
164
165         /** (non-Javadoc)
166          * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
167          */
168         @Override
169         public Response loadModel(String modelid) {
170                 Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
171
172                 return response;
173         }
174
175         /** (non-Javadoc)
176          * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
177          */
178         @Override
179         public Response saveModel(String modelid, String modelname) {
180                 Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
181                                 .build();
182
183                 return response;
184         }
185
186         @Override
187         public Response ingestModel(String modelid, HttpServletRequest req, String payload)
188                         throws IOException {
189                 Response response;
190
191                 if (config.getIngestSimulatorEnabled()) {
192                         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
193
194                         ModelArtifactHandler handler = new ModelArtifactHandler(config);
195                         handler.loadModelTest(payload.getBytes());
196
197                         response = Response.ok().build();
198                 } else {
199                         logger.debug("Simulation interface disabled");
200                         response = Response.serverError().build();
201                 }
202
203                 return response;
204         }
205 }