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