Initial OpenECOMP MSO commit
[so.git] / mso-catalog-db / src / main / java / org / openecomp / mso / db / catalog / CatalogDatabase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
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.mso.db.catalog;
22
23 import java.io.Closeable;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import org.openecomp.mso.db.catalog.beans.*;
30 import org.hibernate.HibernateException;
31 import org.hibernate.Query;
32 import org.hibernate.Session;
33 import org.hibernate.SessionFactory;
34 import org.hibernate.cfg.Configuration;
35 import org.hibernate.service.ServiceRegistry;
36 import org.hibernate.service.ServiceRegistryBuilder;
37
38 import org.openecomp.mso.db.catalog.utils.MavenLikeVersioningComparator;
39 import org.openecomp.mso.logger.MessageEnum;
40 import org.openecomp.mso.logger.MsoLogger;
41
42 /**
43  * This class encapsulates all of the objects that can be queried from a Catalog database.
44  * Clients must use these methods to retrieve catalog objects. The session is not
45  * available for clients to do their own direct queries to the database.
46  *
47  *
48  */
49 public class CatalogDatabase implements Closeable {
50
51     private static final String NETWORK_TYPE = "networkType";
52     private static final String ACTION = "action";
53     private static final String VNF_TYPE = "vnfType";
54     private static final String SERVICE_TYPE = "serviceType";
55     private static final String VNF_COMPONENT_TYPE = "vnfComponentType";
56     private static final String MODEL_NAME = "modelName";
57     private static final String TYPE = "type";
58     private static final String VF_MODULE_ID = "vfModuleId";
59     private static boolean initialized = false;
60     private static SessionFactory sessionFactory;
61     private static ServiceRegistry serviceRegistry;
62
63     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL);
64
65     private Session session = null;
66
67     public CatalogDatabase () {
68     }
69
70
71     private Session getSession () {
72         if (!initialized) {
73             LOGGER.debug ("Initializing Catalog Database in Hibernate");
74             Configuration configuration = null;
75             try {
76                         if ("MYSQL".equals (System.getProperty ("mso.db"))
77                             || "MARIADB".equals (System.getProperty ("mso.db"))) {
78                         configuration = new Configuration ().configure ("hibernate-catalog-mysql.cfg.xml");
79
80                         serviceRegistry = new ServiceRegistryBuilder ().applySettings (configuration.getProperties ()).buildServiceRegistry ();
81
82                         sessionFactory = configuration.buildSessionFactory (serviceRegistry);
83                     } else {
84                         LOGGER.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "DB Connection not specified to the JVM,choose either:-Dmso.db=MARIADB, -Dmso.db=MYSQL or -Dmso.container=AJSC", "", "", MsoLogger.ErrorCode.DataError, "DB Connection not specified to the JVM,choose either:-Dmso.db=MARIADB, -Dmso.db=MYSQL or -Dmso.container=AJSC");
85                     }
86             } catch (Exception e) {
87                 LOGGER.error (MessageEnum.GENERAL_EXCEPTION_ARG,
88                               "Catalog DB initialization issue: " + e.getMessage (), "", "", MsoLogger.ErrorCode.DataError, "Catalog DB initialization issue: " + e.getMessage (), e);
89                 throw e;
90             }
91             initialized = true;
92
93             LOGGER.debug ("Catalog Database initialization complete");
94         }
95
96         if (session == null) {
97             try {
98                 session = sessionFactory.openSession ();
99                 session.beginTransaction ();
100             } catch (HibernateException he) {
101                 LOGGER.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Error creating Hibernate Session: " + he, "", "", MsoLogger.ErrorCode.DataError, "Error creating Hibernate Session: " + he);
102                 throw he;
103             }
104         }
105
106         return session;
107     }
108
109     /**
110      * Close an open Catalog Database session.
111      * This method should always be called when a client is finished using a
112      * CatalogDatabase instance.
113      */
114     @Override
115     public void close () {
116         if (session != null) {
117             session.close ();
118             session = null;
119         }
120     }
121
122     /**
123      * Commits the current transaction on this session and starts a fresh one.
124      */
125     public void commit () {
126         getSession ().getTransaction ().commit ();
127         getSession ().beginTransaction ();
128     }
129
130     /**
131      * Rolls back current transaction and starts a fresh one.
132      */
133     public void rollback () {
134         getSession ().getTransaction ().rollback ();
135         getSession ().beginTransaction ();
136     }
137
138     /**
139      * Return all Heat Templates in the Catalog DB
140      *
141      * @return A list of HeatTemplate objects
142      */
143     @SuppressWarnings("unchecked")
144     public List <HeatTemplate> getAllHeatTemplates () {
145         long startTime = System.currentTimeMillis ();
146         LOGGER.debug ("Catalog database - get all Heat templates");
147         String hql = "FROM HeatTemplate";
148         Query query = getSession ().createQuery (hql);
149
150         List <HeatTemplate> result = query.list ();
151         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllHeatTemplates", null);
152         return result;
153     }
154
155     /**
156      * Fetch a specific Heat Template by ID.
157      *
158      * @param templateId
159      * @return HeatTemplate object or null if none found
160      */
161     public HeatTemplate getHeatTemplate (int templateId) {
162         long startTime = System.currentTimeMillis ();
163         LOGGER.debug ("Catalog database - get Heat template with id " + templateId);
164
165         HeatTemplate template = (HeatTemplate) getSession ().get (HeatTemplate.class, templateId);
166         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
167         return template;
168     }
169
170     /**
171      * Return the newest version of a specific Heat Template (queried by Name).
172      *
173      * @param templateName
174      * @return HeatTemplate object or null if none found
175      */
176     public HeatTemplate getHeatTemplate (String templateName) {
177
178         long startTime = System.currentTimeMillis ();
179         LOGGER.debug ("Catalog database - get Heat template with name " + templateName);
180
181         String hql = "FROM HeatTemplate WHERE templateName = :template_name";
182         Query query = getSession ().createQuery (hql);
183         query.setParameter ("template_name", templateName);
184
185         @SuppressWarnings("unchecked")
186         List <HeatTemplate> resultList = query.list ();
187
188         // See if something came back. Name is unique, so
189         if (resultList.isEmpty ()) {
190             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No template found", "CatalogDB", "getHeatTemplate", null);
191             return null;
192         }
193         Collections.sort (resultList, new MavenLikeVersioningComparator ());
194         Collections.reverse (resultList);
195
196         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
197         return resultList.get (0);
198     }
199
200     /**
201      * Return a specific version of a specific Heat Template (queried by Name).
202      *
203      * @param templateName
204      * @param version
205      * @return HeatTemplate object or null if none found
206      */
207     public HeatTemplate getHeatTemplate (String templateName, String version) {
208
209         long startTime = System.currentTimeMillis ();
210         LOGGER.debug ("Catalog database - get Heat template with name " + templateName
211                                       + " and version "
212                                       + version);
213
214         String hql = "FROM HeatTemplate WHERE templateName = :template_name AND version = :version";
215         Query query = getSession ().createQuery (hql);
216         query.setParameter ("template_name", templateName);
217         query.setParameter ("version", version);
218
219         @SuppressWarnings("unchecked")
220         List <HeatTemplate> resultList = query.list ();
221
222         // See if something came back.
223         if (resultList.isEmpty ()) {
224             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No template found.", "CatalogDB", "getHeatTemplate", null);
225             return null;
226         }
227         // Name + Version is unique, so should only be one element
228         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
229         return resultList.get (0);
230     }
231
232     /**
233      * Fetch a Service definition
234      */
235     public Service getService (String serviceName) {
236
237         long startTime = System.currentTimeMillis ();
238         LOGGER.debug ("Catalog database - get service with name " + serviceName);
239
240         String hql = "FROM Service WHERE serviceName = :service_name";
241         Query query = getSession ().createQuery (hql);
242         query.setParameter ("service_name", serviceName);
243
244         Service service = null;
245         try {
246                 service = (Service) query.uniqueResult ();
247         } catch (org.hibernate.NonUniqueResultException nure) {
248                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: serviceName='" + serviceName + "'");
249                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for serviceName=" + serviceName, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for serviceName=" + serviceName);
250                 return null;
251         } catch (org.hibernate.HibernateException he) {
252                 LOGGER.debug("Hibernate Exception - while searching for: serviceName='" + serviceName + "'");
253                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for serviceName=" + serviceName, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for serviceName=" + serviceName);
254                 return null;
255         } catch (Exception e) {
256                 LOGGER.debug("Generic Exception - while searching for: serviceName='" + serviceName);
257                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for serviceName=" + serviceName, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for serviceName=" + serviceName);
258                 return null;
259         }
260         if (service == null) {
261                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
262         } else {
263                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
264         }
265
266         return service;
267     }
268     
269     /**
270      * Fetch a Service definition
271      */
272     public Service getServiceByUUID (String serviceNameVersionId) {
273
274         long startTime = System.currentTimeMillis ();
275         LOGGER.debug ("Catalog database - get service with UUID " + serviceNameVersionId);
276
277         String hql = "FROM Service WHERE serviceNameVersionId = :service_id";
278         Query query = getSession ().createQuery (hql);
279         query.setParameter ("service_id", serviceNameVersionId);
280
281         Service service = null;
282         try {
283                 service = (Service) query.uniqueResult ();
284         } catch (org.hibernate.NonUniqueResultException nure) {
285                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: serviceNameVersionId='" + serviceNameVersionId + "'");
286                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for serviceNameVersionId=" + serviceNameVersionId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for serviceNameVersionId=" + serviceNameVersionId);
287                 return null;
288         } catch (org.hibernate.HibernateException he) {
289                 LOGGER.debug("Hibernate Exception - while searching for: serviceName='" + serviceNameVersionId + "'");
290                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for serviceNameVersionId=" + serviceNameVersionId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for serviceNameVersionId=" + serviceNameVersionId);
291                 return null;
292         } catch (Exception e) {
293                 LOGGER.debug("Generic Exception - while searching for: serviceName='" + serviceNameVersionId);
294                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for serviceNameVersionId=" + serviceNameVersionId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for serviceNameVersionId=" + serviceNameVersionId);
295                 return null;
296         }
297         if (service == null) {
298                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
299         } else {
300                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
301         }
302
303         return service;
304     }
305     
306     /**
307      * Fetch the Common Service API definition using Http Method + serviceNameVersionId
308      */
309     public Service getService(HashMap<String, String> map, String httpMethod) {
310      
311         String serviceNameVersionId = map.get("serviceNameVersionId");
312         Query query;
313         String serviceId = "not_set";
314         String serviceVersion = "not_set";
315         
316         if(serviceNameVersionId != null && serviceNameVersionId.length() > 0){
317                 LOGGER.debug ("Catalog database - get serviceNameVersionId with id " + serviceNameVersionId);
318
319                 String hql = "FROM Service WHERE service_name_version_id = :service_name_version_id and http_method = :http_method";
320                 query = getSession ().createQuery (hql);
321             query.setParameter ("service_name_version_id", serviceNameVersionId);
322          } else {
323                 serviceId = map.get("serviceId");
324                 serviceVersion = map.get("serviceVersion");
325             LOGGER.debug ("Catalog database - get serviceId with id " + serviceId + " and serviceVersion with " + serviceVersion);
326
327             String hql = "FROM Service WHERE service_id = :service_id and service_version = :service_version and http_method = :http_method";
328             query = getSession ().createQuery (hql);
329             query.setParameter ("service_id", serviceId);
330             query.setParameter ("service_version", serviceVersion);
331          }
332         
333         query.setParameter ("http_method", httpMethod);
334
335         long startTime = System.currentTimeMillis ();
336         Service service = null;
337         try {
338                 service = (Service) query.uniqueResult ();
339         } catch (org.hibernate.NonUniqueResultException nure) {
340                 LOGGER.debug("Non Unique Result Exception - data integrity error: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "'");
341                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for service_id=" + serviceId + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for service_id=" + serviceId);
342                 service = null;
343         } catch (org.hibernate.HibernateException he) {
344                 LOGGER.debug("Hibernate Exception - while searching for: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "'");
345                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for service_id=" + serviceId + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for service_id=" + serviceId);
346                 service = null;
347         } catch (Exception e) {
348                 LOGGER.debug("Generic Exception - while searching for: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "'");
349                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for service_id=" + serviceId + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for service_id=" + serviceId);
350                 service = null;
351         }
352         if (service == null) {
353                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
354         } else {
355                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
356         }
357         return service;
358     }
359     
360     /**
361      * Return the newest version of a Service (queried by Name).
362      *
363      * @param serviceName
364      * @return Service object or null if none found
365      */
366     public Service getServiceByName (String serviceName) {
367
368         long startTime = System.currentTimeMillis ();
369         LOGGER.debug ("Catalog database - get service with name " + serviceName);
370
371         String hql = "FROM Service WHERE serviceName = :service_name";
372         Query query = getSession ().createQuery (hql);
373         query.setParameter ("service_name", serviceName);
374
375         @SuppressWarnings("unchecked")
376         List <Service> resultList = query.list ();
377
378         // See if something came back. 
379         if (resultList.isEmpty ()) {
380             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service not found", "CatalogDB", "getServiceByName", null);
381             return null;
382         }
383         Collections.sort (resultList, new MavenLikeVersioningComparator ());
384         Collections.reverse (resultList);
385
386         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceByName", null);
387         return resultList.get (0);
388     }
389
390     /**
391      * Return a newest version of Service recipe that matches a given SERVICE_ID and ACTION
392      *
393      * @param serviceId
394      * @param action     * 
395      * @return ServiceRecipe object or null if none found
396      */
397     public ServiceRecipe getServiceRecipe (int serviceId, String action) {
398        
399         StringBuilder hql = new StringBuilder ("FROM ServiceRecipe WHERE serviceId = :serviceId AND action = :action ");
400     
401    
402         long startTime = System.currentTimeMillis ();
403         LOGGER.debug ("Catalog database - get Service recipe with serviceId " + Integer.toString(serviceId)
404                                       + " and action "
405                                       + action
406                                       );
407
408         Query query = getSession ().createQuery (hql.toString ());
409         query.setParameter ("serviceId", serviceId);
410         query.setParameter (ACTION, action);
411         
412         @SuppressWarnings("unchecked")
413         List <ServiceRecipe> resultList = query.list ();
414
415         if (resultList.isEmpty ()) {
416             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service recipe not found", "CatalogDB", "getServiceRecipe", null);
417             return null;
418         }
419         
420         Collections.sort (resultList, new MavenLikeVersioningComparator ());
421         Collections.reverse (resultList);
422
423         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipe", null);
424         return resultList.get (0);
425     }
426
427     
428     /**
429      * Return the VNF component data - queried by the VNFs ID and the component type.
430      *
431      * @param vnfId
432      * @param type
433      * @return VnfComponent object or null if none found
434      */
435     public VnfComponent getVnfComponent (int vnfId, String type) {
436         
437         long startTime = System.currentTimeMillis();
438         LOGGER.debug ("Catalog database - get VnfComponent where vnfId="+ vnfId+ " AND componentType="+ type);
439         
440         String hql = "FROM VnfComponent WHERE vnfId = :vnf_id AND componentType = :type";
441         Query query = getSession ().createQuery (hql);
442         query.setParameter ("vnf_id", vnfId);
443         query.setParameter ("type", type);
444
445         VnfComponent result = null;
446         try {
447                 result = (VnfComponent) query.uniqueResult(); 
448         } catch (org.hibernate.NonUniqueResultException nure) {
449                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnf_id='" + vnfId + "', componentType='" + type + "'");
450                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnf_id=" + vnfId + " and componentType=" + type, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnf_id=" + vnfId);
451                 result = null;
452         } catch (org.hibernate.HibernateException he) {
453                 LOGGER.debug("Hibernate Exception - while searching for: vnf_id='" + vnfId + "', componentType='" + type + "'");
454                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for vnf_id=" + vnfId + " and componentType=" + type, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnf_id=" + vnfId);
455                 result = null;
456         } catch (Exception e) {
457                 LOGGER.debug("Generic Exception - while searching for: vnf_id='" + vnfId + "', componentType='" + type + "'");
458                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for vnf_id=" + vnfId + " and componentType=" + type, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for vnf_id=" + vnfId);
459                 result = null;
460         }
461
462         //LOGGER.debug("Found VNF Component: " + result.toString());
463         if (result != null) {
464             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponent", null);
465         } else {
466             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No VNFComponent found", "CatalogDB", "getVnfComponent", null);
467         }
468         return result;
469     }
470
471     /**
472      * Return the newest version of a specific VNF resource (queried by Name).
473      *
474      * @param vnfType
475      * @return VnfResource object or null if none found
476      */
477     public VnfResource getVnfResource (String vnfType) {
478
479         long startTime = System.currentTimeMillis ();
480         LOGGER.debug ("Catalog database - get vnf resource with name " + vnfType);
481
482         String hql = "FROM VnfResource WHERE vnfType = :vnf_name";
483         Query query = getSession ().createQuery (hql);
484         query.setParameter ("vnf_name", vnfType);
485
486         @SuppressWarnings("unchecked")
487         List <VnfResource> resultList = query.list ();
488
489         // See if something came back. Name is unique, so
490         if (resultList.isEmpty ()) {
491             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF not found", "CatalogDB", "getVnfResource", null);
492             return null;
493         }
494         Collections.sort (resultList, new MavenLikeVersioningComparator ());
495         Collections.reverse (resultList);
496
497         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResource", null);
498         return resultList.get (0);
499     }
500
501     /**
502      * Return the newest version of a specific VNF resource (queried by Name).
503      *
504      * @param vnfType
505      * @param version
506      * @return VnfResource object or null if none found
507      */
508     public VnfResource getVnfResource (String vnfType, String serviceVersion) {
509
510         long startTime = System.currentTimeMillis ();
511         LOGGER.debug ("Catalog database - get VNF resource with name " + vnfType);
512
513         String hql = "FROM VnfResource WHERE vnfType = :vnfName and version = :serviceVersion";
514         Query query = getSession ().createQuery (hql);
515         query.setParameter ("vnfName", vnfType);
516         query.setParameter ("serviceVersion", serviceVersion);
517
518         VnfResource resource = null;
519         try {
520                 resource = (VnfResource) query.uniqueResult ();
521         } catch (org.hibernate.NonUniqueResultException nure) {
522                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnfType='" + vnfType + "', serviceVersion='" + serviceVersion + "'");
523                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnfType=" + vnfType);
524                 resource = null;
525         } catch (org.hibernate.HibernateException he) {
526                 LOGGER.debug("Hibernate Exception - while searching for: vnfType='" + vnfType + "', asdc_service_model_version='" + serviceVersion + "'");
527                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfType=" + vnfType);
528                 resource = null;
529         } catch (Exception e) {
530                 LOGGER.debug("Generic Exception - while searching for: vnfType='" + vnfType + "', serviceVersion='" + serviceVersion + "'");
531                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for vnfType=" + vnfType);
532                 resource = null;
533         }
534         if (resource == null) {
535                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResource", null);
536         } else {
537                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResource", null);
538         }
539         return resource;
540     }
541
542     /**
543      * Return the newest version of a specific VNF resource (queried by ID).
544      *
545      * @param id The vnf id
546      * @return VnfResource object or null if none found
547      */
548     public VnfResource getVnfResourceById (int id) {
549
550         long startTime = System.currentTimeMillis ();
551         LOGGER.debug ("Catalog database - get VNF resource with id " + id);
552
553         String hql = "FROM VnfResource WHERE id = :id";
554         Query query = getSession ().createQuery (hql);
555         query.setParameter ("id", id);
556
557         @SuppressWarnings("unchecked")
558         List <VnfResource> resultList = query.list ();
559
560         // See if something came back. Name is unique, so
561         if (resultList.isEmpty ()) {
562             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VnfResource not found", "CatalogDB", "getVnfResourceById", null);
563             return null;
564         }
565         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceById", null);
566         return resultList.get (0);
567     }
568     
569     /**
570      * Return the newest version of a vfModule - 1607 
571      *
572      */
573     public VfModule getVfModuleModelName (String modelName) {
574
575         long startTime = System.currentTimeMillis ();
576         LOGGER.debug ("Catalog database - get vfModuleModelName with name " + modelName);
577
578         String hql = "FROM VfModule WHERE model_name = :model_name";
579         Query query = getSession ().createQuery (hql);
580         query.setParameter ("model_name", modelName);
581
582         @SuppressWarnings("unchecked")
583         List <VfModule> resultList = query.list ();
584
585         // See if something came back. Name is unique, so
586         if (resultList.isEmpty ()) {
587             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleModelName", null);
588             return null;
589         }
590         Collections.sort (resultList, new MavenLikeVersioningComparator ());
591         Collections.reverse (resultList);
592
593         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null);
594         return resultList.get (0);
595     }
596     
597     public VfModule getVfModuleModelName (String modelName, String model_version) {
598
599         long startTime = System.currentTimeMillis ();
600         LOGGER.debug ("Catalog database - get vfModuleModelName with type='" + modelName + "' and asdc_service_model_version='" + model_version + "'");
601
602         String hql = "FROM VfModule WHERE model_name = :model_name and version = :model_version";
603         Query query = getSession ().createQuery (hql);
604         query.setParameter ("model_name", modelName);
605         query.setParameter ("model_version", model_version);
606         
607         VfModule module = null;
608         try {
609                 module = (VfModule) query.uniqueResult ();
610         } catch (org.hibernate.NonUniqueResultException nure) {
611                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: type='" + modelName + "', asdc_service_model_version='" + model_version + "'");
612                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for type=" + modelName);
613                 module = null;
614         } catch (org.hibernate.HibernateException he) {
615                 LOGGER.debug("Hibernate Exception - while searching for: type='" + modelName + "', asdc_service_model_version='" + model_version + "'");
616                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for type=" + modelName);
617                 module = null;
618         } catch (Exception e) {
619                 LOGGER.debug("Generic Exception - while searching for: type='" + modelName + "', asdc_service_model_version='" + model_version + "'");
620                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for type=" + modelName);
621                 module = null;
622         }
623         if (module == null) {
624                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleModelName", null);
625         } else {
626                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null);
627         }
628         return module;
629     }
630    
631
632     /**
633      * Return the newest version of a specific Network resource (queried by Type).
634      *
635      * @param networkType
636      * @return NetworkResource object or null if none found
637      */
638     public NetworkResource getNetworkResource (String networkType) {
639
640         long startTime = System.currentTimeMillis ();
641         LOGGER.debug ("Catalog database - get network resource with type " + networkType);
642
643         String hql = "FROM NetworkResource WHERE networkType = :network_type";
644         Query query = getSession ().createQuery (hql);
645         query.setParameter ("network_type", networkType);
646
647         @SuppressWarnings("unchecked")
648         List <NetworkResource> resultList = query.list ();
649
650         // See if something came back. Name is unique, so
651         if (resultList.isEmpty ()) {
652             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Network Resource not found", "CatalogDB", "getNetworkResource", null);
653             return null;
654         }
655
656         Collections.sort (resultList, new MavenLikeVersioningComparator ());
657         Collections.reverse (resultList);
658         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResource", null);
659         return resultList.get (0);
660     }
661
662     /**
663      * Return a VNF recipe that matches a given VNF_TYPE, ACTION, and, if specified, SERVICE_TYPE
664      *
665      * @param vnfType
666      * @param action
667      * @param serviceType The service Name, if null or empty is provided, it won't be taken into account
668      * @return VnfRecipe object or null if none found
669      */
670     public VnfRecipe getVnfRecipe (String vnfType, String action, String serviceType) {
671         boolean withServiceType = false;
672
673         StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action ");
674
675         // If query c
676         if (serviceType == null || serviceType.isEmpty ()) {
677             hql.append ("AND serviceType is NULL ");
678         } else {
679             hql.append ("AND serviceType = :serviceType ");
680             withServiceType = true;
681         }
682    
683         long startTime = System.currentTimeMillis ();
684         LOGGER.debug ("Catalog database - get VNF recipe with name " + vnfType
685                                       + " and action "
686                                       + action
687                                       + " and service type "
688                                       + serviceType);
689
690         Query query = getSession ().createQuery (hql.toString ());
691         query.setParameter (VNF_TYPE, vnfType);
692         query.setParameter (ACTION, action);
693         if (withServiceType) {
694             query.setParameter (SERVICE_TYPE, serviceType);
695         }
696
697         @SuppressWarnings("unchecked")
698         List <VnfRecipe> resultList = query.list ();
699
700         if (resultList.isEmpty ()) {
701             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null);
702             return null;
703         }
704         
705         Collections.sort (resultList, new MavenLikeVersioningComparator ());
706         Collections.reverse (resultList);
707
708         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null);
709         return resultList.get (0);
710     }
711
712     /**
713      * Return a VNF recipe that matches a given VNF_TYPE and ACTION
714      *
715      * @param vnfType
716      * @param action
717      * @return VnfRecipe object or null if none found
718      */
719     public VnfRecipe getVnfRecipe (String vnfType, String action) {
720         StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action ");
721
722         long startTime = System.currentTimeMillis ();
723         LOGGER.debug ("Catalog database - get VNF recipe with name " + vnfType
724                                       + " and action "
725                                       + action);
726
727         Query query = getSession ().createQuery (hql.toString ());
728         query.setParameter (VNF_TYPE, vnfType);
729         query.setParameter (ACTION, action);
730
731         @SuppressWarnings("unchecked")
732         List <VnfRecipe> resultList = query.list ();
733
734         if (resultList.isEmpty ()) {
735             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null);
736             return null;
737         }
738
739         Collections.sort (resultList, new MavenLikeVersioningComparator ());
740         Collections.reverse (resultList);
741
742         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null);
743         return resultList.get (0);
744     }
745     
746     /**
747      * Return a VNF recipe that matches a given VF_MODULE_ID and ACTION
748      *
749      * @param vfModuleId
750      * @param action     
751      * @return VnfRecipe object or null if none found
752      */
753     public VnfRecipe getVnfRecipeByVfModuleId (String vnfType, String vfModuleId, String action) {
754         
755         StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vfModuleId = :vfModuleId and action = :action  ");
756         
757         long startTime = System.currentTimeMillis ();
758         LOGGER.debug ("Catalog database - get VNF Recipe with vfModuleId " + vfModuleId);
759            
760         Query query = getSession ().createQuery (hql.toString ());
761         query.setParameter (VF_MODULE_ID, vfModuleId);
762         query.setParameter (ACTION, action);
763         
764         @SuppressWarnings("unchecked")
765         List <VnfRecipe> resultList = query.list ();
766
767         if (resultList.isEmpty ()) {
768             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe Entry not found", "CatalogDB", "getVnfRecipeByVfModuleId", null);
769             return null;
770         }
771         
772         Collections.sort (resultList, new MavenLikeVersioningComparator ());
773         Collections.reverse (resultList);
774
775         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF Recipe Entry found", "CatalogDB", "getVnfRecipeByVfModuleId", null);
776         return resultList.get (0);
777     }
778     
779     public VfModule getVfModuleType(String type) {
780         long startTime = System.currentTimeMillis();
781         LOGGER.debug("Catalog database - get vfModuleType with type " + type);
782         
783         String hql = "FROM VfModule WHERE type = :type";
784         Query query = getSession().createQuery(hql);
785         query.setParameter("type",  type);
786         
787         @SuppressWarnings("unchecked")
788         List<VfModule> resultList = query.list();
789         if (resultList.isEmpty()) {
790             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleType", null);
791             return null;
792         }
793         Collections.sort (resultList, new MavenLikeVersioningComparator ());
794         Collections.reverse (resultList);
795
796         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
797         return resultList.get (0);
798     }
799     
800     public VfModule getVfModuleType(String type, String version) {
801         
802         long startTime = System.currentTimeMillis();
803         LOGGER.debug ("Catalog database - get vfModuleType with type " + type + " and model_version " + version);
804
805         String hql = "FROM VfModule WHERE type = :type and version = :version";
806         Query query = getSession().createQuery(hql);
807         query.setParameter ("type", type);
808         query.setParameter ("version", version);
809         VfModule module = null;
810         try {
811                 module = (VfModule) query.uniqueResult ();
812         } catch (org.hibernate.NonUniqueResultException nure) {
813                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: type='" + type + "', asdc_service_model_version='" + version + "'");
814                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for type==" + type);
815                 module = null;
816         } catch (org.hibernate.HibernateException he) {
817                 LOGGER.debug("Hibernate Exception - while searching for: type='" + type + "', asdc_service_model_version='" + version + "'");
818                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for type=" + type);
819                 module = null;
820         } catch (Exception e) {
821                 LOGGER.debug("Generic Exception - while searching for: type='" + type + "', asdc_service_model_version='" + version + "'");
822                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for type=" + type);
823                 module = null;
824         }
825         if (module == null) {
826                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null);
827         } else {
828                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
829         }
830         return module;
831     }
832    
833     
834     /**
835      * Return a VNF recipe that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME, and ACTION
836      * first query VF_MODULE table by type, and then use the ID to query 
837      * VNF_RECIPE by VF_MODULE_ID and ACTION 
838      *
839      * @param vnfType
840      * @parm vfModuleModelName
841      * @param action     
842      * @return VnfRecipe object or null if none found
843      */
844     public VnfRecipe getVfModuleRecipe (String vnfType, String vfModuleModelName, String action) {
845         String vfModuleType = vnfType + "::" + vfModuleModelName;
846         
847         StringBuilder hql = new StringBuilder ("FROM VfModule WHERE type = :type ");
848         
849         long startTime = System.currentTimeMillis ();
850         LOGGER.debug ("Catalog database - get VF MODULE  with type " + vfModuleType);
851            
852         Query query = getSession ().createQuery (hql.toString ());
853         query.setParameter (TYPE, vfModuleType);
854         
855         @SuppressWarnings("unchecked")
856         List <VfModule> resultList = query.list ();
857
858         if (resultList.isEmpty ()) {
859             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF Module Entry not found", "CatalogDB", "getVfModuleRecipe", null);
860             return null;
861         }
862         
863         Collections.sort (resultList, new MavenLikeVersioningComparator ());
864         Collections.reverse (resultList);
865
866         VfModule vfMod = resultList.get(0);
867         
868         int id = vfMod.getId();
869         String vfModuleId = Integer.toString(id);        
870         
871         StringBuilder hql1 = new StringBuilder ("FROM VnfRecipe WHERE vfModuleId = :vfModuleId AND action = :action ");
872           
873         LOGGER.debug ("Catalog database - get VNF recipe with vf module id " + vfModuleId
874                                       + " and action "
875                                       + action);
876
877         Query query1 = getSession ().createQuery (hql1.toString ());
878         query1.setParameter (VF_MODULE_ID, vfModuleId);
879         query1.setParameter (ACTION, action);
880        
881         @SuppressWarnings("unchecked")
882         List <VnfRecipe> resultList1 = query1.list ();
883
884         if (resultList1.isEmpty ()) {
885             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVfModuleRecipe", null);
886             return null;
887         }
888         
889         Collections.sort (resultList1, new MavenLikeVersioningComparator ());
890         Collections.reverse (resultList1);
891
892         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe found", "CatalogDB", "getVfModuleRecipe", null);
893         return resultList1.get (0);
894     }
895     
896     /**
897      * Return a VNF COMPONENTSrecipe that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME, 
898      * ASDC_SERVICE_MODEL_VERSION, MODEL_VERSION, and ACTION
899      * first query VF_MODULE table by type, and then use the ID to query 
900      * VNF_COMPONENTS_RECIPE by VF_MODULE_ID and ACTION 
901      *
902      * @param vnfType
903      * @parm vfModuleModelName
904      * @param action     
905      * @return VnfRecipe object or null if none found
906      */
907     public VnfComponentsRecipe getVnfComponentsRecipe (String vnfType, String vfModuleModelName, String asdcServiceModelVersion, String modelVersion, String action) {
908         String vfModuleType = vnfType + "::" + vfModuleModelName;
909         
910         StringBuilder hql = new StringBuilder ("FROM VfModule WHERE type = :type AND version = :version AND modelVersion = :modelVersion");
911         
912         long startTime = System.currentTimeMillis ();
913         LOGGER.debug ("Catalog database - get VF MODULE  with type " + vfModuleType + ", asdcServiceModelVersion " + asdcServiceModelVersion + ", modelVersion " + modelVersion);
914            
915         Query query = getSession ().createQuery (hql.toString ());
916         query.setParameter (TYPE, vfModuleType);
917         query.setParameter ("version", asdcServiceModelVersion);
918         query.setParameter ("modelVersion", modelVersion);
919         
920         @SuppressWarnings("unchecked")
921         List <VfModule> resultList = query.list ();
922
923         if (resultList.isEmpty ()) {
924             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF Module Entry not found", "CatalogDB", "getVnfComponentsRecipe", null);
925             return null;
926         }
927         
928         Collections.sort (resultList, new MavenLikeVersioningComparator ());
929         Collections.reverse (resultList);
930
931         VfModule vfMod = resultList.get(0);
932         
933         int id = vfMod.getId();
934         String vfModuleId = Integer.toString(id);        
935         
936         StringBuilder hql1 = new StringBuilder ("FROM VnfComponentsRecipe WHERE vfModuleId = :vfModuleId AND action = :action ");
937           
938         LOGGER.debug ("Catalog database - get Vnf Components recipe with vf module id " + vfModuleId
939                                       + " and action "
940                                       + action);
941
942         Query query1 = getSession ().createQuery (hql1.toString ());
943         query1.setParameter (VF_MODULE_ID, vfModuleId);
944         query1.setParameter (ACTION, action);
945        
946         @SuppressWarnings("unchecked")
947         List <VnfComponentsRecipe> resultList1 = query1.list ();
948
949         if (resultList1.isEmpty ()) {
950             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfComponentsRecipe", null);
951             return null;
952         }
953         
954         Collections.sort (resultList1, new MavenLikeVersioningComparator ());
955         Collections.reverse (resultList1);
956
957         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe found", "CatalogDB", "getVnfComponentsRecipe", null);
958         if (resultList1.size() > 1 && (!resultList1. get (0).getOrchestrationUri().equals(resultList1.get (1).getOrchestrationUri ()))) {
959                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Different ORCHESTRATION URIs found for same VERSION and ID. No result returned.", "CatalogDB", "getVnfComponentsRecipe", null);
960                 return null;
961         }
962         return resultList1.get (0);
963     }
964
965
966     /**
967      * Return all VNF Resources in the Catalog DB
968      *
969      * @return A list of VnfResource objects
970      */
971     @SuppressWarnings("unchecked")
972     public List <VnfResource> getAllVnfResources () {
973
974         long startTime = System.currentTimeMillis ();
975         LOGGER.debug ("Catalog database - get all VNF resources");
976
977         String hql = "FROM VnfResource";
978         Query query = getSession ().createQuery (hql);
979
980         List <VnfResource> result = query.list ();
981         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVnfResources", null);
982         return result;
983     }
984
985     /**
986      * Return VNF Resources in the Catalog DB that match a given VNF role
987      *
988      * @return A list of VnfResource objects
989      */
990     @SuppressWarnings("unchecked")
991     public List <VnfResource> getVnfResourcesByRole (String vnfRole) {
992
993         long startTime = System.currentTimeMillis ();
994         LOGGER.debug ("Catalog database - get all VNF resources for role " + vnfRole);
995
996         String hql = "FROM VnfResource WHERE vnfRole = :vnfRole";
997         Query query = getSession ().createQuery (hql);
998         query.setParameter ("vnfRole", vnfRole);
999
1000         List <VnfResource> resources = query.list ();
1001         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourcesByRole", null);
1002         return resources;
1003     }
1004
1005     /**
1006      * Return all Network Resources in the Catalog DB
1007      *
1008      * @return A list of NetworkResource objects
1009      */
1010     @SuppressWarnings("unchecked")
1011     public List <NetworkResource> getAllNetworkResources () {
1012
1013         long startTime = System.currentTimeMillis ();
1014         LOGGER.debug ("Catalog database - get all network resources");
1015
1016         String hql = "FROM NetworkResource";
1017         Query query = getSession ().createQuery (hql);
1018
1019         List <NetworkResource> result = query.list ();
1020         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworkResources", null);
1021         return result;
1022     }
1023     
1024     /**
1025      * Return all VF Modules in the Catalog DB
1026      *
1027      * @return A list of VfModule objects
1028      */
1029     @SuppressWarnings("unchecked")
1030     public List <VfModule> getAllVfModules () {
1031
1032         long startTime = System.currentTimeMillis ();
1033         LOGGER.debug ("Catalog database - get all vf modules");
1034
1035         String hql = "FROM VfModule";
1036         Query query = getSession ().createQuery (hql);
1037
1038         List <VfModule> result = query.list ();
1039         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVfModules", null);
1040         return result;
1041     }
1042
1043     /**
1044      * Return all HeatEnvironment in the Catalog DB
1045      *
1046      * @return A list of HeatEnvironment objects
1047      */
1048     @SuppressWarnings("unchecked")
1049     public List <HeatEnvironment> getAllHeatEnvironment () {
1050
1051         long startTime = System.currentTimeMillis ();
1052         LOGGER.debug ("Catalog database - get all Heat environments");
1053
1054         String hql = "FROM HeatEnvironment";
1055         Query query = getSession ().createQuery (hql);
1056
1057         List <HeatEnvironment> result = query.list ();
1058         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllHeatEnvironment", null);
1059         return result;
1060     }
1061
1062     /**
1063      * Fetch the Environment by Environment ID - 1510
1064      */
1065     public HeatEnvironment getHeatEnvironment (int id) {
1066
1067         long startTime = System.currentTimeMillis ();
1068         LOGGER.debug ("Catalog database - get Heat environment with id " + id);
1069
1070         String hql = "FROM HeatEnvironment WHERE id = :idValue";
1071
1072         LOGGER.debug ("getHeatEnvironment called with id=" + id);
1073
1074         Query query = getSession ().createQuery (hql);
1075         query.setParameter ("idValue", id);
1076
1077         @SuppressWarnings("unchecked")
1078         List <HeatEnvironment> resultList = query.list ();
1079
1080         // See if something came back.
1081         if (resultList.isEmpty ()) {
1082             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat environment not found", "CatalogDB", "getHeatEnvironment", null);
1083             return null;
1084         }
1085         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatEnvironment", null);
1086         return resultList.get (0);
1087     }
1088
1089     /**
1090      * Fetch the nested templates - 1510
1091      */
1092
1093     public Map <String, Object> getNestedTemplates (int templateId) {
1094         Map <String, Object> nestedTemplates = null;
1095         long startTime = System.currentTimeMillis ();
1096         LOGGER.debug ("Catalog database - getNestedTemplates called with templateId " + templateId);
1097
1098         String hql = "FROM HeatNestedTemplate where parent_template_id = :parentIdValue";
1099
1100         Query query = getSession ().createQuery (hql);
1101         query.setParameter ("parentIdValue", templateId);
1102
1103         @SuppressWarnings("unchecked")
1104         List <HeatNestedTemplate> resultList = query.list ();
1105         // If nothing comes back, there are no nested templates
1106         if (resultList.isEmpty ()) {
1107             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No nestedTemplate found", "CatalogDB", "getNestedTemplates", null);
1108             LOGGER.debug ("No nestedTemplates found for templateId=" + templateId + ", " + hql);
1109             return null;
1110         }
1111         // Now, for each entry in NESTED_HEAT_TEMPLATES, we need to grab the template body from HEAT_TEMPLATE
1112         nestedTemplates = new HashMap <String, Object> ();
1113         for (HeatNestedTemplate hnt : resultList) {
1114             LOGGER.debug ("Querying for " + hnt);
1115             HeatTemplate ht = this.getHeatTemplate (hnt.getChildTemplateId ());
1116             if (ht == null) {
1117                 LOGGER.debug ("No template found matching childTemplateId=" + hnt.getChildTemplateId ());
1118                 continue;
1119             }
1120             String providerResourceFile = hnt.getProviderResourceFile ();
1121             String heatTemplateBody = ht.getTemplateBody ();
1122             if (providerResourceFile != null && heatTemplateBody != null) {
1123                 nestedTemplates.put (providerResourceFile, heatTemplateBody);
1124             } else {
1125                 LOGGER.debug ("providerResourceFile or heatTemplateBody were null - do not add to HashMap!");
1126             }
1127         }
1128         // Make sure we're not returning an empty map - if so, just return null
1129         if (nestedTemplates.isEmpty ()) {
1130             LOGGER.debug ("nestedTemplates is empty - just return null");
1131             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Nested template is empty", "CatalogDB", "getNestedTemplate", null);
1132             return null;
1133         }
1134         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedTemplate", null);
1135         return nestedTemplates;
1136     }
1137
1138     /*
1139      * Fetch any files in the HEAT_FILES table 1510
1140      */
1141     public Map <String, HeatFiles> getHeatFiles (int vnfResourceId) {
1142        Map <String, HeatFiles> heatFiles = null;
1143
1144         long startTime = System.currentTimeMillis ();
1145         LOGGER.debug ("Catalog database - getHeatFiles called with vnfResourceId " + vnfResourceId);
1146         String hql = "FROM HeatFiles where vnf_resource_id = :vnfResourceIdValue";
1147
1148         Query query = getSession ().createQuery (hql);
1149         query.setParameter ("vnfResourceIdValue", vnfResourceId);
1150
1151         @SuppressWarnings("unchecked")
1152         List <HeatFiles> resultList = query.list ();
1153         // If nothing comes back, there are no heat files
1154         if (resultList.isEmpty ()) {
1155             LOGGER.debug ("No heatFiles found for vnfResourceId=" + vnfResourceId);
1156             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No heat files", "CatalogDB", "getHeatFiles", null);
1157             return null;
1158         }
1159         // Now, we just need to return a HashMap (key=fileName, object=fileBody)
1160         heatFiles = new HashMap <String, HeatFiles> ();
1161         for (HeatFiles hf : resultList) {
1162             LOGGER.debug ("Adding " + hf.getFileName () + "->" + hf.getFileBody ());
1163             heatFiles.put (hf.getFileName (), hf);
1164         }
1165         // Make sure we're not returning an empty map - if so, just return null
1166         if (heatFiles.isEmpty ()) {
1167             LOGGER.debug ("heatFiles is empty - just return null");
1168             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat files is empty", "CatalogDB", "getHeatFiles", null);
1169             return null;
1170         }
1171         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFiles", null);
1172         return heatFiles;
1173     }
1174     
1175     // New 1607 - with modularization, use new table to determine which HEAT_FILES entries to attach
1176     
1177     public Map <String, HeatFiles> getHeatFilesForVfModule(int vfModuleId) {
1178         Map <String, HeatFiles> heatFiles = null;
1179
1180         long startTime = System.currentTimeMillis ();
1181         LOGGER.debug ("Catalog database - getHeatFilesForVfModule called with vfModuleId " + vfModuleId);
1182         String hql = "FROM VfModuleToHeatFiles where vf_module_id = :vfModuleIdValue";
1183
1184         Query query = getSession ().createQuery (hql);
1185         query.setParameter ("vfModuleIdValue", vfModuleId);
1186         
1187         List<VfModuleToHeatFiles> mapList = query.list();
1188         if (mapList.isEmpty()) {
1189             LOGGER.debug ("No heatFiles found for vfModuleId=" + vfModuleId);
1190             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No heatfiles found for vfModule", "CatalogDB", "getHeatFilesForVfModule", null);
1191             return null;
1192         }
1193         //Now the fun part - we have a list of the heat files we need to get - could clean this up with a join
1194         //TODO - convert this all with one join - brute force for now due to time
1195         heatFiles = new HashMap<String, HeatFiles>();
1196         for (VfModuleToHeatFiles vmthf : mapList) {
1197                 int heatFilesId = vmthf.getHeatFilesId();
1198                 hql = "FROM HeatFiles where id = :id_value";
1199                 query = getSession().createQuery(hql);
1200                 query.setParameter("id_value", heatFilesId);
1201                 List<HeatFiles> fileList = query.list();
1202                 if (fileList.isEmpty()) {
1203                         // Should this throw an exception??
1204                         LOGGER.debug("Unable to find a HEAT_FILES entry at " + heatFilesId);
1205                 String errorString = "_ERROR|" + heatFilesId;
1206                         // The receiving code needs to know to throw an exception for this - or ignore it.
1207                         heatFiles.put(errorString, null);
1208                 } else {
1209                         // Should only ever have 1 result - add it to our Map
1210                         LOGGER.debug("Retrieved " + fileList.size() + " heat file entry at " + heatFilesId);
1211                         for (HeatFiles hf : fileList) {
1212                                 LOGGER.debug("Adding " + hf.getFileName() + "->" + hf.getFileBody());
1213                                 heatFiles.put(hf.getFileName(), hf);
1214                         }
1215                 }
1216         }
1217         if (heatFiles.isEmpty()) {
1218             LOGGER.debug ("heatFiles is empty - just return null");
1219             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles is empty", "CatalogDB", "getHeatFilesForVfModule", null);
1220             return null;
1221         }
1222         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFilesForVfModule", null);
1223         return heatFiles;
1224     }
1225
1226     
1227     
1228     /**
1229      * Get the heat template object based on asdc attributes
1230      *
1231      * @param templateName The template name, generally the yaml filename. "example.yaml"
1232      * @param version The version as specified by ASDC. "1.1"
1233      * @param asdcResourceName The ASDC resource name provided in the ASDC artifact
1234      *
1235      * @return The HeatTemplate
1236      */
1237     public HeatTemplate getHeatTemplate (String templateName, String version, String asdcResourceName) {
1238
1239         long startTime = System.currentTimeMillis ();
1240         LOGGER.debug ("Catalog database - getHeatTemplate with name " + templateName
1241                                       + " and version "
1242                                       + version
1243                                       + " and ASDC resource name "
1244                                       + asdcResourceName);
1245
1246         String hql = "FROM HeatTemplate WHERE templateName = :template_name AND version = :version AND asdcResourceName = :asdcResourceName";
1247         Query query = getSession ().createQuery (hql);
1248         query.setParameter ("template_name", templateName);
1249         query.setParameter ("version", version);
1250         query.setParameter ("asdcResourceName", asdcResourceName);
1251
1252         @SuppressWarnings("unchecked")
1253         List <HeatTemplate> resultList = query.list ();
1254
1255         // See if something came back.
1256         if (resultList.isEmpty ()) {
1257             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat template not found", "CatalogDB", "getHeatTemplate", null);
1258             return null;
1259         }
1260         // Name + Version is unique, so should only be one element
1261         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
1262         return resultList.get (0);
1263     }
1264
1265     /**
1266      * Save the Heat Template
1267      *
1268      * @param heat The heat template
1269      * @param paramSet The list of heat template parameters
1270      */
1271     public void saveHeatTemplate (HeatTemplate heat, Set <HeatTemplateParam> paramSet) {
1272
1273         long startTime = System.currentTimeMillis ();
1274         LOGGER.debug ("Catalog database - save Heat Template with name " + heat.getTemplateName());
1275
1276         heat.setParameters(null);
1277         try {
1278             HeatTemplate heatTemp = this.getHeatTemplate (heat.getTemplateName (),
1279                                                           heat.getVersion (),
1280                                                           heat.getAsdcResourceName ());
1281             if (heatTemp == null) {
1282                 this.getSession ().save (heat);
1283
1284                 if (paramSet != null) {
1285                     for (HeatTemplateParam param : paramSet) {
1286                         param.setHeatTemplateId (heat.getId ());
1287                     }
1288                     heat.setParameters (paramSet);
1289                     this.getSession ().merge (heat);
1290                 }
1291
1292             } else {
1293                 heat.setId(heatTemp.getId());
1294             }
1295         } finally {
1296                 heat.setParameters(paramSet);
1297             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
1298         }
1299     }
1300
1301     /**
1302      * Retrieves a Heat environment from DB based on its unique key.
1303      *
1304      * @param name the environment artifact name
1305      * @param version the environment resource version
1306      * @param asdcResourceName the environment resource name
1307      * @return the heat environment from DB or null if not found
1308      */
1309     public HeatEnvironment getHeatEnvironment (String name, String version, String asdcResourceName) {
1310         long startTime = System.currentTimeMillis ();
1311         LOGGER.debug ("Catalog database - get Heat environment with name " + name
1312                                       + " and version "
1313                                       + version
1314                                       + " and ASDC resource name "
1315                                       + asdcResourceName);
1316
1317         String hql = "FROM HeatEnvironment WHERE name=:name AND version=:version AND asdcResourceName=:asdcResourceName";
1318         Query query = getSession ().createQuery (hql);
1319         query.setParameter ("name", name);
1320         query.setParameter ("version", version);
1321         query.setParameter ("asdcResourceName", asdcResourceName);
1322         HeatEnvironment env = null;
1323         try {
1324                 env = (HeatEnvironment) query.uniqueResult ();
1325         } catch (org.hibernate.NonUniqueResultException nure) {
1326                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: envName='" + name + "', version='" + version + "' and asdcResourceName=" + asdcResourceName);
1327                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for envName=" + name + " and version=" + version + " and asdcResourceName=" + asdcResourceName, "", "", MsoLogger.ErrorCode.DataError, "non unique result for envName=" + name);
1328                 env = null;
1329         } catch (org.hibernate.HibernateException he) {
1330                 LOGGER.debug("Hibernate Exception - while searching for: envName='" + name + "', asdc_service_model_version='" + version + "' and asdcResourceName=" + asdcResourceName);
1331                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for envName=" + name + " and version=" + version + " and asdcResourceName=" + asdcResourceName, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for envName=" + name);
1332                 env = null;
1333         } catch (Exception e) {
1334                 LOGGER.debug("Generic Exception - while searching for: envName='" + name + "', asdc_service_model_version='" + version + "' and asdcResourceName=" + asdcResourceName);
1335                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for envName=" + name + " and version=" + version + " and asdcResourceName=" + asdcResourceName, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for envName=" + name);
1336                 env = null;
1337         }
1338         if (env == null) {
1339                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getHeatTemplate", null);
1340         } else {
1341                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
1342         }
1343         return env;
1344     }
1345
1346     /**
1347      * Save the HeatEnvironment
1348      *
1349      * @param env The Environment
1350      */
1351     public void saveHeatEnvironment (HeatEnvironment env) {
1352         long startTime = System.currentTimeMillis ();
1353         LOGGER.debug ("Catalog database - save Heat environment with name "
1354                                       + env.getEnvironment());
1355         try {
1356             HeatEnvironment dbEnv = getHeatEnvironment (env.getName (), env.getVersion (), env.getAsdcResourceName ());
1357             if (dbEnv == null) {
1358
1359                 this.getSession ().save (env);
1360                
1361             } else {
1362                 env.setId(dbEnv.getId());
1363             }
1364
1365         } finally {
1366             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
1367         }
1368     }
1369
1370     /**
1371      * Save the heatTemplate
1372      *
1373      * @param heat The heat template
1374      */
1375     public void saveHeatTemplate (HeatTemplate heat) {
1376         long startTime = System.currentTimeMillis ();
1377         LOGGER.debug ("Catalog database - save Heat template with name " + heat.getTemplateName ());
1378         try {
1379             this.getSession ().update (heat);
1380         } finally {
1381             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
1382         }
1383     }
1384
1385     public void saveHeatFile (HeatFiles heatFile) {
1386         long startTime = System.currentTimeMillis ();
1387         LOGGER.debug ("Catalog database - save Heat file with name " + heatFile.getFileName ());
1388         try {
1389             this.getSession ().save (heatFile);
1390         } finally {
1391             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatFile", null);
1392         }
1393     }
1394
1395     public void saveVnfRecipe (VnfRecipe vnfRecipe) {
1396         long startTime = System.currentTimeMillis ();
1397         LOGGER.debug ("Catalog database - save VNF recipe with VNF type " + vnfRecipe.getVnfType ());
1398         try {
1399             this.getSession ().save (vnfRecipe);
1400         } finally {
1401             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfRecipe", null);
1402         }
1403     }
1404     
1405     public void saveVnfComponentsRecipe (VnfComponentsRecipe vnfComponentsRecipe) {
1406         long startTime = System.currentTimeMillis ();
1407         LOGGER.debug ("Catalog database - save VNF Component recipe with VNF type " + vnfComponentsRecipe.getVnfType ());
1408         try {
1409             this.getSession ().save (vnfComponentsRecipe);
1410         } finally {
1411             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfComponentsRecipe", null);
1412         }
1413     }
1414
1415
1416     public void saveOrUpdateVnfResource (VnfResource vnfResource) {
1417         long startTime = System.currentTimeMillis ();
1418         LOGGER.debug ("Catalog database - save VNF Resource with VNF type " + vnfResource.getVnfType ());
1419         try {
1420
1421             if (vnfResource.getId() != 0) {
1422                 this.getSession ().merge (vnfResource);
1423             } else {
1424                 this.getSession ().save (vnfResource);
1425             }
1426       
1427         } finally {
1428             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVnfResource", null);
1429         }
1430     }
1431     
1432     public void saveService (Service service) {
1433         long startTime = System.currentTimeMillis ();
1434         LOGGER.debug ("Catalog database - save Service with ServiceName/Version/serviceUUID(SERVICE_NAME_VERSION_ID)" + service.getServiceName()+"/"+service.getServiceVersion()+"/"+service.getServiceNameVersionId());
1435         try {
1436                 Service serviceDB = this.getServiceByUUID(service.getServiceNameVersionId());
1437             if (serviceDB == null) {
1438                 this.getSession ().save (service);
1439             }
1440       
1441         } finally {
1442             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateService", null);
1443         }
1444     }
1445     
1446     public void saveOrUpdateVfModule (VfModule vfModule) {
1447         long startTime = System.currentTimeMillis ();
1448         LOGGER.debug ("Catalog database - save VNF Module with VF Model Name " + vfModule.getModelName());
1449         try {
1450
1451             if (vfModule.getId() != 0) {
1452                 this.getSession ().merge (vfModule);
1453             } else {
1454                 this.getSession ().save (vfModule);
1455             }
1456       
1457         } finally {
1458             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVfModule", null); 
1459         }
1460     }
1461
1462     public HeatNestedTemplate getNestedHeatTemplate(int parentTemplateId, int childTemplateId) {
1463           long startTime = System.currentTimeMillis ();
1464           LOGGER.debug ("Catalog database - get nested Heat template with PerentId-Child Id "
1465                                         + parentTemplateId +"-"+childTemplateId);
1466           try {
1467               HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
1468               nestedTemplate.setParentTemplateId (parentTemplateId);
1469               nestedTemplate.setChildTemplateId (childTemplateId);
1470               
1471               return (HeatNestedTemplate)session.get (HeatNestedTemplate.class,nestedTemplate);
1472           } finally {
1473               LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedHeatTemplate", null);
1474           }
1475     }
1476       
1477     public void saveNestedHeatTemplate (int parentTemplateId, HeatTemplate childTemplate, String yamlFile) {
1478         long startTime = System.currentTimeMillis ();
1479         LOGGER.debug ("Catalog database - save nested Heat template with name "
1480                                       + childTemplate.getTemplateName ());
1481         try {
1482       
1483                 saveHeatTemplate(childTemplate, childTemplate.getParameters());
1484                 if (getNestedHeatTemplate(parentTemplateId,childTemplate.getId()) == null) { 
1485                     HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
1486                     nestedTemplate.setParentTemplateId (parentTemplateId);
1487                     nestedTemplate.setChildTemplateId (childTemplate.getId ());
1488                     nestedTemplate.setProviderResourceFile (yamlFile);
1489                     session.save (nestedTemplate);
1490                 }
1491         } finally {
1492             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNestedHeatTemplate", null);
1493         }
1494     }
1495     
1496     public HeatFiles getHeatFiles(int vnfResourceId,String fileName,String asdcResourceName, String version) {
1497           long startTime = System.currentTimeMillis ();
1498           LOGGER.debug ("Catalog database - getHeatFiles with name " + fileName
1499                                         + " and vnfResourceID "
1500                                         + vnfResourceId
1501 //                                        + " and ASDC resource name "
1502                                         + asdcResourceName
1503                                         + " and version "
1504                                         + version);
1505
1506           String hql = "FROM HeatFiles WHERE fileName = :fileName AND vnfResourceId = :vnfResourceId AND asdcResourceName = :asdcResourceName AND version = :version";
1507           Query query = getSession ().createQuery (hql);
1508           query.setParameter ("fileName", fileName);
1509           query.setParameter ("vnfResourceId", vnfResourceId);
1510           query.setParameter ("asdcResourceName", asdcResourceName);
1511           query.setParameter ("version", version);
1512
1513           @SuppressWarnings("unchecked")
1514         
1515           HeatFiles heatFilesResult = null;
1516           try {
1517                   heatFilesResult = (HeatFiles) query.uniqueResult ();
1518           } catch (org.hibernate.NonUniqueResultException nure) {
1519                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: fileName='" + fileName + "', vnfResourceId='" + vnfResourceId + "' and asdcResourceName=" + asdcResourceName + " and version=" + version);
1520                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for fileName=" + fileName + " and vnfResourceId=" + vnfResourceId + " and asdcResourceName=" + asdcResourceName + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for fileName=" + fileName);
1521                 heatFilesResult = null;
1522           } catch (org.hibernate.HibernateException he) {
1523                 LOGGER.debug("Hibernate Exception - while searching for: fileName='" + fileName + "', vnfResourceId='" + vnfResourceId + "' and asdcResourceName=" + asdcResourceName + " and version=" + version);
1524                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for fileName=" + fileName + " and vnfResourceId=" + vnfResourceId + " and asdcResourceName=" + asdcResourceName + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for fileName=" + fileName);
1525                 heatFilesResult = null;
1526           } catch (Exception e) {
1527                 LOGGER.debug("Generic Exception - while searching for: fileName='" + fileName + "', vnfResourceId='" + vnfResourceId + "' and asdcResourceName=" + asdcResourceName + " and version=" + version);
1528                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for fileName=" + fileName + " and vnfResourceId=" + vnfResourceId + " and asdcResourceName=" + asdcResourceName + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for fileName=" + fileName);
1529                 heatFilesResult = null;
1530           } 
1531           
1532           // See if something came back.
1533           if (heatFilesResult == null) {
1534               LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles not found", "CatalogDB", "getHeatFiles", null);
1535               return null;
1536           }
1537           // Name + Version is unique, so should only be one element
1538           LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFiles", null);
1539           return heatFilesResult;
1540     }
1541     
1542     public void saveHeatFiles (HeatFiles childFile) {
1543          long startTime = System.currentTimeMillis ();
1544          LOGGER.debug ("Catalog database - save Heat File with name "
1545                                        + childFile.getFileName());
1546          try {
1547              HeatFiles heatFiles = getHeatFiles (childFile.getVnfResourceId(), childFile.getFileName(), childFile.getAsdcResourceName (),childFile.getVersion());
1548              if (heatFiles == null) {
1549
1550                  // asdc_heat_files_save
1551                  this.getSession ().save (childFile);
1552                  
1553              } else {
1554                  /* replaced 'heatFiles' by 'childFile'
1555                     Based on following comment:
1556                                         It must be childFile.setId instead of heatFiles.setId, we must return the ID if it exists in DB.
1557                                  */
1558                  childFile.setId(heatFiles.getId());
1559              }
1560
1561          } finally {
1562              LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatFiles", null);
1563          }
1564     }
1565     
1566     public void saveVfModuleToHeatFiles (int parentVfModuleId, HeatFiles childFile) {
1567         long startTime = System.currentTimeMillis ();
1568         LOGGER.debug ("Catalog database - save Heat File to VFmodule link "
1569                                       + childFile.getFileName());
1570         try {
1571             saveHeatFiles (childFile);
1572             VfModuleToHeatFiles vfModuleToHeatFile = new VfModuleToHeatFiles ();
1573                 vfModuleToHeatFile.setVfModuleId(parentVfModuleId);
1574                 vfModuleToHeatFile.setHeatFilesId(childFile.getId());
1575                     
1576                 session.save (vfModuleToHeatFile);
1577           
1578         } finally {
1579             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVfModuleToHeatFiles", null);
1580         }
1581     }
1582     
1583
1584     /**
1585      * Return a Network recipe that matches a given NETWORK_TYPE, ACTION, and, if specified, SERVICE_TYPE
1586      *
1587      * @param networkType
1588      * @param action
1589      * @param serviceType
1590      * @return NetworkRecipe object or null if none found
1591      */
1592     public NetworkRecipe getNetworkRecipe (String networkType, String action, String serviceType) {
1593
1594         long startTime = System.currentTimeMillis ();
1595         LOGGER.debug ("Catalog database - get network recipe with network type " + networkType
1596                                       + " and action "
1597                                       + action
1598                                       + " and service type "
1599                                       + serviceType);
1600
1601         try {
1602             String hql;
1603             if (serviceType == null) {
1604                 hql = "FROM NetworkRecipe WHERE networkType = :networkType AND action = :action AND serviceType IS NULL ";
1605             } else {
1606                 hql = "FROM NetworkRecipe WHERE networkType = :networkType AND action = :action AND serviceType = :serviceType ";
1607             }
1608             Query query = getSession ().createQuery (hql);
1609             query.setParameter (NETWORK_TYPE, networkType);
1610             query.setParameter (ACTION, action);
1611             if (serviceType != null) {
1612                 query.setParameter ("serviceType", serviceType);
1613             }
1614
1615             @SuppressWarnings("unchecked")
1616             List <NetworkRecipe> resultList = query.list ();
1617
1618             if (resultList.isEmpty ()) {
1619                 return null;
1620             }
1621             
1622             Collections.sort (resultList, new MavenLikeVersioningComparator ());
1623             Collections.reverse (resultList);
1624             
1625             return resultList.get (0);
1626         } finally {
1627             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
1628         }
1629     }
1630     
1631     /**
1632      * Return a Network recipe that matches a given NETWORK_TYPE and ACTION
1633      *
1634      * @param networkType
1635      * @param action 
1636      * @return NetworkRecipe object or null if none found
1637      */
1638     public NetworkRecipe getNetworkRecipe (String networkType, String action) {
1639
1640         long startTime = System.currentTimeMillis ();
1641         LOGGER.debug ("Catalog database - get network recipe with network type " + networkType
1642                                       + " and action "
1643                                       + action
1644                                       );
1645
1646         try {
1647             String hql = "FROM NetworkRecipe WHERE networkType = :networkType AND action = :action";
1648             
1649             Query query = getSession ().createQuery (hql);
1650             query.setParameter (NETWORK_TYPE, networkType);
1651             query.setParameter (ACTION, action);
1652             
1653             @SuppressWarnings("unchecked")
1654             List <NetworkRecipe> resultList = query.list ();
1655
1656             if (resultList.isEmpty ()) {
1657                 return null;
1658             }
1659             
1660             Collections.sort (resultList, new MavenLikeVersioningComparator ());
1661             Collections.reverse (resultList);
1662             
1663             return resultList.get (0);
1664         } finally {
1665             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
1666         }
1667     }
1668
1669     /**
1670      * Return a VnfComponents recipe that matches a given VNF_TYPE, VNF_COMPONENT_TYPE, ACTION, and, if specified,
1671      * SERVICE_TYPE
1672      *
1673      * @param vnfType
1674      * @param vnfComponentType
1675      * @param action
1676      * @param serviceType
1677      * @return VnfComponentsRecipe object or null if none found
1678      */
1679     public VnfComponentsRecipe getVnfComponentsRecipe (String vnfType,
1680                                                        String vnfComponentType,
1681                                                        String action,
1682                                                        String serviceType) {
1683
1684         long startTime = System.currentTimeMillis ();
1685         LOGGER.debug ("Catalog database - get Vnf Component recipe with network type " + vnfType
1686                                       + " and component type "
1687                                       + vnfComponentType
1688                                       + " and action "
1689                                       + action
1690                                       + " and service type "
1691                                       + serviceType);
1692
1693         try {
1694             String hql;
1695             if (serviceType == null) {
1696                 hql = "FROM VnfComponentsRecipe WHERE vnfType = :vnfType AND vnfComponentType = :vnfComponentType AND action = :action AND serviceType IS NULL ";
1697             } else {
1698                 hql = "FROM VnfComponentsRecipe WHERE vnfType = :vnfType AND vnfComponentType = :vnfComponentType AND action = :action AND serviceType = :serviceType ";
1699             }
1700             Query query = getSession ().createQuery (hql);
1701             query.setParameter (VNF_TYPE, vnfType);
1702             query.setParameter (VNF_COMPONENT_TYPE, vnfComponentType);
1703             query.setParameter (ACTION, action);
1704             if (serviceType != null) {
1705                 query.setParameter ("serviceType", serviceType);
1706             }
1707
1708             @SuppressWarnings("unchecked")
1709             List <VnfComponentsRecipe> resultList = query.list ();
1710
1711             if (resultList.isEmpty ()) {
1712                 return null;
1713             }
1714             Collections.sort (resultList, new MavenLikeVersioningComparator ());
1715             Collections.reverse (resultList);
1716             
1717             return resultList.get (0);
1718         } finally {
1719             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponentsRecipe", null);
1720         }
1721     }
1722     
1723     /**
1724      * Return a VnfComponents recipe that matches a given VF_MODULE_ID, VNF_COMPONENT_TYPE, ACTION
1725      *
1726      * @param vfModuleId
1727      * @param vnfComponentType
1728      * @param action    
1729      * @return VnfComponentsRecipe object or null if none found
1730      */
1731     public VnfComponentsRecipe getVnfComponentsRecipeByVfModuleId (String vfModuleId,
1732                                                        String vnfComponentType,
1733                                                        String action) {                     
1734
1735         long startTime = System.currentTimeMillis ();
1736         LOGGER.debug ("Catalog database - get Vnf Component recipe with vfModuleId " + vfModuleId
1737                                       + " and component type "
1738                                       + vnfComponentType
1739                                       + " and action "
1740                                       + action);
1741
1742         try {
1743             String hql;
1744             hql = "FROM VnfComponentsRecipe WHERE vfModuleId = :vfModuleId AND vnfComponentType = :vnfComponentType AND action = :action ";
1745             
1746             Query query = getSession ().createQuery (hql);
1747             query.setParameter (VF_MODULE_ID, vfModuleId);
1748             query.setParameter (VNF_COMPONENT_TYPE, vnfComponentType);
1749             query.setParameter (ACTION, action);
1750             
1751             @SuppressWarnings("unchecked")
1752             List <VnfComponentsRecipe> resultList = query.list ();
1753
1754             if (resultList.isEmpty ()) {
1755                 return null;
1756             }
1757             Collections.sort (resultList, new MavenLikeVersioningComparator ());
1758             Collections.reverse (resultList);
1759             
1760             return resultList.get (0);
1761         } finally {
1762             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponentsRecipeByVfModuleId", null);
1763         }
1764     }
1765
1766
1767
1768     public void saveOrUpdateVnfComponent (VnfComponent vnfComponent) {
1769         long startTime = System.currentTimeMillis ();
1770
1771         LOGGER.debug ("Catalog database - save VnfComponent where vnfId="+ vnfComponent.getVnfId()+ " AND componentType="+ vnfComponent.getComponentType());
1772
1773         VnfComponent vnfComponentDb = this.getVnfComponent(vnfComponent.getVnfId(), vnfComponent.getComponentType());
1774
1775         try {
1776
1777             if (vnfComponentDb != null) {
1778                 this.getSession ().merge (vnfComponent);
1779             } else {
1780                 this.getSession ().save (vnfComponent);
1781             }
1782
1783         } finally {
1784             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVnfComponent", null);
1785         }
1786     }
1787
1788     /**
1789      * Return a VfModule record that matches a given MODEL_NAME
1790      *
1791      * @param modelName
1792      * @return VfModule object or null if none found
1793      */
1794     public VfModule getVfModule (String modelName) {
1795
1796         long startTime = System.currentTimeMillis ();
1797         LOGGER.debug ("Catalog database - get vf module with model name " + modelName);
1798
1799         try {
1800             String hql;
1801
1802             hql = "FROM VfModule WHERE modelName = :modelName";
1803
1804             Query query = getSession ().createQuery (hql);
1805             query.setParameter (MODEL_NAME, modelName);
1806
1807             @SuppressWarnings("unchecked")
1808             List <VfModule> resultList = query.list ();
1809
1810             if (resultList.isEmpty ()) {
1811                 return null;
1812             }
1813             Collections.sort (resultList, new MavenLikeVersioningComparator ());
1814             Collections.reverse (resultList);
1815
1816             return resultList.get (0);
1817         } finally {
1818             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModule", null);
1819         }
1820     }
1821
1822
1823     /**
1824      * Verify the health of the DB.
1825      *
1826      * @return boolean value indicate whether DB is healthy
1827      */
1828     public boolean healthCheck () {
1829         long startTime = System.currentTimeMillis ();
1830         Session session = this.getSession ();
1831
1832         Query query = session.createSQLQuery (" show tables ");
1833
1834         List<?> list = query.list();
1835         LOGGER.debug("healthCheck CatalogDB - Successful");
1836         return true;
1837     }
1838 }