Initial OpenECOMP A&AI Model Loader commit
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / service / ModelLoaderService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * MODEL LOADER SERVICE
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License 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.openecomp.modelloader.service;
22
23 import org.openecomp.sdc.api.IDistributionClient;
24 import org.openecomp.sdc.api.results.IDistributionClientResult;
25 import org.openecomp.sdc.impl.DistributionClientFactory;
26 import org.openecomp.sdc.utils.DistributionActionResultEnum;
27
28 import org.openecomp.cl.api.Logger;
29 import org.openecomp.cl.eelf.LoggerFactory;
30 import org.openecomp.modelloader.config.ModelLoaderConfig;
31 import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
32 import org.openecomp.modelloader.notification.EventCallback;
33
34 import java.io.IOException;
35 import java.util.Properties;
36
37 import javax.annotation.PostConstruct;
38 import javax.annotation.PreDestroy;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.ws.rs.core.Response;
41
42 /**
43  * Service class in charge of managing the negotiating model loading
44  * capabilities between AAI and an ASDC.
45  */
46 public class ModelLoaderService implements ModelLoaderInterface {
47
48   protected static String CONFIG_FILE = "model-loader.properties";
49
50   private IDistributionClient client;
51   private ModelLoaderConfig config;
52
53   static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
54
55   /**
56    * Responsible for loading configuration files and calling initialization.
57    */
58   @PostConstruct
59   protected void start() {
60     // Load model loader system configuration
61     logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
62     Properties configProperties = new Properties();
63     try {
64       configProperties.load(this.getClass().getClassLoader().getResourceAsStream(CONFIG_FILE));
65     } catch (IOException e) {
66       String errorMsg = "Failed to load configuration: " + e.getMessage();
67       logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
68       shutdown();
69     }
70     
71     config = new ModelLoaderConfig(configProperties);
72     init();
73   }
74
75   /**
76    * Responsible for stopping the connection to the distribution client before
77    * the resource is destroyed.
78    */
79   @PreDestroy
80   protected void preShutdownOperations() {
81     logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
82     if (client != null) {
83       client.stop();
84     }
85   }
86
87   /**
88    * Responsible for loading configuration files, initializing model
89    * distribution clients, and starting them.
90    */
91   protected void init() {
92     // Initialize distribution client
93     logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
94     client = DistributionClientFactory.createDistributionClient();
95     IDistributionClientResult initResult = client.init(config, new EventCallback(client, config));
96     if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
97       String errorMsg = "Failed to initialize distribution client: "
98           + initResult.getDistributionMessageResult();
99       logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
100       shutdown();
101     }
102
103     // Start distribution client
104     logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
105     IDistributionClientResult startResult = client.start();
106     if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
107       String errorMsg = "Failed to start distribution client: "
108           + startResult.getDistributionMessageResult();
109       logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
110       shutdown();
111     }
112
113     logger.debug(ModelLoaderMsgs.INITIALIZING,
114         "Succcessfully loaded service: " + this.getClass().getSimpleName());
115   }
116
117   /**
118    * Shut down the process.
119    */
120   private void shutdown() {
121     preShutdownOperations();
122
123     // TODO: Find a better way to shut down the model loader.
124     try {
125       // Give logs time to write to file
126       Thread.sleep(2000);
127     } catch (InterruptedException e) {
128       // Nothing we can do at this point
129     }
130
131     Runtime.getRuntime().halt(1);
132   }
133
134   /** (non-Javadoc)
135    * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
136    */
137   @Override
138   public Response loadModel(String modelid) {
139     Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
140
141     return response;
142   }
143
144   /** (non-Javadoc)
145    * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
146    */
147   @Override
148   public Response saveModel(String modelid, String modelname) {
149     Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
150         .build();
151
152     return response;
153   }
154
155   @Override
156   public Response ingestModel(String modelid, HttpServletRequest req, String payload)
157       throws IOException {
158     Response response;
159
160     if (config.getIngestSimulatorEnabled()) {
161       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
162
163       ModelArtifactHandler handler = new ModelArtifactHandler(config);
164       handler.loadModelTest(payload.getBytes());
165
166       response = Response.ok().build();
167     } else {
168       logger.debug("Simulation interface disabled");
169       response = Response.serverError().build();
170     }
171
172     return response;
173   }
174 }