Swap Collection.sort with list.sort
[so.git] / mso-catalog-db / src / main / java / org / openecomp / mso / db / catalog / CatalogDatabase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.mso.db.catalog;
23
24 import java.io.Closeable;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32
33 import org.hibernate.HibernateException;
34 import org.hibernate.Query;
35 import org.hibernate.Session;
36 import org.openecomp.mso.db.AbstractSessionFactoryManager;
37 import org.openecomp.mso.db.catalog.beans.AllottedResource;
38 import org.openecomp.mso.db.catalog.beans.AllottedResourceCustomization;
39 import org.openecomp.mso.db.catalog.beans.ArRecipe;
40 import org.openecomp.mso.db.catalog.beans.HeatEnvironment;
41 import org.openecomp.mso.db.catalog.beans.HeatFiles;
42 import org.openecomp.mso.db.catalog.beans.HeatNestedTemplate;
43 import org.openecomp.mso.db.catalog.beans.HeatTemplate;
44 import org.openecomp.mso.db.catalog.beans.HeatTemplateParam;
45 import org.openecomp.mso.db.catalog.beans.Model;
46 import org.openecomp.mso.db.catalog.beans.ModelRecipe;
47 import org.openecomp.mso.db.catalog.beans.NetworkRecipe;
48 import org.openecomp.mso.db.catalog.beans.NetworkResource;
49 import org.openecomp.mso.db.catalog.beans.NetworkResourceCustomization;
50 import org.openecomp.mso.db.catalog.beans.Service;
51 import org.openecomp.mso.db.catalog.beans.ServiceMacroHolder;
52 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
53 import org.openecomp.mso.db.catalog.beans.ServiceToAllottedResources;
54 import org.openecomp.mso.db.catalog.beans.ServiceToNetworks;
55 import org.openecomp.mso.db.catalog.beans.ServiceToResourceCustomization;
56 import org.openecomp.mso.db.catalog.beans.TempNetworkHeatTemplateLookup;
57 import org.openecomp.mso.db.catalog.beans.ToscaCsar;
58 import org.openecomp.mso.db.catalog.beans.VfModule;
59 import org.openecomp.mso.db.catalog.beans.VfModuleCustomization;
60 import org.openecomp.mso.db.catalog.beans.VfModuleToHeatFiles;
61 import org.openecomp.mso.db.catalog.beans.VnfComponent;
62 import org.openecomp.mso.db.catalog.beans.VnfComponentsRecipe;
63 import org.openecomp.mso.db.catalog.beans.VnfRecipe;
64 import org.openecomp.mso.db.catalog.beans.VnfResCustomToVfModuleCustom;
65 import org.openecomp.mso.db.catalog.beans.VnfResource;
66 import org.openecomp.mso.db.catalog.beans.VnfResourceCustomization;
67 import org.openecomp.mso.db.catalog.utils.MavenLikeVersioningComparator;
68 import org.openecomp.mso.db.catalog.utils.RecordNotFoundException;
69 import org.openecomp.mso.logger.MessageEnum;
70 import org.openecomp.mso.logger.MsoLogger;
71
72 /**
73  * This class encapsulates all of the objects that can be queried from a Catalog database.
74  * Clients must use these methods to retrieve catalog objects. The session is not
75  * available for clients to do their own direct queries to the database.
76  *
77  *
78  */
79 public class CatalogDatabase implements Closeable {
80
81     protected final AbstractSessionFactoryManager sessionFactoryCatalogDB;
82
83     private static final String NETWORK_TYPE = "networkType";
84     private static final String ACTION = "action";
85     private static final String VNF_TYPE = "vnfType";
86     private static final String SERVICE_TYPE = "serviceType";
87     private static final String MODEL_UUID= "modelUUID";
88     private static final String VNF_COMPONENT_TYPE = "vnfComponentType";
89     private static final String MODEL_ID = "modelId";
90     private static final String MODEL_NAME = "modelName";
91     private static final String MODEL_VERSION = "version";
92     private static final String TYPE = "type";
93     private static final String MODEL_TYPE = "modelType";
94     private static final String MODEL_VERSION_ID = "modelVersionId";
95     private static final String MODEL_CUSTOMIZATION_UUID = "modelCustomizationUuid";
96         private static final String VF_MODULE_MODEL_UUID = "vfModuleModelUUId";
97
98     protected static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL);
99
100     protected Session session = null;
101
102     protected CatalogDatabase (AbstractSessionFactoryManager sessionFactoryCatalog) {
103         sessionFactoryCatalogDB = sessionFactoryCatalog;
104     }
105     
106     public static CatalogDatabase getInstance() {
107         return new CatalogDatabase(new CatalogDbSessionFactoryManager ());
108     }
109     
110     private Session getSession () {
111
112              if (session == null) {
113             try {
114                 session = sessionFactoryCatalogDB.getSessionFactory ().openSession ();
115                 session.beginTransaction ();
116             } catch (HibernateException he) {
117                 LOGGER.error (MessageEnum.GENERAL_EXCEPTION_ARG, "Error creating Hibernate Session: " + he, "", "", MsoLogger.ErrorCode.DataError, "Error creating Hibernate Session: " + he);
118                 throw he;
119             }
120         }
121
122         return session;
123     }
124
125     /**
126      * Close an open Catalog Database session.
127      * This method should always be called when a client is finished using a
128      * CatalogDatabase instance.
129      */
130     @Override
131     public void close () {
132         if (session != null) {
133             session.close ();
134             session = null;
135         }
136     }
137
138     /**
139      * Commits the current transaction on this session and starts a fresh one.
140      */
141     public void commit () {
142         getSession ().getTransaction ().commit ();
143         getSession ().beginTransaction ();
144     }
145
146     /**
147      * Rolls back current transaction and starts a fresh one.
148      */
149     public void rollback () {
150         getSession ().getTransaction ().rollback ();
151         getSession ().beginTransaction ();
152     }
153
154     /**
155      * Return all Heat Templates in the Catalog DB
156      *
157      * @return A list of HeatTemplate objects
158      */
159     @SuppressWarnings("unchecked")
160     public List <HeatTemplate> getAllHeatTemplates() {
161         long startTime = System.currentTimeMillis();
162         LOGGER.debug("Catalog database - get all Heat templates");
163         String hql = "FROM HeatTemplate";
164         Query query = getSession().createQuery(hql);
165
166         List <HeatTemplate> result = query.list();
167         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllHeatTemplates", null);
168         return result;
169     }
170
171     /**
172      * Fetch a specific Heat Template by ID.
173      *
174      * @param templateId template id
175      * @return HeatTemplate object or null if none found
176      */
177     @Deprecated
178     public HeatTemplate getHeatTemplate(int templateId) {
179         long startTime = System.currentTimeMillis();
180         LOGGER.debug ("Catalog database - get Heat template with id " + templateId);
181
182         HeatTemplate template = (HeatTemplate) getSession().get(HeatTemplate.class, templateId);
183         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
184         return template;
185     }
186
187     /**
188      * Return the newest version of a specific Heat Template (queried by Name).
189      *
190      * @param templateName template name
191      * @return HeatTemplate object or null if none found
192      */
193     public HeatTemplate getHeatTemplate(String templateName) {
194
195         long startTime = System.currentTimeMillis();
196         LOGGER.debug("Catalog database - get Heat template with name " + templateName);
197
198         String hql = "FROM HeatTemplate WHERE templateName = :template_name";
199         Query query = getSession().createQuery (hql);
200         query.setParameter("template_name", templateName);
201
202         @SuppressWarnings("unchecked")
203         List <HeatTemplate> resultList = query.list();
204
205         // See if something came back. Name is unique, so
206         if (resultList.isEmpty ()) {
207             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No template found", "CatalogDB", "getHeatTemplate", null);
208             return null;
209         }
210         resultList.sort(new MavenLikeVersioningComparator());
211         Collections.reverse(resultList);
212
213         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
214         return resultList.get(0);
215     }
216
217     /**
218      * Return a specific version of a specific Heat Template (queried by Name).
219      *
220      * @param templateName
221      * @param version
222      * @return HeatTemplate object or null if none found
223      */
224     public HeatTemplate getHeatTemplate(String templateName, String version) {
225
226         long startTime = System.currentTimeMillis();
227         LOGGER.debug("Catalog database - get Heat template with name " + templateName
228                                       + " and version "
229                                       + version);
230
231         String hql = "FROM HeatTemplate WHERE templateName = :template_name AND version = :version";
232         Query query = getSession().createQuery(hql);
233         query.setParameter("template_name", templateName);
234         query.setParameter("version", version);
235
236         @SuppressWarnings("unchecked")
237         List <HeatTemplate> resultList = query.list();
238
239         // See if something came back.
240         if (resultList.isEmpty()) {
241             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No template found.", "CatalogDB", "getHeatTemplate", null);
242             return null;
243         }
244         // Name + Version is unique, so should only be one element
245         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
246         return resultList.get(0);
247     }
248
249     /**
250      * Return a specific Heat Template by ARTIFACT_UUID).
251      *
252      * @param artifactUuid
253      * @return HeatTemplate object or null if none found
254      */    
255     
256     public HeatTemplate getHeatTemplateByArtifactUuid(String artifactUuid) {
257         long startTime = System.currentTimeMillis ();
258         LOGGER.debug ("Catalog database - get Heat template with artifactUuid " + artifactUuid);
259
260         // Will this work if the id is a string? 
261         HeatTemplate template = (HeatTemplate) getSession ().get (HeatTemplate.class, artifactUuid);
262         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
263         return template;
264     }
265     
266     /**
267      * Return a specific Heat Template by ARTIFACT_UUID using standard query method. unique record expected.
268      *
269      * @param artifactUuid
270      * @return HeatTemplate object or null if none found
271      */
272     public HeatTemplate getHeatTemplateByArtifactUuidRegularQuery(String artifactUuid) {
273         long startTime = System.currentTimeMillis();
274         LOGGER.debug("Catalog database - get Heat template (regular query) with artifactUuid " + artifactUuid);
275
276         String hql = "FROM HeatTemplate WHERE artifactUuid = :artifactUuidValue";
277         HashMap<String, String> variables = new HashMap<>();
278         variables.put("artifactUuidValue", artifactUuid);
279         HeatTemplate template = (HeatTemplate) this.executeQuerySingleRow(hql, variables, true);
280
281         if (template == null) {
282             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getHeatTemplateByArtifactUuidRegularQuery", null);
283         } else {
284             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplateByArtifactUuidRegularQuery", null);
285         }
286         return template;
287     }
288     
289     public List<HeatTemplateParam> getParametersForHeatTemplate(String heatTemplateArtifactUuid) {
290         LOGGER.debug ("Catalog database - getParametersForHeatTemplate with artifactUuid " + heatTemplateArtifactUuid);
291
292         String hql = "FROM HeatTemplateParams WHERE artifactUuid = :artifactUuidValue";
293         Query query = getSession().createQuery(hql);
294         query.setParameter ("artifactUuidValue", heatTemplateArtifactUuid);
295         List<HeatTemplateParam> resultList = new ArrayList<>();
296         try {
297                 resultList = query.list ();
298         } catch (org.hibernate.HibernateException he) {
299                 LOGGER.debug("Hibernate Exception - while searching HeatTemplateParams for: heatTemplateArtifactUuid='" + heatTemplateArtifactUuid + "'" + he.getMessage());
300                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching HeatTemplateParams for artifactUuid=" + heatTemplateArtifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for artifactUuid=" + heatTemplateArtifactUuid);
301                 throw he;
302         } catch (Exception e) {
303                 LOGGER.debug("Generic Exception - while searching HeatTemplateParam for: artifactUuid='" + heatTemplateArtifactUuid + "'" + e.getMessage());
304                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching HeatTemplate for artifactUuid=" + heatTemplateArtifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for artifactUuid=" + heatTemplateArtifactUuid);
305                 throw e;
306         }
307         
308         return resultList;
309         
310     }
311     
312     /**
313      * Return a specific Heat Environment by ARTIFACT_UUID using standard query method. unique record expected.
314      *
315      * @param artifactUuid
316      * @return HeatEnvironment object or null if none found
317      */    
318     public HeatEnvironment getHeatEnvironmentByArtifactUuid(String artifactUuid) {
319         long startTime = System.currentTimeMillis();
320         LOGGER.debug("Catalog database - get Heat Environment with artifactUuid " + artifactUuid);
321
322         String hql = "FROM HeatEnvironment WHERE artifactUuid = :artifactUuidValue";
323         Query query = getSession().createQuery(hql);
324         query.setParameter("artifactUuidValue", artifactUuid);
325         HeatEnvironment environment = null;
326         try {
327             environment = (HeatEnvironment) query.uniqueResult();
328         } catch (org.hibernate.NonUniqueResultException nure) {
329                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row for Envt - data integrity error: artifactUuid='" + artifactUuid +"'", nure);
330                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for heatEnvironment artifactUuid=" + artifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for artifactUuid==" + artifactUuid);
331         } catch (org.hibernate.HibernateException he) {
332                 LOGGER.debug("Hibernate Exception - while searching for envt: artifactUuid='" + artifactUuid + "' " + he.getMessage());
333                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching envt for artifactUuid=" + artifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching envt for artifactUuid=" + artifactUuid);
334
335                 throw he;
336         } catch (Exception e) {
337                 LOGGER.debug("Generic Exception - while searching for: artifactUuid='" + artifactUuid + "' " + e.getMessage());
338                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching envt for artifactUuid=" + artifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching envt for artifactUuid=" + artifactUuid);
339
340                 throw e;
341         }
342
343         if (environment == null) {
344                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getHeatEnvironmentByArtifactUuid", null);
345         } else {
346                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatEnvironmentByArtifactUuid", null);
347         }
348         return environment;
349     }
350     
351     /**
352      * Fetch a Service definition by InvariantUUID
353      */
354     public Service getServiceByInvariantUUID (String modelInvariantUUID) {
355
356         long startTime = System.currentTimeMillis();
357         LOGGER.debug("Catalog database - get service with Invariant UUID " + modelInvariantUUID);
358
359         String hql = "FROM Service WHERE modelInvariantUUID = :model_invariant_uuid";
360         Query query = getSession().createQuery(hql);
361         query.setParameter ("model_invariant_uuid", modelInvariantUUID);
362
363         @SuppressWarnings("unchecked")
364         List <Service> resultList = query.list ();
365
366         // See if something came back.
367         if (resultList.isEmpty ()) {
368             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service not found", "CatalogDB", "getServiceByName", null);
369             return null;
370         }
371         resultList.sort(new MavenLikeVersioningComparator());
372         Collections.reverse (resultList);
373
374         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceByName", null);
375         return resultList.get (0);
376     }
377
378     /**
379      * Fetch a Service definition
380      */
381     public Service getService (String modelName) {
382
383         long startTime = System.currentTimeMillis();
384         LOGGER.debug("Catalog database - get service with name " + modelName);
385
386         String hql = "FROM Service WHERE modelName = :MODEL_NAME";
387         Query query = getSession().createQuery(hql);
388         query.setParameter("MODEL_NAME", modelName);
389
390         Service service = null;
391         try {
392                 service = (Service) query.uniqueResult();
393         } catch (org.hibernate.NonUniqueResultException nure) {
394                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelName='" + modelName + "'");
395                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelName=" + modelName, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelName=" + modelName);
396                 throw nure;
397         } catch (org.hibernate.HibernateException he) {
398                 LOGGER.debug("Hibernate Exception - while searching for: modelName='" + modelName + "' " + he.getMessage());
399                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelName=" + modelName, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelName=" + modelName);
400                 throw he;
401         } catch (Exception e) {
402                 LOGGER.debug("Generic Exception - while searching for: modelName='" + modelName + " " + e.getMessage());
403                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelName=" + modelName, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelName=" + modelName);
404                 throw e;
405         }
406         if (service == null) {
407                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
408         } else {
409                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
410         }
411
412         return service;
413     }
414
415     public Service getServiceByModelUUID (String modelUUID) {
416
417         long startTime = System.currentTimeMillis();
418         LOGGER.debug("Catalog database - get service with Model UUID " + modelUUID);
419
420         String hql = "FROM Service WHERE modelUUID = :MODEL_UUID";
421         HashMap<String, String> parameters = new HashMap<>();
422         parameters.put("MODEL_UUID", modelUUID);
423
424         
425         Service service = this.executeQuerySingleRow(hql, parameters, true);
426
427         /*
428         try {
429                 service = (Service) query.uniqueResult ();
430         } catch (org.hibernate.NonUniqueResultException nure) {
431                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelUUID='" + modelUUID + "'");
432                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelUUID=" + modelUUID, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelUUID=" + modelUUID);
433                 throw nure;
434         } catch (org.hibernate.HibernateException he) {
435                 LOGGER.debug("Hibernate Exception - while searching for: modelUUID='" + modelUUID + "' " + he.getMessage());
436                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelUUID=" + modelUUID, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelUUID=" + modelUUID);
437                 throw he;
438         } catch (Exception e) {
439                 LOGGER.debug("Generic Exception - while searching for: modelUUID='" + modelUUID + " " + e.getMessage());
440                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelUUID=" + modelUUID, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelUUID=" + modelUUID);
441                 throw e;
442         }
443         */
444         if (service == null) {
445                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getServiceByModelUUID", null);
446         } else {
447                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceByModelUUID", null);
448         }
449
450         return service;
451     }
452
453     /**
454      * Fetch the Common Service API definition using Http Method + serviceNameVersionId
455      */
456     public Service getService(Map<String, String> map, String httpMethod) {
457
458         String serviceNameVersionId = map.get("serviceNameVersionId");
459         Query query;
460         String serviceId = "not_set";
461         String serviceVersion = "not_set";
462
463         if(serviceNameVersionId != null && serviceNameVersionId.length() > 0){
464                 LOGGER.debug ("Catalog database - get service modelUUID with id " + serviceNameVersionId);
465
466                 String hql = "FROM Service WHERE MODEL_UUID = :MODEL_UUID and http_method = :http_method";
467                 query = getSession().createQuery(hql);
468             query.setParameter("MODEL_UUID", serviceNameVersionId);
469          } else {
470                 serviceId = map.get("serviceId");
471                 serviceVersion = map.get("serviceVersion");
472             LOGGER.debug("Catalog database - get serviceId with id " + serviceId + " and serviceVersion with " + serviceVersion);
473
474             String hql = "FROM Service WHERE service_id = :service_id and service_version = :service_version and http_method = :http_method";
475             query = getSession().createQuery(hql);
476             query.setParameter("service_id", serviceId);
477             query.setParameter("service_version", serviceVersion);
478          }
479
480         query.setParameter("http_method", httpMethod);
481
482         long startTime = System.currentTimeMillis();
483         Service service = null;
484         try {
485                 service = (Service) query.uniqueResult();
486         } catch (org.hibernate.NonUniqueResultException nure) {
487                 LOGGER.debug("Non Unique Result Exception - data integrity error: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "'");
488                 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);
489
490                 throw nure;
491         } catch (org.hibernate.HibernateException he) {
492                 LOGGER.debug("Hibernate Exception - while searching for: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "' " + he.getMessage());
493                 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);
494
495                 throw he;
496         } catch (Exception e) {
497                 LOGGER.debug("Generic Exception - while searching for: service_id='" + serviceId + "', serviceVersion='" + serviceVersion + "' " + e.getMessage());
498                 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);
499
500                 throw e;
501         }
502         if (service == null) {
503                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
504         } else {
505                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
506         }
507         return service;
508     }
509
510     /**
511      * Return the newest version of a Service (queried by Name).
512      *
513      * @param modelName
514      * @return Service object or null if none found
515      */
516     public Service getServiceByModelName(String modelName){
517
518         long startTime = System.currentTimeMillis();
519         LOGGER.debug("Catalog database - get service with name " + modelName);
520
521         String hql = "FROM Service WHERE modelName = :MODEL_NAME";
522         Query query = getSession().createQuery(hql);
523         query.setParameter("MODEL_NAME", modelName);
524
525         @SuppressWarnings("unchecked")
526         List <Service> resultList = query.list();
527
528         // See if something came back.
529         if (resultList.isEmpty()) {
530             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service not found", "CatalogDB", "getServiceByModelName", null);
531             return null;
532         }
533         resultList.sort(new MavenLikeVersioningComparator());
534         Collections.reverse(resultList);
535
536         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceByModelName", null);
537         return resultList.get(0);
538     }
539
540     public Service getServiceByVersionAndInvariantId(String modelInvariantId, String modelVersion) throws Exception {
541         long startTime = System.currentTimeMillis();
542         LOGGER.debug("Catalog database - get service with modelInvariantId: " + modelInvariantId + " and modelVersion: " + modelVersion);
543
544         String hql = "FROM Service WHERE modelInvariantUUID = :MODEL_INVARIANT_UUID AND version = :VERSION_STR";
545         Query query = getSession().createQuery(hql);
546         query.setParameter("MODEL_INVARIANT_UUID", modelInvariantId);
547         query.setParameter("VERSION_STR", modelVersion);
548
549         Service result = null;
550         try {
551             result = (Service) query.uniqueResult();
552         } catch (org.hibernate.NonUniqueResultException nure) {
553             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelInvariantId='" + modelInvariantId + "', modelVersion='" + modelVersion + "'", nure);
554             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelInvariantId=" + modelInvariantId + " and modelVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelInvariantId=" + modelInvariantId);
555             throw new Exception("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelInvariantId='" + modelInvariantId + "', modelVersion='" + modelVersion + "'");
556         }
557         // See if something came back.
558         if (result==null) {
559             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service not found", "CatalogDB", "getServiceByVersionAndInvariantId", null);
560             return null;
561         }
562
563         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceByVersionAndInvariantId", null);
564         return result;
565     }
566
567     /**
568      * Return a newest version of Service recipe that matches a given SERVICE_ID and ACTION
569      *
570      * @param serviceModelUUID
571      * @param action     * 
572      * @return ServiceRecipe object or null if none found
573      */
574     @Deprecated
575     public ServiceRecipe getServiceRecipe (int serviceModelUUID, String action) {
576        
577         StringBuilder hql;
578
579         if(action == null){
580                 hql = new StringBuilder ("FROM ServiceRecipe WHERE serviceModelUUID = :serviceModelUUID");
581         }else {
582                 hql = new StringBuilder ("FROM ServiceRecipe WHERE serviceModelUUID = :serviceModelUUID AND action = :action ");
583         }
584
585         long startTime = System.currentTimeMillis ();
586         LOGGER.debug ("Catalog database - get Service recipe with serviceModelUUID " + Integer.toString(serviceModelUUID)
587                                       + " and action "
588                                       + action
589                                       );
590
591         Query query = getSession ().createQuery (hql.toString ());
592         query.setParameter ("serviceModelUUID", serviceModelUUID);
593         if(action != null){
594                 query.setParameter (ACTION, action);
595         }
596
597                         @SuppressWarnings("unchecked")
598         List <ServiceRecipe> resultList = query.list ();
599
600         if (resultList.isEmpty ()) {
601             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service recipe not found", "CatalogDB", "getServiceRecipe", null);
602                                 return null;
603                         }
604
605         resultList.sort(new MavenLikeVersioningComparator());
606         Collections.reverse (resultList);
607
608         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipe", null);
609         return resultList.get (0);
610     }
611
612     /**
613      * Return a newest version of Service recipe that matches a given SERVICE_MODEL_UUID and ACTION
614      *
615      * @param serviceModelUuid
616      * @param action     *
617      * @return ServiceRecipe object or null if none found
618      */
619     public ServiceRecipe getServiceRecipeByServiceModelUuid(String serviceModelUuid, String action) {
620
621         StringBuilder hql;
622
623         if(action == null){
624             hql = new StringBuilder("FROM ServiceRecipe WHERE serviceModelUuid = :serviceModelUuid");
625         }else {
626             hql = new StringBuilder("FROM ServiceRecipe WHERE serviceModelUuid = :serviceModelUuid AND action = :action ");
627         }
628
629         long startTime = System.currentTimeMillis ();
630         LOGGER.debug("Catalog database - get Service recipe with serviceModelUuid " + serviceModelUuid
631                                       + " and action "
632                                       + action
633                                       );
634
635         Query query = getSession().createQuery(hql.toString());
636         query.setParameter("serviceModelUuid", serviceModelUuid);
637         if(action != null){
638             query.setParameter(ACTION, action);
639         }
640
641         @SuppressWarnings("unchecked")
642         List <ServiceRecipe> resultList = query.list();
643
644         if (resultList.isEmpty()) {
645             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service recipe not found", "CatalogDB", "getServiceRecipe", null);
646             return null;
647         }
648
649         resultList.sort(new MavenLikeVersioningComparator());
650         Collections.reverse(resultList);
651
652         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipe", null);
653         return resultList.get(0);
654     }
655
656     public List<ServiceRecipe> getServiceRecipes(String serviceModelUuid) {
657
658         StringBuilder hql;
659
660         hql = new StringBuilder("FROM ServiceRecipe WHERE serviceModelUUID = :serviceModelUUID");
661
662         long startTime = System.currentTimeMillis();
663         LOGGER.debug("Catalog database - get Service recipe with serviceModelUUID " + serviceModelUuid);
664
665         Query query = getSession().createQuery(hql.toString());
666         query.setParameter("serviceModelUUID", serviceModelUuid);
667
668         @SuppressWarnings("unchecked")
669         List <ServiceRecipe> resultList = query.list();
670
671         if (resultList.isEmpty()) {
672             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service recipe not found", "CatalogDB", "getServiceRecipes", null);
673             return Collections.EMPTY_LIST;
674         }
675
676         resultList.sort(new MavenLikeVersioningComparator());
677         Collections.reverse(resultList);
678
679         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipes", null);
680         return resultList;
681     }
682
683     
684     /**
685      * Return the VNF component data - queried by the VNFs ID and the component type.
686      *
687      * @param vnfId
688      * @param type
689      * @return VnfComponent object or null if none found
690      */
691     @Deprecated
692     public VnfComponent getVnfComponent (int vnfId, String type) {
693
694         long startTime = System.currentTimeMillis();
695         LOGGER.debug ("Catalog database - get VnfComponent where vnfId="+ vnfId+ " AND componentType="+ type);
696
697         String hql = "FROM VnfComponent WHERE vnfId = :vnf_id AND componentType = :type";
698         Query query = getSession ().createQuery (hql);
699         query.setParameter ("vnf_id", vnfId);
700         query.setParameter ("type", type);
701
702         VnfComponent result = null;
703         try {
704                 result = (VnfComponent) query.uniqueResult();
705         } catch (org.hibernate.NonUniqueResultException nure) {
706                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnf_id='" + vnfId + "', componentType='" + type + "'");
707                 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);
708
709                 throw nure;
710         } catch (org.hibernate.HibernateException he) {
711                 LOGGER.debug("Hibernate Exception - while searching for: vnf_id='" + vnfId + "', componentType='" + type + "' " + he.getMessage());
712                 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);
713
714                 throw he;
715         } catch (Exception e) {
716                 LOGGER.debug("Generic Exception - while searching for: vnf_id='" + vnfId + "', componentType='" + type + "' " + e.getMessage());
717                 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);
718
719                 throw e;
720         }
721
722         if (result != null) {
723             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponent", null);
724         } else {
725             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No VNFComponent found", "CatalogDB", "getVnfComponent", null);
726         }
727         return result;
728     }
729
730     /**
731      * Return the newest version of a specific VNF resource (queried by Name).
732      *
733      * @param vnfType
734      * @return VnfResource object or null if none found
735      */
736     public VnfResource getVnfResource (String vnfType) {
737
738         long startTime = System.currentTimeMillis();
739         LOGGER.debug("Catalog database - get vnf resource with model_name " + vnfType);
740
741         String hql = "FROM VnfResource WHERE modelName = :vnf_name";
742         Query query = getSession().createQuery(hql);
743         query.setParameter("vnf_name", vnfType);
744
745         @SuppressWarnings("unchecked")
746         List <VnfResource> resultList = query.list();
747
748         // See if something came back. Name is unique, so
749         if (resultList.isEmpty()) {
750             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF not found", "CatalogDB", "getVnfResource", null);
751             return null;
752         }
753         resultList.sort(new MavenLikeVersioningComparator());
754         Collections.reverse(resultList);
755
756         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResource", null);
757         return resultList.get(0);
758     }
759
760     /**
761      * Return the newest version of a specific VNF resource (queried by Name).
762      *
763      * @param vnfType
764      * @param serviceVersion
765      * @return VnfResource object or null if none found
766      */
767     public VnfResource getVnfResource (String vnfType, String serviceVersion) {
768
769         long startTime = System.currentTimeMillis();
770         LOGGER.debug("Catalog database - get VNF resource with model_name " + vnfType + " and version=" + serviceVersion);
771
772         String hql = "FROM VnfResource WHERE modelName = :vnfName and version = :serviceVersion";
773         Query query = getSession().createQuery(hql);
774         query.setParameter("vnfName", vnfType);
775         query.setParameter("serviceVersion", serviceVersion);
776
777         VnfResource resource = null;
778         try {
779                 resource = (VnfResource) query.uniqueResult();
780         } catch (org.hibernate.NonUniqueResultException nure) {
781                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnfType='" + vnfType + "', serviceVersion='" + serviceVersion + "'");
782                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnfType=" + vnfType);
783
784                 throw nure;
785         } catch (org.hibernate.HibernateException he) {
786                 LOGGER.debug("Hibernate Exception - while searching for: vnfType='" + vnfType + "', asdc_service_model_version='" + serviceVersion + "' " + he.getMessage());
787                 LOGGER.debug(Arrays.toString(he.getStackTrace()));
788                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfType=" + vnfType);
789
790                 throw he;
791         } catch (Exception e) {
792                 LOGGER.debug("Generic Exception - while searching for: vnfType='" + vnfType + "', serviceVersion='" + serviceVersion + "' " + e.getMessage());
793                 LOGGER.debug(Arrays.toString(e.getStackTrace()));
794                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for vnfType=" + vnfType + " and serviceVersion=" + serviceVersion, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for vnfType=" + vnfType);
795
796                 throw e;
797         }
798         if (resource == null) {
799                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResource", null);
800         } else {
801                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResource", null);
802         }
803         return resource;
804     }
805
806     /**
807      * Return VnfResource (queried by modelCustomizationId).
808      *
809      * @param modelCustomizationId
810      * @return VnfResource object or null if none found
811      */
812     public VnfResource getVnfResourceByModelCustomizationId(String modelCustomizationId) {
813
814         long startTime = System.currentTimeMillis();
815         LOGGER.debug("Catalog database - get VNF resource with modelCustomizationId " + modelCustomizationId);
816
817         String hql = "SELECT vr "
818                                         + "FROM VnfResource as vr JOIN vr.vnfResourceCustomizations as vrc "
819                                         + "WHERE vrc.modelCustomizationUuid = :modelCustomizationId";
820                 
821         Query query = getSession().createQuery(hql);
822         query.setParameter("modelCustomizationId", modelCustomizationId);
823
824         VnfResource resource = null;
825         try {
826             resource = (VnfResource) query.uniqueResult();
827         } catch(org.hibernate.NonUniqueResultException nure) {
828                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelCustomizationUuid='" + modelCustomizationId + "'");
829                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelCustomizationUuid=" + modelCustomizationId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelCustomizationId=" + modelCustomizationId);
830
831                 throw nure;
832         } catch (org.hibernate.HibernateException he) {
833                 LOGGER.debug("Hibernate Exception - while searching for: modelCustomizationId='" + modelCustomizationId + "' " + he.getMessage());
834                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelCustomizationId=" + modelCustomizationId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationId=" + modelCustomizationId);
835
836                 throw he;
837         } catch (Exception e) {
838                 LOGGER.debug("Generic Exception - while searching for: modelCustomizationId='" + modelCustomizationId + "' " + e.getMessage());
839                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelCustomizationId=" + modelCustomizationId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelCustomizationId=" + modelCustomizationId);
840
841                 throw e;
842         }
843         if (resource == null) {
844             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResourceByModelCustomizationId", null);
845         } else {
846             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceByModelCustomizationId", null);
847         }
848         return resource;
849     }
850     
851     
852     /**
853      * Return the newest version of a specific VNF resource Customization (queried by modelCustomizationName and modelVersionId).
854      *
855      * @return {@link VnfResourceCustomization} object or null if none found
856      */
857     public VnfResourceCustomization getVnfResourceCustomizationByModelCustomizationName (String modelCustomizationName, String modelVersionId) {
858
859         long startTime = System.currentTimeMillis();
860         LOGGER.debug("Catalog database - get VNF resource Customization with modelCustomizationName " + modelCustomizationName + " serviceModelUUID " + modelVersionId);
861
862         String hql = "SELECT vrc FROM VnfResourceCustomization as vrc WHERE vrc.modelCustomizationUuid IN "
863                                         + "(SELECT src.resourceModelCustomizationUUID FROM ServiceToResourceCustomization src "
864                                         + "WHERE src.serviceModelUUID = :modelVersionId)"
865                                         + "AND vrc.modelInstanceName = :modelCustomizationName";
866                 
867         Query query = getSession().createQuery(hql);
868         query.setParameter("modelCustomizationName", modelCustomizationName);
869         query.setParameter("modelVersionId", modelVersionId);
870
871         @SuppressWarnings("unchecked")
872         List<VnfResourceCustomization> resultList = query.list();
873
874         if (resultList.isEmpty()) {
875             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VnfResourceCustomization not found", "CatalogDB", "getVnfResourceCustomizationByModelCustomizationName", null);
876             return null;
877         }
878         
879         resultList.sort(new MavenLikeVersioningComparator());
880         Collections.reverse(resultList);
881
882         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationByModelCustomizationName", null);
883         return resultList.get(0);
884     }
885     
886     
887     /**
888      * Return the newest version of a specific VNF resource (queried by modelInvariantId).
889      *
890      * @param modelInvariantUuid model invariant ID
891      * @param modelVersion model version
892      * @return VnfResource object or null if none found
893      */
894     public VnfResource getVnfResourceByModelInvariantId(String modelInvariantUuid, String modelVersion) {
895
896         long startTime = System.currentTimeMillis();
897         LOGGER.debug("Catalog database - get VNF resource with modelInvariantUuid " + modelInvariantUuid);
898
899         String hql = "FROM VnfResource WHERE modelInvariantUuid = :modelInvariantUuid and version = :serviceVersion";
900         Query query = getSession().createQuery(hql);
901         query.setParameter("modelInvariantUuid", modelInvariantUuid);
902         query.setParameter("serviceVersion", modelVersion);
903
904         VnfResource resource = null;
905         try {
906                 resource = (VnfResource) query.uniqueResult();
907         } catch (org.hibernate.NonUniqueResultException nure) {
908                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelInvariantUuid='" + modelInvariantUuid + "', serviceVersion='" + modelVersion + "'");
909                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelInvariantUuid=" + modelInvariantUuid + " and serviceVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelInvariantUuid=" + modelInvariantUuid);
910
911                 throw nure;
912         } catch (org.hibernate.HibernateException he) {
913                 LOGGER.debug("Hibernate Exception - while searching for: modelInvariantUuid='" + modelInvariantUuid + "', asdc_service_model_version='" + modelVersion + "' " + he.getMessage());
914                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelInvariantUuid=" + modelInvariantUuid + " and serviceVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelInvariantUuid=" + modelInvariantUuid);
915
916                 throw he;
917         } catch (Exception e) {
918                 LOGGER.debug("Generic Exception - while searching for: modelInvariantUuid='" + modelInvariantUuid + "', serviceVersion='" + modelVersion + "' " + e.getMessage());
919                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelInvariantUuid=" + modelInvariantUuid + " and serviceVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelInvariantUuid=" + modelInvariantUuid);
920
921                 throw e;
922         }
923         if (resource == null) {
924             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResource", null);
925         } else {
926             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResource", null);
927         }
928         return resource;
929     }
930
931     /**
932      * Return the newest version of a specific VNF resource (queried by ID).
933      *
934      * @param id The vnf id
935      * @return VnfResource object or null if none found
936      */
937     @Deprecated
938     public VnfResource getVnfResourceById (int id) {
939
940         long startTime = System.currentTimeMillis ();
941         LOGGER.debug ("Catalog database - get VNF resource with id " + id);
942
943         String hql = "FROM VnfResource WHERE id = :id";
944         Query query = getSession ().createQuery (hql);
945         query.setParameter ("id", id);
946
947         @SuppressWarnings("unchecked")
948         List <VnfResource> resultList = query.list ();
949
950         // See if something came back. Name is unique, so
951         if (resultList.isEmpty ()) {
952             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VnfResource not found", "CatalogDB", "getVnfResourceById", null);
953             return null;
954         }
955         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceById", null);
956         return resultList.get (0);
957     }
958
959     /**
960      * Return the newest version of a vfModule - 1607
961      *
962      */
963     public VfModule getVfModuleModelName(String modelName) {
964
965         long startTime = System.currentTimeMillis();
966         LOGGER.debug("Catalog database - get vfModuleModelName with name " + modelName);
967
968         String hql = "FROM VfModule WHERE modelName = :model_name";
969         Query query = getSession().createQuery(hql);
970         query.setParameter("model_name", modelName);
971
972         @SuppressWarnings("unchecked")
973         List<VfModule> resultList = query.list();
974
975         // See if something came back. Name is unique, so
976         if (resultList.isEmpty()) {
977             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleModelName", null);
978             return null;
979         }
980         resultList.sort(new MavenLikeVersioningComparator());
981         Collections.reverse(resultList);
982
983         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null);
984         return resultList.get(0);
985     }
986
987     public VfModule getVfModuleModelName(String modelName, String model_version) {
988
989         long startTime = System.currentTimeMillis();
990         LOGGER.debug("Catalog database - get vfModuleModelName with type='" + modelName + "' and asdc_service_model_version='" + model_version + "'");
991
992         String hql = "FROM VfModule WHERE Name = :model_name and version = :model_version";
993         Query query = getSession().createQuery(hql);
994         query.setParameter("modelName", modelName);
995         query.setParameter("model_version", model_version);
996
997         VfModule module = null;
998         try {
999             module = (VfModule) query.uniqueResult();
1000         } catch (org.hibernate.NonUniqueResultException nure) {
1001                 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 + "'");
1002                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for type=" + modelName);
1003
1004                 throw nure;
1005         } catch (org.hibernate.HibernateException he) {
1006                 LOGGER.debug("Hibernate Exception - while searching for: type='" + modelName + "', asdc_service_model_version='" + model_version + "' " + he.getMessage());
1007                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for type=" + modelName);
1008
1009                 throw he;
1010         } catch (Exception e) {
1011                 LOGGER.debug("Generic Exception - while searching for: type='" + modelName + "', asdc_service_model_version='" + model_version + "' " + e.getMessage());
1012                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for type=" + modelName);
1013
1014                 throw e;
1015         }
1016         if (module == null) {
1017             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleModelName", null);
1018         } else {
1019             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null);
1020         }
1021         return module;
1022     }
1023     
1024     /**
1025      * Need this for 1707 DHV. This may be a temporary solution. May
1026      * change it to get resources using service's model name.
1027      * 
1028      *@author cb645j
1029      *
1030      */
1031     public VfModuleCustomization getVfModuleCustomizationByModelName(String modelName) {
1032
1033         long startTime = System.currentTimeMillis();
1034         LOGGER.debug("Catalog database - get VfModuleCustomization By VfModule's ModelName: " + modelName);
1035
1036         String hql = "SELECT VfModuleCustomization FROM VfModuleCustomization as vfmc LEFT OUTER JOIN VfModule as vfm on vfm.modelUUID = vfmc.vfModuleModelUuid where vfm.modelName = :model_name";
1037         Query query = getSession().createQuery(hql);
1038         query.setParameter("model_name", modelName);
1039
1040         @SuppressWarnings("unchecked")
1041         List<VfModuleCustomization> resultList = query.list();
1042
1043         // See if something came back. Name is unique, so
1044         if (resultList.isEmpty()) {
1045             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful query but Vf module NOT found", "CatalogDB", "getVfModuleCustomizationByModelName", null);
1046             return null;
1047         }
1048
1049         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful query ", "CatalogDB", "getVfModuleCustomizationByModelName", null);
1050         return resultList.get(0);
1051     }
1052
1053
1054     /**
1055      * Return the newest version of a specific Network resource (queried by Type).
1056      *
1057      * @param networkType
1058      * @return NetworkResource object or null if none found
1059      */
1060     public NetworkResource getNetworkResource(String networkType) {
1061
1062         long startTime = System.currentTimeMillis();
1063         LOGGER.debug("Catalog database - get network resource with type " + networkType);
1064
1065         String hql = "FROM NetworkResource WHERE model_name = :network_type";
1066         Query query = getSession().createQuery(hql);
1067         query.setParameter("network_type", networkType);
1068
1069         @SuppressWarnings("unchecked")
1070         List <NetworkResource> resultList = query.list();
1071
1072         // See if something came back. Name is unique, so
1073         if (resultList.isEmpty()) {
1074             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Network Resource not found", "CatalogDB", "getNetworkResource", null);
1075             return null;
1076         }
1077
1078         resultList.sort(new MavenLikeVersioningComparator());
1079         Collections.reverse(resultList);
1080         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResource", null);
1081         return resultList.get(0);
1082     }
1083
1084     /**
1085      * Return a VNF recipe that matches a given VNF_TYPE, ACTION, and, if specified, SERVICE_TYPE
1086      *
1087      * @param vnfType
1088      * @param action
1089      * @param serviceType The service Name, if null or empty is provided, it won't be taken into account
1090      * @return VnfRecipe object or null if none found
1091      */
1092     public VnfRecipe getVnfRecipe(String vnfType, String action, String serviceType) {
1093         boolean withServiceType = false;
1094
1095         StringBuilder hql = new StringBuilder("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action ");
1096
1097         // If query c
1098         if (serviceType == null || serviceType.isEmpty()) {
1099             hql.append("AND serviceType is NULL ");
1100         } else {
1101             hql.append("AND serviceType = :serviceType ");
1102             withServiceType = true;
1103         }
1104
1105         long startTime = System.currentTimeMillis();
1106         LOGGER.debug("Catalog database - get VNF recipe with name " + vnfType
1107                                       + " and action "
1108                                       + action
1109                                       + " and service type "
1110                                       + serviceType);
1111
1112         Query query = getSession().createQuery(hql.toString());
1113         query.setParameter(VNF_TYPE, vnfType);
1114         query.setParameter(ACTION, action);
1115         if (withServiceType) {
1116             query.setParameter(SERVICE_TYPE, serviceType);
1117         }
1118
1119         @SuppressWarnings("unchecked")
1120         List <VnfRecipe> resultList = query.list();
1121
1122         if (resultList.isEmpty()) {
1123             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null);
1124             return null;
1125         }
1126
1127         resultList.sort(new MavenLikeVersioningComparator());
1128         Collections.reverse(resultList);
1129
1130         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null);
1131         return resultList.get(0);
1132     }
1133
1134     
1135     
1136     /**
1137      * Return a VNF recipe that matches a given VNF_TYPE and ACTION
1138      *
1139      * @param vnfType
1140      * @param action
1141      * @return VnfRecipe object or null if none found
1142      */
1143     public VnfRecipe getVnfRecipe(String vnfType, String action) {
1144
1145         long startTime = System.currentTimeMillis();
1146         LOGGER.debug("Catalog database - get VNF recipe with name " + vnfType
1147                                       + " and action "
1148                                       + action);
1149
1150         Query query = getSession().createQuery("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action ");
1151         query.setParameter(VNF_TYPE, vnfType);
1152         query.setParameter(ACTION, action);
1153
1154         @SuppressWarnings("unchecked")
1155         List <VnfRecipe> resultList = query.list();
1156
1157         if (resultList.isEmpty()) {
1158             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null);
1159             return null;
1160         }
1161
1162         resultList.sort(new MavenLikeVersioningComparator());
1163         Collections.reverse(resultList);
1164
1165         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null);
1166         return resultList.get(0);
1167     }
1168     
1169     /**
1170      * Return a VNF recipe that matches a given ModelName and Modelversion and ACTION
1171      *
1172      * @param modelName
1173      * @param modelVersion
1174      * @param action
1175      * @return VnfRecipe object or null if none found
1176      */
1177     public VnfRecipe getVnfRecipeByNameVersion(String modelName, String modelVersion, String action) {
1178         StringBuilder hql = new StringBuilder("FROM VnfRecipe WHERE vnfType = :vnfType AND version= :version AND action = :action ");
1179
1180         long startTime = System.currentTimeMillis();
1181         LOGGER.debug("Catalog database - get VNF recipe with name " + modelName
1182                                       + " and action "
1183                                       + action);
1184
1185         Query query = getSession().createQuery(hql.toString());
1186         query.setParameter(VNF_TYPE, modelName);
1187         query.setParameter(MODEL_VERSION, modelVersion);
1188         query.setParameter(ACTION, action);
1189
1190         @SuppressWarnings("unchecked")
1191         List <VnfRecipe> resultList = query.list();
1192
1193         if (resultList.isEmpty()) {
1194             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null);
1195             return null;
1196         }
1197
1198         resultList.sort(new MavenLikeVersioningComparator());
1199         Collections.reverse(resultList);
1200
1201         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null);
1202         return resultList.get(0);
1203     }
1204     
1205     /**
1206      * Return a Network recipe that matches a given MODEL_UUID and ACTION
1207      *
1208      * @param modelName
1209      * @param action
1210      * @return NetworkRecipe object or null if none found
1211      */
1212     public VnfRecipe getVnfRecipeByModuleUuid (String vnfModelUuid, String action) {
1213         LOGGER.debug ("Catalog database - get vnf recipe with vnf resource model uuid " + vnfModelUuid
1214                 + " and action "
1215                 + action
1216                 );
1217         VnfResource vnfResource = getVnfResourceByModelUuid(vnfModelUuid);
1218         if(null == vnfResource){
1219             return null;
1220         }
1221         
1222         VnfRecipe recipe = this.getVnfRecipeByNameVersion(vnfResource.getModelName(), vnfResource.getModelVersion(), action);
1223         return recipe;        
1224     }
1225
1226     /**
1227      * Return a VNF recipe that matches a given VF_MODULE_ID and ACTION
1228      *
1229      * @param vfModuleId
1230      * @param action
1231      * @return VnfRecipe object or null if none found
1232      */
1233     public VnfRecipe getVnfRecipeByVfModuleId(String vnfType, String vfModuleId, String action) {
1234
1235         long startTime = System.currentTimeMillis();
1236         LOGGER.debug("Catalog database - get VNF Recipe with vfModuleId " + vfModuleId);
1237
1238         Query query = getSession().createQuery("FROM VnfRecipe WHERE vfModuleId = :vfModuleId and action = :action  ");
1239         query.setParameter(VF_MODULE_MODEL_UUID, vfModuleId);
1240         query.setParameter(ACTION, action);
1241
1242         @SuppressWarnings("unchecked")
1243         List <VnfRecipe> resultList = query.list();
1244
1245         if (resultList.isEmpty()) {
1246             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe Entry not found", "CatalogDB", "getVnfRecipeByVfModuleId", null);
1247             return null;
1248         }
1249
1250         resultList.sort(new MavenLikeVersioningComparator());
1251         Collections.reverse(resultList);
1252
1253         LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF Recipe Entry found", "CatalogDB", "getVnfRecipeByVfModuleId", null);
1254         return resultList.get(0);
1255     }
1256
1257     public VfModule getVfModuleTypeByUuid(String modelCustomizationUuid) {
1258         long startTime = System.currentTimeMillis();
1259         LOGGER.debug("Catalog database - get vfModuleTypeByUuid with uuid=" + modelCustomizationUuid);
1260
1261         String hql = "FROM VfModule WHERE modelCustomizationUuid = :modelCustomizationUuid";
1262         Query query = getSession().createQuery(hql);
1263         query.setParameter("modelCustomizationUuid", modelCustomizationUuid);
1264
1265         VfModule module = null;
1266         try {
1267             module = (VfModule) query.uniqueResult();
1268         } catch (org.hibernate.NonUniqueResultException nure) {
1269             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelCustomizationUuid='" + modelCustomizationUuid + "'");
1270             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelCustomizationUuid==" + modelCustomizationUuid);
1271
1272                 throw nure;
1273         } catch (org.hibernate.HibernateException he) {
1274                 LOGGER.debug("Hibernate Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + he.getMessage());
1275             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1276
1277                 throw he;
1278         } catch (Exception e) {
1279                 LOGGER.debug("Generic Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + e.getMessage());
1280             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1281
1282                 throw e;
1283         }
1284         if (module == null) {
1285             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleTypeByUuid", null);
1286         } else {
1287             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleTypeByUuid", null);
1288         }
1289         return module;
1290     }
1291
1292     @Deprecated
1293     public VfModule getVfModuleType(String type) {
1294         long startTime = System.currentTimeMillis();
1295         LOGGER.debug("Catalog database - get vfModuleType with type " + type);
1296
1297         String hql = "FROM VfModule WHERE type = :type";
1298         Query query = getSession().createQuery(hql);
1299         query.setParameter("type",  type);
1300
1301         @SuppressWarnings("unchecked")
1302         List<VfModule> resultList = query.list();
1303         if (resultList.isEmpty()) {
1304             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleType", null);
1305             return null;
1306         }
1307         resultList.sort(new MavenLikeVersioningComparator());
1308         Collections.reverse (resultList);
1309
1310         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
1311         return resultList.get (0);
1312     }
1313
1314     @Deprecated
1315     public VfModule getVfModuleType(String type, String version) {
1316
1317         long startTime = System.currentTimeMillis();
1318         LOGGER.debug ("Catalog database - get vfModuleType with type " + type + " and model_version " + version);
1319
1320         String hql = "FROM VfModule WHERE type = :type and version = :version";
1321         Query query = getSession().createQuery(hql);
1322         query.setParameter ("type", type);
1323         query.setParameter ("version", version);
1324         VfModule module = null;
1325         try {
1326                 module = (VfModule) query.uniqueResult ();
1327         } catch (org.hibernate.NonUniqueResultException nure) {
1328                 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 + "'");
1329                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for type==" + type);
1330
1331                 throw nure;
1332         } catch (org.hibernate.HibernateException he) {
1333                 LOGGER.debug("Hibernate Exception - while searching for: type='" + type + "', asdc_service_model_version='" + version + "' " + he.getMessage());
1334                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for type=" + type);
1335
1336                 throw he;
1337         } catch (Exception e) {
1338                 LOGGER.debug("Generic Exception - while searching for: type='" + type + "', asdc_service_model_version='" + version + "' " + e.getMessage());
1339                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for type=" + type + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for type=" + type);
1340
1341                 throw e;
1342         }
1343         if (module == null) {
1344                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null);
1345         } else {
1346                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
1347         }
1348         return module;
1349     }
1350
1351     public VnfResource getVnfResourceByServiceUuid(String serviceModelInvariantUuid) {
1352         long startTime = System.currentTimeMillis();
1353         LOGGER.debug ("Catalog database - get vfModuleType with serviceModelInvariantUuid " + serviceModelInvariantUuid);
1354
1355         String hql = "FROM VnfResource WHERE serviceModelInvariantUuid = :serviceModelInvariantUuid";
1356         Query query = getSession().createQuery(hql);
1357         query.setParameter ("serviceModelInvariantUuid", serviceModelInvariantUuid);
1358         VnfResource vnfResource = null;
1359         try {
1360             vnfResource = (VnfResource) query.uniqueResult();
1361         } catch (org.hibernate.NonUniqueResultException nure) {
1362             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: serviceModelInvariantUuid='" + serviceModelInvariantUuid);
1363             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for serviceModelInvariantUuid==" + serviceModelInvariantUuid);
1364
1365                 throw nure;
1366         } catch (org.hibernate.HibernateException he) {
1367                 LOGGER.debug("Hibernate Exception - while searching for: serviceModelInvariantUuid='" + serviceModelInvariantUuid + "' " + he.getMessage());
1368             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid);
1369
1370                 throw he;
1371         } catch (Exception e) {
1372                 LOGGER.debug("Generic Exception - while searching for: serviceModelInvariantUuid='" + serviceModelInvariantUuid + "' " + e.getMessage());
1373             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid);
1374
1375                 throw e;
1376         }
1377         if (vnfResource == null) {
1378             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null);
1379         } else {
1380             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
1381         }
1382         return vnfResource;
1383     }
1384
1385     public VnfResource getVnfResourceByVnfUuid(String vnfResourceModelInvariantUuid) {
1386         long startTime = System.currentTimeMillis();
1387         LOGGER.debug("Catalog database - get vfModuleType with vnfResourceModelInvariantUuid " + vnfResourceModelInvariantUuid);
1388
1389         String hql = "FROM VnfResource WHERE vnfResourceModelInvariantUuid = :vnfResourceModelInvariantUuid";
1390         Query query = getSession().createQuery(hql);
1391         query.setParameter("vnfResourceModelInvariantUuid", vnfResourceModelInvariantUuid);
1392         VnfResource vnfResource = null;
1393         try {
1394             vnfResource = (VnfResource) query.uniqueResult();
1395         } catch (org.hibernate.NonUniqueResultException nure) {
1396             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnfResourceModelInvariantUuid='" + vnfResourceModelInvariantUuid);
1397             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnfResourceModelInvariantUuid==" + vnfResourceModelInvariantUuid);
1398
1399                 throw nure;
1400         } catch (org.hibernate.HibernateException he) {
1401                 LOGGER.debug("Hibernate Exception - while searching for: vnfResourceModelInvariantUuid='" + vnfResourceModelInvariantUuid + "' " + he.getMessage());
1402             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid);
1403
1404                 throw he;
1405         } catch (Exception e) {
1406                 LOGGER.debug("Generic Exception - while searching for: vnfResourceModelInvariantUuid='" + vnfResourceModelInvariantUuid + "' " + e.getMessage());
1407             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid);
1408
1409                 throw e;
1410         }
1411         if (vnfResource == null) {
1412             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null);
1413         } else {
1414             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null);
1415         }
1416         return vnfResource;
1417     }
1418
1419     public VnfResource getVnfResourceByType(String vnfType) {
1420         return this.getVnfResource(vnfType);
1421     }
1422
1423     public VfModule getVfModuleByModelInvariantUuid(String modelInvariantUUID) {
1424         long startTime = System.currentTimeMillis();
1425         LOGGER.debug ("Catalog database - get vfModuleTypeByModelInvariantUuid with uuid " + modelInvariantUUID);
1426
1427         String hql = "FROM VfModule WHERE modelInvariantUUID = :modelInvariantUUID ";
1428         HashMap<String, String> parameters = new HashMap<>();
1429         parameters.put("modelInvariantUUID", modelInvariantUUID);
1430         List<VfModule> modules = this.executeQueryMultipleRows(hql, parameters, true);
1431         VfModule module = null;
1432         
1433         if (modules != null && ! modules.isEmpty()) {
1434                 modules.sort(new MavenLikeVersioningComparator());
1435                 Collections.reverse (modules);
1436                 module =  modules.get(0);
1437         }
1438   
1439         if (module == null) {
1440             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelInvariantUuid", null);
1441         } else {
1442             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelInvariantUuid", null);
1443         }
1444         return module;
1445     }
1446
1447     public VfModuleCustomization getVfModuleByModelCustomizationUuid(String modelCustomizationUuid) {
1448         long startTime = System.currentTimeMillis();
1449         LOGGER.debug ("Catalog database - get vfModuleTypeByModelCustomizationUuid with uuid " + modelCustomizationUuid);
1450
1451         String hql = "FROM VfModuleCustomization WHERE modelCustomizationUuid = :modelCustomizationUuid ";
1452         Query query = getSession().createQuery(hql);
1453         query.setParameter ("modelCustomizationUuid", modelCustomizationUuid);
1454         VfModuleCustomization module = null;
1455         try {
1456                 module = (VfModuleCustomization) query.uniqueResult ();
1457         } catch (org.hibernate.NonUniqueResultException nure) {
1458             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelCustomizationUuid='" + modelCustomizationUuid + "'");
1459             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vfModuleModelInvariantUuid=" + modelCustomizationUuid , "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelCustomizationUuid==" + modelCustomizationUuid);
1460
1461                 throw nure;
1462         } catch (org.hibernate.HibernateException he) {
1463                 LOGGER.debug("Hibernate Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + he.getMessage());
1464             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1465
1466                 throw he;
1467         } catch (Exception e) {
1468                 LOGGER.debug("Generic Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + e.getMessage());
1469             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1470
1471                 throw e;
1472         }
1473         if (module == null) {
1474             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelCustomizationUuid", null);
1475         } else {
1476             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelCustomizationUuid", null);
1477         }
1478         return module;
1479     }
1480
1481     
1482     public VfModule getVfModuleByModelInvariantUuidAndModelVersion(String modelInvariantUuid, String modelVersion) {
1483         long startTime = System.currentTimeMillis();
1484         LOGGER.debug ("Catalog database - get getVfModuleByModelInvariantUuidAndModelVersion with modelInvariantUuid: " + modelInvariantUuid + ", modelVersion: " + modelVersion);
1485
1486         String hql = "FROM VfModule WHERE modelInvariantUUID = :modelInvariantUuid and version = :modelVersion";
1487         Query query = getSession().createQuery(hql);
1488         query.setParameter ("modelInvariantUuid", modelInvariantUuid);
1489         query.setParameter("modelVersion", modelVersion);
1490         VfModule module = null;
1491         try {
1492                 module = (VfModule) query.uniqueResult ();
1493         } catch (org.hibernate.NonUniqueResultException nure) {
1494                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelInvariantUuid='" + modelInvariantUuid + "', modelVersion='" +modelVersion + "'");
1495                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vfModule ModelInvariantUuid=" + modelInvariantUuid + " modelVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for ModelInvariantUuid==" + modelInvariantUuid + " modelVersion==" + modelVersion);
1496                 throw nure;
1497         } catch (org.hibernate.HibernateException he) {
1498                 LOGGER.debug("Hibernate Exception - while searching for: modelInvariantUuid='" + modelInvariantUuid + "', modelVersion='" +modelVersion + "' " + he.getMessage());
1499                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelInvariantUuid=" + modelInvariantUuid + " modelVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelInvariantUuid=" + modelInvariantUuid + " modelVersion=" + modelVersion);
1500                 throw he;
1501         } catch (Exception e) {
1502                 LOGGER.debug("Generic Exception - while searching for: modelInvariantUuid='" + modelInvariantUuid + "', modelVersion='" +modelVersion + "' " + e.getMessage());
1503                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelInvariantUuid=" + modelInvariantUuid + " modelVersion=" + modelVersion, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelInvariantUuid=" + modelInvariantUuid + " modelVersion=" + modelVersion);
1504                 throw e;
1505         }
1506         if (module == null) {
1507                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelInvariantUuidAndModelVersion", null);
1508         } else {
1509                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelInvariantUuidAndModelVersion", null);
1510         }
1511         return module;
1512     }
1513     
1514     /**
1515      * Return the VfModuleCustomization object identified by the given modelCustomizationUuid 1707
1516      *
1517      * @param modelCustomizationUuid
1518      * @return VfModuleCustomization or null if not found
1519      */
1520     public VfModuleCustomization getVfModuleCustomizationByModelCustomizationId(String modelCustomizationUuid) {
1521         long startTime = System.currentTimeMillis();
1522         LOGGER.debug ("Catalog database - get getVfModuleCustomizationByModelCustomizationId with modelCustomizationUuid: " + modelCustomizationUuid);
1523
1524         String hql = "FROM VfModuleCustomization WHERE modelCustomizationUuid = :modelCustomizationUuid";
1525         Query query = getSession().createQuery(hql);
1526         query.setParameter ("modelCustomizationUuid", modelCustomizationUuid);
1527         VfModuleCustomization VfModuleCustomization = null;
1528         try {
1529                 VfModuleCustomization = (VfModuleCustomization) query.uniqueResult ();
1530         } catch (org.hibernate.NonUniqueResultException nure) {
1531                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: modelCustomizationUuid='" + modelCustomizationUuid +"'");
1532                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vfModuleCustomization modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelCustomizationUuid==" + modelCustomizationUuid);
1533                 throw nure;
1534         } catch (org.hibernate.HibernateException he) {
1535                 LOGGER.debug("Hibernate Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + he.getMessage());
1536                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1537                 throw he;
1538         } catch (Exception e) {
1539                 LOGGER.debug("Generic Exception - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + e.getMessage());
1540                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1541                 throw e;
1542         }
1543         if (VfModuleCustomization != null) {
1544                 LOGGER.debug("Found VMC of " + VfModuleCustomization.getModelCustomizationUuid() + ", now looking for vfModule=" + VfModuleCustomization.getVfModuleModelUuid());
1545                 VfModuleCustomization.setVfModule(this.getVfModuleByModelUuid(VfModuleCustomization.getVfModuleModelUuid()));
1546         }
1547
1548         if (VfModuleCustomization == null) {
1549                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleCustomizationByModelCustomizationId", null);
1550         } else {
1551                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleCustomizationByModelCustomizationId", null);
1552         }
1553         return VfModuleCustomization;
1554     }
1555     
1556     /**
1557      * Return the VfModule object identified by the given modelUuid 1707
1558      * per Mike Z. - this may return more than one row - and even if it does, 
1559      * the heat template will be the same - so just return any of the rows.
1560      *
1561      * @param modelUuid
1562      * @return VfModule or null if not found
1563      */
1564     public VfModule getVfModuleByModelUuid(String modelUuid) {
1565         long startTime = System.currentTimeMillis();
1566         LOGGER.debug ("Catalog database - get getVfModuleByModelUuid with modelUuid: " + modelUuid);
1567
1568         String hql = "FROM VfModule WHERE modelUUID = :modelUuidValue";
1569         Query query = getSession().createQuery(hql);
1570         query.setParameter ("modelUuidValue", modelUuid);
1571         List<VfModule> vfModules = null;
1572         try {
1573                 vfModules = query.list ();
1574         } catch (org.hibernate.HibernateException he) {
1575                 LOGGER.debug("Hibernate Exception - while searching VfModule for: modelUuid='" + modelUuid + "' " + he.getMessage());
1576                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VfModule for modelUuid=" + modelUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelUuid=" + modelUuid);
1577                 throw he;
1578         } catch (Exception e) {
1579                 LOGGER.debug("Generic Exception - while searching VfModule for: modelUuid='" + modelUuid + "' " + e.getMessage());
1580                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for modelUuid=" + modelUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelUuid=" + modelUuid);
1581                 throw e;
1582         }
1583
1584         if (vfModules == null || vfModules.isEmpty()) {
1585                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelUuid", null);
1586                 return null;
1587         } else {
1588                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelUuid", null);
1589         }
1590         return vfModules.get(0);
1591     }
1592     /**
1593      * Return the VnfResourceCustomization object identified by the given modelCustomizationUuid 1707
1594      * Note that the corresponding VnfResource Object will be put in the VnfResourceCustomization bean
1595      *
1596      * @param modelCustomizationUuid
1597      * @return VnfResourceCustomization or null if not found
1598      */
1599     public VnfResourceCustomization getVnfResourceCustomizationByModelCustomizationUuid(String modelCustomizationUuid) {
1600         long startTime = System.currentTimeMillis();
1601         LOGGER.debug ("Catalog database - get getVnfResourceByModelCustomizatonUuid with modelCustomizationUuid: " + modelCustomizationUuid);
1602
1603         String hql = "FROM VnfResourceCustomization WHERE modelCustomizationUuid = :modelCustomizationUuid";
1604         Query query = getSession().createQuery(hql);
1605         query.setParameter ("modelCustomizationUuid", modelCustomizationUuid);
1606         VnfResourceCustomization vnfResourceCustomization = null;
1607         try {
1608                 vnfResourceCustomization = (VnfResourceCustomization) query.uniqueResult ();
1609         } catch (org.hibernate.NonUniqueResultException nure) {
1610                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row in VRC - data integrity error: modelCustomizationUuid='" + modelCustomizationUuid +"'");
1611                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceCustomization modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelCustomizationUuid==" + modelCustomizationUuid);
1612                 throw nure;
1613         } catch (org.hibernate.HibernateException he) {
1614                 LOGGER.debug("Hibernate Exception - while searching VRC for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + he.getMessage());
1615                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VRC for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1616                 throw he;
1617         } catch (Exception e) {
1618                 LOGGER.debug("Generic Exception - while searching VRC for: modelCustomizationUuid='" + modelCustomizationUuid + "' " + e.getMessage());
1619                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching VRC for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1620                 throw e;
1621         }
1622         if (vnfResourceCustomization != null) {
1623                 LOGGER.debug("Found VRC of " + vnfResourceCustomization.getModelCustomizationUuid() + ", now looking for vnfResource=" + vnfResourceCustomization.getVnfResourceModelUuid() );
1624                 vnfResourceCustomization.setVnfResource(this.getVnfResourceByModelUuid(vnfResourceCustomization.getVnfResourceModelUuid()));
1625                 LOGGER.debug("Now looking for vfModules for " + vnfResourceCustomization.getModelCustomizationUuid());
1626                 vnfResourceCustomization.setVfModuleCustomizations(this.getAllVfModuleCustomizations(vnfResourceCustomization.getModelCustomizationUuid()));
1627         }
1628
1629         if (vnfResourceCustomization == null) {
1630                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResourceCustomizationByModelCustomizationUuid", null);
1631         } else {
1632                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationByModelCustomizationUuid", null);
1633         }
1634         return vnfResourceCustomization;
1635     }
1636     
1637     /**
1638      * Return the VnfResourceCustomization object identified by the given modelCustomizationUuid 1707
1639      * Note that the corresponding VnfResource Object will be put in the VnfResourceCustomization bean
1640      *
1641      * @param modelVersionId
1642      * @return VnfResourceCustomization or null if not found
1643      */
1644     public VnfResourceCustomization getVnfResourceCustomizationByModelVersionId(String modelVersionId) {
1645         long startTime = System.currentTimeMillis();
1646         LOGGER.debug ("Catalog database - get getVnfResourceCustomizationByModelVersionId with modelVersionId: " + modelVersionId);
1647
1648         String hql = "FROM VnfResourceCustomization WHERE vnfResourceModelUuid = :modelVersionId";
1649         Query query = getSession().createQuery(hql);
1650         query.setParameter ("modelVersionId", modelVersionId);
1651         VnfResourceCustomization vnfResourceCustomization = null;
1652         try {
1653                 vnfResourceCustomization = (VnfResourceCustomization) query.uniqueResult ();
1654         } catch (org.hibernate.NonUniqueResultException nure) {
1655                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row in VRC - data integrity error: modelVersionId='" + modelVersionId +"'");
1656                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceCustomization modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelVersionId==" + modelVersionId);
1657                 throw nure;
1658         } catch (org.hibernate.HibernateException he) {
1659                 LOGGER.debug("Hibernate Exception - while searching VRC for: modelVersionId='" + modelVersionId + "' " + he.getMessage());
1660                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VRC for modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelVersionId=" + modelVersionId);
1661                 throw he;
1662         } catch (Exception e) {
1663                 LOGGER.debug("Generic Exception - while searching VRC for: modelVersionId='" + modelVersionId + "' " + e.getMessage());
1664                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching VRC for modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelVersionId=" + modelVersionId);
1665                 throw e;
1666         }
1667         if (vnfResourceCustomization != null) {
1668                 LOGGER.debug("Found VRC of " + vnfResourceCustomization.getModelCustomizationUuid() + ", now looking for vnfResource=" + vnfResourceCustomization.getVnfResourceModelUuid() );
1669                 vnfResourceCustomization.setVnfResource(this.getVnfResourceByModelUuid(vnfResourceCustomization.getVnfResourceModelUuid()));
1670                 LOGGER.debug("Now looking for vfModules for " + vnfResourceCustomization.getModelCustomizationUuid());
1671                 vnfResourceCustomization.setVfModuleCustomizations(this.getAllVfModuleCustomizations(vnfResourceCustomization.getModelCustomizationUuid()));
1672         }
1673
1674         if (vnfResourceCustomization == null) {
1675                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResourceCustomizationByModelVersionId", null);
1676         } else {
1677                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationByModelVersionId", null);
1678         }
1679         return vnfResourceCustomization;
1680     }
1681     
1682     /**
1683      * Return the VfModule object identified by the given modelCustomizationId, modelVersionId 1707
1684      *
1685      * @param modelVersionId, modelCustomizationId
1686      * @return VfModule or null if not found
1687      */
1688     public VfModule getVfModuleByModelCustomizationIdAndVersion(String modelCustomizationId, String modelVersionId) {
1689         long startTime = System.currentTimeMillis();
1690         LOGGER.debug ("Catalog database - get getVfModuleByModelCustomizationIdAndVersion with modelVersionId: " + modelVersionId + " modelCustomizationId: " + modelCustomizationId);
1691
1692 //      select * from vf_module vfm where vfm.MODEL_UUID IN (
1693 //      select vfmc.VF_MODULE_MODEL_UUID from vf_module_customization vfmc where vfmc.MODEL_CUSTOMIZATION_UUID='222bd8f2-341d-4419-aa0e-98398fa34050')
1694 //      and vfm.MODEL_UUID = 'fa1c8558-006c-4fb6-82f2-4fc0646d6b06';
1695         
1696         String hql = "Select vfm FROM VfModule as vfm WHERE vfm.modelUUID IN ("
1697                         + "SELECT vfmc.vfModuleModelUuid FROM VfModuleCustomization as vfmc "
1698                         + "WHERE vfmc.modelCustomizationUuid = :modelCustomizationId) "
1699                         + "AND vfm.modelUUID = :modelVersionId";
1700         Query query = getSession().createQuery(hql);
1701         query.setParameter ("modelVersionId", modelVersionId);
1702         query.setParameter ("modelCustomizationId", modelCustomizationId);
1703         VfModule vfModule = null;
1704         try {
1705                 vfModule = (VfModule) query.uniqueResult ();
1706         } catch (org.hibernate.NonUniqueResultException nure) {
1707                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row in VRC - data integrity error: modelVersionId='" + modelVersionId +"' modelCustomizationId='" + modelCustomizationId + "'");
1708                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceCustomization modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelVersionId=" + modelVersionId + " modelCustomizationId=" + modelCustomizationId);
1709                 throw nure;
1710         } catch (org.hibernate.HibernateException he) {
1711                 LOGGER.debug("Hibernate Exception - while searching VRC for: modelVersionId='" + modelVersionId + "' modelCustomizationId='" + modelCustomizationId + "' " + he.getMessage());
1712                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VRC for modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelVersionId=" + modelVersionId + " modelCustomizationId=" + modelCustomizationId);
1713                 throw he;
1714         } catch (Exception e) {
1715                 LOGGER.debug("Generic Exception - while searching VRC for: modelVersionId='" + modelVersionId + "' modelCustomizationId='" + modelCustomizationId + "' " + e.getMessage());
1716                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching VRC for modelVersionId=" + modelVersionId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelVersionId=" + modelVersionId + " modelCustomizationId=" + modelCustomizationId);
1717                 throw e;
1718         }
1719
1720         if (vfModule == null) {
1721                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelCustomizationIdAndVersion", null);
1722         } else {
1723                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelCustomizationIdAndVersion", null);
1724         }
1725         return vfModule;
1726     }
1727     
1728     /**
1729      * Return the VfModule object identified by the given modelCustomizationId, modelVersion, modelInvariantId 1707
1730      *
1731      * @param modelCustomizationId, modelVersion, modelInvariantId
1732      * @return VfModule or null if not found
1733      */
1734     public VfModule getVfModuleByModelCustomizationIdModelVersionAndModelInvariantId(String modelCustomizationId, String modelVersion, String modelInvariantId) {
1735         long startTime = System.currentTimeMillis();
1736         LOGGER.debug ("Catalog database - get getVfModuleByModelCustomizationIdModelVersionAndModelInvariantId with modelVersionId: " + modelVersion);
1737
1738         //select * from vf_module vfm left outer join vf_module_customization vfmc on vfmc.VF_MODULE_MODEL_UUID = vfm.MODEL_UUID 
1739 //        where vfmc.MODEL_CUSTOMIZATION_UUID='52643a8e-7953-4e48-8eab-97165b2b3a4b' and vfm.MODEL_UUID = ''
1740         
1741         String hql = "Select vfm FROM VfModule as vfm LEFT OUTER JOIN VfModuleCustomization as vfmc on vfmc.vfModuleModelUuid = vfm.modelUUID"
1742                         + "WHERE vfmc.modelCustomizationUuid = :modelCustomizationId AND vfm.modelInvariantUUID = :modelInvariantId AND vfm.modelVersion = :modelVersion";
1743         Query query = getSession().createQuery(hql);
1744         query.setParameter ("modelInvariantId", modelInvariantId);
1745         query.setParameter ("modelCustomizationId", modelCustomizationId);
1746         query.setParameter ("modelVersion", modelVersion);
1747         VfModule vfModule = null;
1748         try {
1749                 vfModule = (VfModule) query.uniqueResult ();
1750         } catch (org.hibernate.NonUniqueResultException nure) {
1751                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row in VRC - data integrity error: modelInvariantId='" + modelInvariantId +"' modelVersion='" + modelVersion + "' modelCustomizationId='" + modelCustomizationId +"'");
1752                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceCustomization modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelInvariantId=" + modelInvariantId + " modelVersion=" + modelVersion + " modelCustomizationId=" + modelCustomizationId);
1753                 throw nure;
1754         } catch (org.hibernate.HibernateException he) {
1755                 LOGGER.debug("Hibernate Exception - while searching VRC for: modelInvariantId='" + modelInvariantId + "' modelVersion='" + modelVersion + "' modelCustomizationId='" + modelCustomizationId + "' " + he.getMessage());
1756                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VRC for modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelInvariantId=" + modelInvariantId + " modelVersion=" + modelVersion + " modelCustomizationId=" + modelCustomizationId);
1757                 throw he;
1758         } catch (Exception e) {
1759                 LOGGER.debug("Generic Exception - while searching VRC for: modelInvariantId='" + modelInvariantId + "' modelVersion='" + modelVersion + "' modelCustomizationId='" + modelCustomizationId + "' " + e.getMessage());
1760                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching VRC for modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelInvariantId=" + modelInvariantId + " modelVersion=" + modelVersion + " modelCustomizationId=" + modelCustomizationId);
1761                 throw e;
1762         }
1763
1764         if (vfModule == null) {
1765                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleByModelCustomizationIdModelVersionAndModelInvariantId", null);
1766         } else {
1767                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelCustomizationIdModelVersionAndModelInvariantId", null);
1768         }
1769         return vfModule;
1770     }
1771     
1772     /**
1773      * Return the VnfResourceCustomization object identified by the given modelCustomizationName, modelInvariantId and modelVersion 1707
1774      *
1775      * @param modelInvariantId, modelVersion, modelCustomizationName
1776      * @return VnfResourceCustomization or null if not found
1777      */
1778     public VnfResourceCustomization getVnfResourceCustomizationByModelInvariantId(String modelInvariantId, String modelVersion, String modelCustomizationName) {
1779         long startTime = System.currentTimeMillis();
1780         LOGGER.debug ("Catalog database - get getVnfResourceCustomizationByModelInvariantId with modelInvariantId: " + modelInvariantId + ", modelVersion: " 
1781                                                 + modelVersion + ", modelCustomizationName: " + modelCustomizationName);
1782         
1783         String hql = "SELECT VnfResourceCustomization FROM VnfResourceCustomization as vrc "
1784                                 + "LEFT OUTER JOIN VnfResource as vr "
1785                                 + "on vr.modelUuid =vrc.vnfResourceModelUuid "
1786                                 + "WHERE vr.modelInvariantUuid = :modelInvariantId AND vr.modelVersion = :modelVersion AND vrc.modelInstanceName = :modelCustomizationName";
1787         
1788         Query query = getSession().createQuery(hql);
1789         query.setParameter ("modelInvariantId", modelInvariantId);
1790         query.setParameter("modelVersion", modelVersion);
1791         query.setParameter("modelCustomizationName", modelCustomizationName);
1792         VnfResourceCustomization vnfResourceCustomization = null;
1793         try {
1794                 vnfResourceCustomization = (VnfResourceCustomization) query.uniqueResult ();
1795         } catch (org.hibernate.NonUniqueResultException nure) {
1796                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row in VRC - data integrity error: modelInvariantId='" + modelInvariantId +"' and modelVersion='" + modelVersion + "' modelCustomizationName='" + modelCustomizationName + "'");
1797                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceCustomization modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for modelInvariantId==" + modelInvariantId+"' and modelVersion='" + modelVersion + "'modelCustomizationName='" + modelCustomizationName + "'");
1798                 throw nure;
1799         } catch (org.hibernate.HibernateException he) {
1800                 LOGGER.debug("Hibernate Exception - while searching VRC for: modelInvariantId='" + modelInvariantId +"' and modelVersion='" + modelVersion + "'modelCustomizationName='" + modelCustomizationName + "' " + he.getMessage());
1801                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching VRC for modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelInvariantId=" + modelInvariantId+"' and modelVersion='" + modelVersion + "'modelCustomizationName='" + modelCustomizationName + "'");
1802                 throw he;
1803         } catch (Exception e) {
1804                 LOGGER.debug("Generic Exception - while searching VRC for: modelInvariantId='" + modelInvariantId +"' and modelVersion='" + modelVersion + "' " + e.getMessage());
1805                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching VRC for modelInvariantId=" + modelInvariantId, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for modelInvariantId=" + modelInvariantId+"' and modelVersion='" + modelVersion + "'modelCustomizationName='" + modelCustomizationName + "'");
1806                 throw e;
1807         }
1808         if (vnfResourceCustomization != null) {
1809                 LOGGER.debug("Found VRC of " + vnfResourceCustomization.getModelCustomizationUuid() + ", now looking for vnfResource=" + vnfResourceCustomization.getVnfResourceModelUuid() );
1810                 vnfResourceCustomization.setVnfResource(this.getVnfResourceByModelUuid(vnfResourceCustomization.getVnfResourceModelUUID()));
1811                 LOGGER.debug("Now looking for vfModules for " + vnfResourceCustomization.getModelCustomizationUuid());
1812                 vnfResourceCustomization.setVfModuleCustomizations(this.getAllVfModuleCustomizations(vnfResourceCustomization.getModelCustomizationUuid()));
1813         }
1814
1815         if (vnfResourceCustomization == null) {
1816                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResourceCustomizationByModelInvariantId", null);
1817         } else {
1818                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationByModelInvariantId", null);
1819         }
1820         return vnfResourceCustomization;
1821     }
1822     
1823     /**
1824      * Return list of VnfResourceCustomization objects identified by the given modelCustomizationUuid 1707
1825      *
1826      * @param modelCustomizationUuid
1827      * @return List<VfModuleCustomization> or null if not found
1828      */
1829     public List<VfModuleCustomization> getVfModuleCustomizationByVnfModuleCustomizationUuid(String modelCustomizationUuid) {
1830         long startTime = System.currentTimeMillis();
1831         LOGGER.debug ("Catalog database - get getVfModuleCustomizationByVnfModuleCustomizationUuid with modelCustomizationUuid: " + modelCustomizationUuid);
1832         
1833 //      select * from vf_module_customization as vfmc where vfmc.MODEL_CUSTOMIZATION_UUID IN(
1834 //      select vrcmc.VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID from vnf_res_custom_to_vf_module_custom as vrcmc
1835 //      where vrcmc.VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID = 'd279139c-4b85-48ff-8ac4-9b83a6fc6da7') 
1836         
1837         String hql = "SELECT vfmc FROM VfModuleCustomization as vfmc where vfmc.modelCustomizationUuid "
1838                                 + "IN(select vrcmc.vfModuleCustModelCustomizationUuid from VnfResCustomToVfModuleCustom as vrcmc "
1839                                                 + "WHERE vrcmc.vnfResourceCustModelCustomizationUuid = :modelCustomizationUuid)";
1840         
1841         Query query = getSession().createQuery(hql);
1842         query.setParameter ("modelCustomizationUuid", modelCustomizationUuid);
1843         List<VfModuleCustomization> resultList = null;
1844         try {
1845                 resultList = query.list();
1846         } catch (org.hibernate.HibernateException he) {
1847                 LOGGER.debug("Hibernate Exception - getVfModuleCustomizationByVnfModuleCustomizationUuid - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + " " + he.getMessage());
1848                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception - getVfModuleCustomizationByVnfModuleCustomizationUuid - searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1849                 throw he;
1850         } catch (Exception e) {
1851                 LOGGER.debug("Exception - getVfModuleCustomizationByVnfModuleCustomizationUuid - while searching for: modelCustomizationUuid='" + modelCustomizationUuid + " " + e.getMessage());
1852                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception - getVfModuleCustomizationByVnfModuleCustomizationUuid - searching for modelCustomizationUuid=" + modelCustomizationUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for modelCustomizationUuid=" + modelCustomizationUuid);
1853                 throw e;
1854         }
1855
1856         if (resultList == null) {
1857                 resultList = new ArrayList<>();
1858         }
1859         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleCustomizationByVnfModuleCustomizationUuid", null);
1860         return resultList;
1861     }
1862     
1863     /**
1864      * Return the newest version of a specific VNF resource Customization (queried by modelCustomizationName and modelVersionId).
1865      *
1866      * @return {@link VnfResourceCustomization} object or null if none found
1867      */
1868     public VnfResourceCustomization getVnfResourceCustomizationByVnfModelCustomizationNameAndModelVersionId (String modelCustomizationName, String modelVersionId) {
1869
1870         long startTime = System.currentTimeMillis ();
1871         LOGGER.debug ("Catalog database - get VNF resource Customization with modelCustomizationName " + modelCustomizationName + " modelUUID " + modelVersionId);
1872
1873         String hql = "SELECT vrc FROM VnfResourceCustomization as vrc WHERE vrc.vnfResourceModelUuid IN "
1874                                         + "(SELECT vr.modelUuid FROM VnfResource vr "
1875                                         + "WHERE vr.modelUuid = :modelVersionId)"
1876                                         + "AND vrc.modelInstanceName = :modelCustomizationName";
1877                 
1878         Query query = getSession ().createQuery (hql);
1879         query.setParameter ("modelCustomizationName", modelCustomizationName);
1880         query.setParameter ("modelVersionId", modelVersionId);
1881
1882         @SuppressWarnings("unchecked")
1883         List <VnfResourceCustomization> resultList = query.list ();
1884
1885         if (resultList.isEmpty ()) {
1886             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VnfResourceCustomization not found", "CatalogDB", "getVnfResourceCustomizationByVnfModelCustomizationNameAndModelVersionId", null);
1887             return null;
1888         }
1889         
1890         resultList.sort(new MavenLikeVersioningComparator());
1891         Collections.reverse (resultList);
1892
1893         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationByVnfModelCustomizationNameAndModelVersionId", null);
1894         return resultList.get (0);
1895     }
1896     
1897     public ArrayList<VfModuleCustomization> getAllVfModuleCustomizations(String vnfResourceCustomizationMCU) {
1898         LOGGER.debug ("Catalog database - getAllVfModuleCustomizations with vnfResourceCustomizationMCU " + vnfResourceCustomizationMCU);
1899         
1900         List<VnfResCustomToVfModuleCustom> matches = this.getVRCtoVFMC(vnfResourceCustomizationMCU, null); 
1901         if (matches == null || matches.isEmpty()) {
1902                 LOGGER.debug("Found no vf modules for " + vnfResourceCustomizationMCU);
1903                 return new ArrayList<>();
1904         }
1905         ArrayList<VfModuleCustomization> list = new ArrayList<>();
1906         for (VnfResCustomToVfModuleCustom v : matches) {
1907                 String m = v.getVfModuleCustModelCustomizationUuid();
1908                 LOGGER.debug("VfModule to match: " + m);
1909                 VfModuleCustomization c = this.getVfModuleCustomizationByModelCustomizationId(m);
1910                 if (c != null) {
1911                         list.add(c);
1912                 } else {
1913                         LOGGER.debug("**UNABLE to find vfModule " + m);
1914                 }
1915         }
1916         return list;
1917     }
1918     
1919     /**
1920      * Return the VnfResourceCustomization object identified by the given modelCustomizationUuid 1707
1921      * Note that the corresponding VnfResource Object will be put in the VnfResourceCustomization bean
1922      *
1923      * @param modelUuid
1924      * @return VnfResourceCustomization or null if not found
1925      */
1926     public VnfResource getVnfResourceByModelUuid(String modelUuid) {
1927         long startTime = System.currentTimeMillis();
1928         LOGGER.debug ("Catalog database - get VnfResource with modelUuid " + modelUuid);
1929
1930         String hql = "FROM VnfResource WHERE modelUuid = :modelUuid";
1931         Query query = getSession().createQuery(hql);
1932         query.setParameter ("modelUuid", modelUuid);
1933         VnfResource vnfResource = null;
1934         try {
1935                 vnfResource = (VnfResource) query.uniqueResult ();
1936         } catch (org.hibernate.NonUniqueResultException nure) {
1937                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique Vnf_Resource row - data integrity error: modelUuid='" + modelUuid);
1938                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for Vnf Resource modelUuid=" + modelUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnfResource modelUuid==" + modelUuid);
1939                 throw nure;
1940         } catch (org.hibernate.HibernateException he) {
1941                 LOGGER.debug("Hibernate Exception - while searching for: VnfResource modelUuid='" + modelUuid + "' " + he.getMessage());
1942                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for vnfResource ModelUuid=" + modelUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfResource modelUuid=" + modelUuid);
1943                 throw he;
1944         } catch (Exception e) {
1945                 LOGGER.debug("Generic Exception - while searching for: vnfResource ModelUuid='" + modelUuid + "'");
1946                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for vnfResource ModelUuid=" + modelUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for vnfResource modelUuid=" + modelUuid);
1947                 throw e;
1948         }
1949         if (vnfResource == null) {
1950                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResourceByModelUuid", null);
1951         } else {
1952                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceByModelUuid", null);
1953         }
1954         return vnfResource;
1955     }
1956
1957     public VnfResCustomToVfModuleCustom getVnfResCustomToVfModule(String vnfId, String vfId) {
1958         long startTime = System.currentTimeMillis();
1959         LOGGER.debug("Catalog database - getVnfResCustomToVfModule - vnfResourceCustModelCustUuid: " + vnfId + ", vfModuleCustModelCustomUuid=" + vfId);
1960         HashMap<String, String> parameters = new HashMap<>();
1961         parameters.put("vnfIdValue", vnfId);
1962         parameters.put("vfIdValue", vfId);
1963         VnfResCustomToVfModuleCustom vrctvmc = this.executeQuerySingleRow(
1964             "FROM VnfResCustomToVfModuleCustom where vnfResourceCustModelCustomizationUuid = :vnfIdValue and vfModuleCustModelCustomizationUuid = :vfIdValue", parameters, true);
1965         if (vrctvmc == null) {
1966                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVnfResCustomToVfModule", null);
1967         } else {
1968                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResCustomToVfModule", null);
1969         }
1970         return vrctvmc;
1971     }
1972
1973     public List<VfModule> getVfModulesForVnfResource(VnfResource vnfResource) {
1974         if (vnfResource == null)
1975             return Collections.EMPTY_LIST;
1976         String vnfResourceModelUuid = vnfResource.getModelUuid();
1977
1978         LOGGER.debug("Catalog database - getVfModulesForVnfResource - vnfResource: " + vnfResource.toString());
1979
1980         return this.getVfModulesForVnfResource(vnfResourceModelUuid);
1981
1982     }
1983
1984     public List<VfModule> getVfModulesForVnfResource(String vnfResourceModelUuid) {
1985         long startTime = System.currentTimeMillis();
1986         LOGGER.debug("Catalog database - getVfModulesForVnfResource - vnfResourceModelUuid: " + vnfResourceModelUuid);
1987         Query query = getSession().createQuery("FROM VfModule where vnfResourceModelUUId = :vnfResourceModelUUId");
1988         query.setParameter("vnfResourceModelUUId", vnfResourceModelUuid);
1989         List<VfModule> resultList = null;
1990         try {
1991             resultList = query.list();
1992             if (resultList != null)
1993                 LOGGER.debug("\tQuery found " + resultList.size() + " records.");
1994             else
1995                 LOGGER.debug("\tQuery found no records.");
1996         } catch (org.hibernate.HibernateException he) {
1997                 LOGGER.debug("Hibernate Exception - getVfModulesForVnfResource - while searching for: vnfResourceModelUUId='" + vnfResourceModelUuid + " " + he.getMessage());
1998                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception - getVfModulesForVnfResource - searching for vnfResourceModelUUId=" + vnfResourceModelUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfResourceModelUUId=" + vnfResourceModelUuid);
1999                 throw he;
2000         } catch (Exception e) {
2001                 LOGGER.debug("Exception - getVfModulesForVnfResource - while searching for: vnfResourceModelUUId='" + vnfResourceModelUuid + " " + e.getMessage());
2002                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception - getVfModulesForVnfResource - searching for vnfResourceModelUUId=" + vnfResourceModelUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for vnfResourceModelUUId=" + vnfResourceModelUuid);
2003                 throw e;
2004         }
2005         if (resultList == null) {
2006             resultList = new ArrayList<>();
2007         }
2008         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModulesForVnfResource", null);
2009         return resultList;
2010     }
2011
2012     public Service getServiceByUuid (String serviceModelInvariantUuid) {
2013
2014         long startTime = System.currentTimeMillis ();
2015         LOGGER.debug ("Catalog database - get service with ModelInvariantUuid " + serviceModelInvariantUuid);
2016
2017         String hql = "FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid";
2018         Query query = getSession ().createQuery (hql);
2019         query.setParameter ("serviceModelInvariantUuid", serviceModelInvariantUuid);
2020
2021         Service service = null;
2022         try {
2023             service = (Service) query.uniqueResult ();
2024         } catch (org.hibernate.NonUniqueResultException nure) {
2025             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: serviceModelInvariantUuid='" + serviceModelInvariantUuid + "'");
2026             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for serviceModelInvariantUuid=" + serviceModelInvariantUuid);
2027                 throw nure;
2028         } catch (org.hibernate.HibernateException he) {
2029                 LOGGER.debug("Hibernate Exception - while searching for: serviceName='" + serviceModelInvariantUuid + "' " + he.getMessage());
2030             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid);
2031                 throw he;
2032         } catch (Exception e) {
2033                 LOGGER.debug("Generic Exception - while searching for: serviceModelInvariantUuid='" + serviceModelInvariantUuid + " " + e.getMessage());
2034             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for serviceModelInvariantUuid=" + serviceModelInvariantUuid);
2035                 throw e;
2036         }
2037         if (service == null) {
2038             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getService", null);
2039         } else {
2040             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getService", null);
2041         }
2042
2043         return service;
2044     }
2045
2046     public NetworkResource getNetworkResourceById(Integer id) {
2047         long startTime = System.currentTimeMillis ();
2048         LOGGER.debug ("Catalog database - getNetworkResource with id " + id);
2049
2050         String hql = "FROM NetworkResource WHERE id = :id";
2051         Query query = getSession ().createQuery (hql);
2052         query.setParameter ("id", id);
2053
2054         NetworkResource networkResource = null;
2055         try {
2056             networkResource = (NetworkResource) query.uniqueResult ();
2057         } catch (org.hibernate.NonUniqueResultException nure) {
2058             LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: NETWORK_RESOURCE.id='" + id + "'");
2059             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for NETWORK_RESOURCE.id=" + id, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for NETWORK_RESOURCE.id=" + id);
2060                 throw nure;
2061         } catch (org.hibernate.HibernateException he) {
2062                 LOGGER.debug("Hibernate Exception - while searching for: NETWORK_RESOURCE.id='" + id + "' " + he.getMessage());
2063             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for NETWORK_RESOURCE.id=" + id, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for NETWORK_RESOURCE.id=" + id);
2064                 throw he;
2065         } catch (Exception e) {
2066                 LOGGER.debug("Generic Exception - while searching for: NETWORK_RESOURCE.id='" + id + " " + e.getMessage());
2067             LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for NETWORK_RESOURCE.id=" + id, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for NETWORK_RESOURCE.id=" + id);
2068                 throw e;
2069         }
2070
2071         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResourceById", null);
2072         return networkResource;
2073
2074     }
2075
2076     public NetworkResource getNetworkResourceById(String id) {
2077         long startTime = System.currentTimeMillis ();
2078         LOGGER.debug ("Catalog database - getNetworkResource with model_uuid " + id);
2079
2080         String hql = "FROM NetworkResource WHERE modelUUID = :model_uuid";
2081         Query query = getSession ().createQuery (hql);
2082         query.setParameter ("model_uuid", id);
2083         
2084         List<NetworkResource> networkResources = null;
2085         try {
2086                 networkResources = query.list ();
2087         } catch (org.hibernate.HibernateException he) {
2088                 LOGGER.debug("Hibernate Exception - while searching for: NETWORK_RESOURCE.id='" + id + "' " + he.getMessage());
2089                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for NETWORK_RESOURCE.model_uuid=" + id, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for NETWORK_RESOURCE.model_uuid=" + id);
2090                 throw he;
2091         } catch (Exception e) {
2092                 LOGGER.debug("Generic Exception - while searching for: NETWORK_RESOURCE.id='" + id + " " + e.getMessage());
2093                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for NETWORK_RESOURCE.model_uuid=" + id, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for NETWORK_RESOURCE.model_uuid=" + id);
2094                 throw e;
2095         }
2096         
2097         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResourceById", null);
2098         if (networkResources == null || networkResources.isEmpty())
2099                 return null;
2100         else
2101                 return networkResources.get(0);
2102     }
2103     
2104     // 1707 API Spec
2105     
2106     public static boolean isEmptyOrNull(String str) {
2107         if (str == null) 
2108                 return true;
2109         if ("null".equals(str))
2110                 return true;
2111         if ("".equals(str))
2112                 return true;
2113         return false;
2114     }
2115     
2116     public List<ServiceToResourceCustomization> getSTR(String serviceModelUuid, String resourceModelCustomizationUuid, String modelType) {
2117         LOGGER.debug("Catalog database: getSTR - smu=" + serviceModelUuid + ", rmcu=" + resourceModelCustomizationUuid + ", modelType = " + modelType);
2118         
2119         if (isEmptyOrNull(serviceModelUuid) && isEmptyOrNull(resourceModelCustomizationUuid) && isEmptyOrNull(modelType)) 
2120                 return null;
2121         
2122         StringBuilder hql = new StringBuilder("FROM ServiceToResourceCustomization WHERE ");
2123         boolean first = true;
2124         if (serviceModelUuid != null && !serviceModelUuid.equals("")) {
2125                 hql.append("serviceModelUUID = :smu");
2126                 first = false;
2127         }
2128         if (resourceModelCustomizationUuid != null && !resourceModelCustomizationUuid.equals("")) {
2129                 if (!first) {
2130                         hql.append(" AND ");
2131                 }
2132                 hql.append("resourceModelCustomizationUUID = :rmcu");
2133                 first = false;
2134         }
2135         if (modelType != null && !modelType.equals("")) {
2136                 if (!first) {
2137                         hql.append(" AND ");
2138                         first = false;
2139                 }
2140                 hql.append("modelType = :modelType");
2141                 first = false;
2142         }
2143         Query query = getSession().createQuery(hql.toString());
2144         if (hql.toString().contains(":smu")) 
2145                 query.setParameter("smu", serviceModelUuid);
2146         if (hql.toString().contains(":rmcu")) 
2147                 query.setParameter("rmcu", resourceModelCustomizationUuid);
2148         if (hql.toString().contains(":modelType")) 
2149                 query.setParameter("modelType", modelType);
2150         LOGGER.debug("query - " + hql.toString());
2151         
2152         @SuppressWarnings("unchecked")
2153         List<ServiceToResourceCustomization> resultList = query.list();
2154         if (resultList == null || resultList.isEmpty()) {
2155                 LOGGER.debug("Found no matches to the query - " + hql.toString());
2156                 return new ArrayList<>();
2157         }
2158         return resultList;
2159     }
2160     
2161     public List<VnfResCustomToVfModuleCustom> getVRCtoVFMC (String vrc_mcu, String vfmc_mcu) {
2162         LOGGER.debug("Catalog database: getVRCtoVFMC - vrc_mcu=" + vrc_mcu + ", vfmc_mcu=" + vfmc_mcu);
2163         
2164         if (isEmptyOrNull(vrc_mcu) && isEmptyOrNull(vfmc_mcu))
2165                 return null;
2166         
2167         StringBuilder hql = new StringBuilder("FROM VnfResCustomToVfModuleCustom WHERE ");
2168         boolean first = true;
2169         if (vrc_mcu != null && !vrc_mcu.equals("")) {
2170                 hql.append("vnfResourceCustModelCustomizationUuid = :vrc_mcu");
2171                 first = false;
2172         }
2173         if (vfmc_mcu != null && !vfmc_mcu.equals("")) {
2174                 if (!first) {
2175                         hql.append(" AND ");
2176                 }
2177                 hql.append("vfModuleCustModelCustomizationUuid = :vfmc_mcu");
2178                 first = false;
2179         }
2180         Query query = getSession().createQuery(hql.toString());
2181         if (hql.toString().contains(":vrc_mcu")) 
2182                 query.setParameter("vrc_mcu", vrc_mcu);
2183         if (hql.toString().contains(":vfmc_mcu")) 
2184                 query.setParameter("vfmc_mcu", vfmc_mcu);
2185         @SuppressWarnings("unchecked")
2186         List<VnfResCustomToVfModuleCustom> resultList = query.list();
2187         if (resultList == null || resultList.isEmpty()) {
2188                 LOGGER.debug("Found no matches to the query - " + hql.toString());
2189                 return new ArrayList<>();
2190         }
2191         return resultList;
2192     }
2193     
2194     @SuppressWarnings("unchecked")
2195     public List <TempNetworkHeatTemplateLookup> getTempNetworkHeatTemplateLookup (String networkResourceModelName) {
2196
2197         long startTime = System.currentTimeMillis ();
2198         LOGGER.debug ("Catalog database - GetTempNetworkHeatTemplateLookup for Network Name " + networkResourceModelName);
2199
2200         String hql = "FROM TempNetworkHeatTemplateLookup where networkResourceModelName = :networkResourceModelName";
2201         Query query = getSession ().createQuery (hql);
2202         query.setParameter ("networkResourceModelName", networkResourceModelName);
2203
2204         List <TempNetworkHeatTemplateLookup> result = query.list ();
2205         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getTempNetworkHeatTemplateLookup", null);
2206         return result;
2207     }
2208     
2209     // 1702 API Spec - Query for all networks in a Service:
2210     public List<NetworkResourceCustomization> getAllNetworksByServiceModelUuid(String serviceModelUuid) {
2211         long startTime = System.currentTimeMillis();
2212         LOGGER.debug("Catalog database: getServiceNetworksByServiceModelUuid - " + serviceModelUuid);
2213
2214         List<ServiceToResourceCustomization> strMappings = this.getSTR(serviceModelUuid, null, "network");
2215         if (strMappings == null || strMappings.isEmpty()) {
2216                 LOGGER.debug("Found NO matches for NRC with ServiceModelUuid=" + serviceModelUuid);
2217             return new ArrayList<>();
2218         }
2219         LOGGER.debug("Found " + strMappings.size() + " entries in ServiceToResourceCustomizations.network with smu=" + serviceModelUuid); 
2220
2221         ArrayList<NetworkResourceCustomization> masterList = new ArrayList<>();
2222         for (ServiceToResourceCustomization stn : strMappings) {
2223                 String networkModelCustomizationUuid = stn.getResourceModelCustomizationUUID();
2224             LOGGER.debug("Now searching for NetworkResourceCustomization for " + networkModelCustomizationUuid);
2225             List<NetworkResourceCustomization> resultSet = this.getAllNetworksByNetworkModelCustomizationUuid(networkModelCustomizationUuid);
2226             masterList.addAll(resultSet);
2227         }
2228         LOGGER.debug("Returning " + masterList.size() + " NRC records");
2229         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworksByServiceModelUuid", null);
2230         return masterList;
2231     }
2232     public List<NetworkResourceCustomization> getAllNetworksByServiceModelInvariantUuid(String serviceModelInvariantUuid) {
2233         LOGGER.debug("Catalog database: getServiceNetworksByServiceModelInvariantUuid - " + serviceModelInvariantUuid);
2234
2235         Query query = getSession().createQuery("FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid");
2236         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2237         @SuppressWarnings("unchecked")
2238         List<Service> serviceList = query.list();
2239
2240         if (serviceList.isEmpty()) {
2241             LOGGER.debug("Could not find Service for " + serviceModelInvariantUuid);
2242             return new ArrayList<>();
2243         }
2244
2245         serviceList.sort(new MavenLikeVersioningComparator());
2246         Collections.reverse (serviceList);
2247         Service service = serviceList.get(0);
2248
2249         String serviceNameVersionId = service.getModelUUID();
2250         LOGGER.debug("The highest version for the Service " + serviceModelInvariantUuid + " is " + serviceNameVersionId);
2251
2252         // Service.serviceNameVersionId == ServiceToNetworks.serviceModelUuid
2253         return this.getAllNetworksByServiceModelUuid(serviceNameVersionId);
2254     }
2255     public List<NetworkResourceCustomization> getAllNetworksByServiceModelInvariantUuid(String serviceModelInvariantUuid, String serviceModelVersion) {
2256         LOGGER.debug("Catalog database: getServiceNetworksByServiceModelInvariantUuid - " + serviceModelInvariantUuid + ", version=" + serviceModelVersion);
2257
2258         Query query = getSession().createQuery(
2259             "FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid and version = :serviceModelVersion");
2260         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2261         query.setParameter("serviceModelVersion", serviceModelVersion);
2262
2263         //TODO
2264         //can fix this later - no time - could do a unique query here - but this should work
2265         @SuppressWarnings("unchecked")
2266         List<Service> serviceList = query.list();
2267
2268         if (serviceList.isEmpty()) {
2269             LOGGER.debug("No Service found with smu=" + serviceModelInvariantUuid + " and smv=" + serviceModelVersion);
2270             return new ArrayList<>();
2271         }
2272
2273         serviceList.sort(new MavenLikeVersioningComparator());
2274         Collections.reverse (serviceList);
2275         Service service = serviceList.get(0);
2276
2277         String serviceNameVersionId = service.getModelUUID();
2278
2279         // Service.serviceNameVersionId == ServiceToNetworks.serviceModelUuid
2280         return this.getAllNetworksByServiceModelUuid(serviceNameVersionId);
2281
2282     }
2283     public List<NetworkResourceCustomization> getAllNetworksByNetworkModelCustomizationUuid(String networkModelCustomizationUuid) {
2284         long startTime = System.currentTimeMillis();
2285         LOGGER.debug("Catalog database: getAllNetworksByNetworkModelCustomizationUuid - " + networkModelCustomizationUuid);
2286
2287         //Query query = getSession().createQuery(hql.toString());
2288         //query.setParameter("networkModelCustomizationUuid", networkModelCustomizationUuid);
2289         //LOGGER.debug("QUERY: " + hql.toString() + ", networkModelCustomizationUuid=" + networkModelCustomizationUuid);
2290
2291         //@SuppressWarnings("unchecked")
2292         //List<NetworkResourceCustomization> resultList = query.list();
2293
2294         HashMap<String, String> params = new HashMap<>();
2295         params.put("networkModelCustomizationUuid", networkModelCustomizationUuid);
2296
2297         List<NetworkResourceCustomization> resultList = this.executeQueryMultipleRows(
2298             "FROM NetworkResourceCustomization WHERE modelCustomizationUuid = :networkModelCustomizationUuid", params, true);
2299
2300         if (resultList.isEmpty()) {
2301                 LOGGER.debug("Unable to find an NMC with nmcu=" + networkModelCustomizationUuid);
2302                 return new ArrayList<>();
2303         }
2304         for (NetworkResourceCustomization nrc : resultList) {
2305                 nrc.setNetworkResource(this.getNetworkResourceById(nrc.getNetworkResourceModelUuid()));
2306         }
2307
2308         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworksByNetworkModelCustomizationUuid", null);
2309         return resultList;
2310     }
2311     
2312     public List<NetworkResourceCustomization> getAllNetworksByNetworkType(String networkType) {
2313         long startTime = System.currentTimeMillis();
2314         LOGGER.debug("Catalog database: getServiceNetworksByNetworkType - " + networkType);
2315
2316         NetworkResource nr = this.getNetworkResource(networkType);
2317         if (nr == null) {
2318             return new ArrayList<>();
2319         }
2320         String networkResourceId = nr.getModelUUID();
2321
2322         LOGGER.debug("Now searching for NRC's with networkResourceId = " + networkResourceId);
2323
2324         Query query = getSession().createQuery(
2325             "FROM NetworkResourceCustomization WHERE networkResourceModelUuid = :networkResourceId");
2326         query.setParameter("networkResourceId", networkResourceId);
2327
2328         @SuppressWarnings("unchecked")
2329         List<NetworkResourceCustomization> resultList = query.list();
2330
2331         if (resultList != null && ! resultList.isEmpty()) {
2332             LOGGER.debug("Found " + resultList.size() + " results");
2333             for (NetworkResourceCustomization nrc : resultList) {
2334                 nrc.setNetworkType(networkType);
2335                 nrc.setNetworkResource(nr);
2336             }
2337         }
2338         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworksByNetworkType", null);
2339
2340         return resultList;
2341     }
2342     public ArrayList<VfModuleCustomization> getAllVfmcForVrc(VnfResourceCustomization vrc) {
2343         LOGGER.debug("Catalog database: getAllVfmcForVrc - " + vrc.getModelCustomizationUuid());
2344
2345         List<VnfResCustomToVfModuleCustom> vfmcs = this.getVRCtoVFMC(vrc.getModelCustomizationUuid(), null);
2346         if (vfmcs == null || vfmcs.isEmpty()) {
2347                 return new ArrayList<>();
2348         }
2349         ArrayList<VfModuleCustomization> vfModuleCusts = new ArrayList<>();
2350         for (VnfResCustomToVfModuleCustom vfmc : vfmcs) {
2351                 VfModuleCustomization vfmcust = this.getVfModuleCustomizationByModelCustomizationId(vfmc.getVfModuleCustModelCustomizationUuid());
2352                 if (vfmcust != null) {
2353                         vfModuleCusts.add(vfmcust);
2354                 }
2355         }
2356         return vfModuleCusts;
2357     }
2358
2359     //1702 API Spec cont'd - Query for all VnfResources in a Service:
2360     //1707 modified for db refactoring
2361     public List<VnfResourceCustomization> getAllVnfsByServiceModelUuid(String serviceModelUuid) {
2362         LOGGER.debug("Catalog database: getAllVnfsByServiceModelUuid - " + serviceModelUuid);
2363
2364         Query query = getSession().createQuery("FROM Service WHERE modelUUID = :serviceModelUuid");
2365         query.setParameter("serviceModelUuid", serviceModelUuid);
2366         @SuppressWarnings("unchecked")
2367         List<Service> serviceList = query.list();
2368
2369         if (serviceList.isEmpty()) {
2370                 LOGGER.debug("Unable to find a service with modelUuid=" + serviceModelUuid);
2371                 return new ArrayList<>();
2372         }
2373
2374         serviceList.sort(new MavenLikeVersioningComparator());
2375         Collections.reverse (serviceList);
2376
2377         // Step 2 - Now query to get the related VnfResourceCustomizations
2378
2379         List<ServiceToResourceCustomization> strcs = this.getSTR(serviceModelUuid, null, "vnf");
2380
2381         if (strcs.isEmpty()) {
2382                 LOGGER.debug("Unable to find any related vnfs to a service with modelUuid=" + serviceModelUuid);
2383                 return new ArrayList<>();
2384     }
2385
2386         ArrayList<VnfResourceCustomization> allVrcs = new ArrayList<>();
2387         for (ServiceToResourceCustomization strc : strcs) {
2388                 LOGGER.debug("Try to find VRC for mcu=" + strc.getResourceModelCustomizationUUID());
2389                 VnfResourceCustomization vrc = this.getVnfResourceCustomizationByModelCustomizationUuid(strc.getResourceModelCustomizationUUID());
2390                 if (vrc != null)
2391                         allVrcs.add(vrc);
2392         }
2393         return allVrcs;
2394
2395     }
2396     public List<VnfResourceCustomization> getAllVnfsByServiceModelInvariantUuid(String serviceModelInvariantUuid) {
2397         LOGGER.debug("Catalog database: getAllVnfsByServiceModelInvariantUuid - " + serviceModelInvariantUuid);
2398
2399         Query query = getSession().createQuery("FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid");
2400         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2401         @SuppressWarnings("unchecked")
2402         List<Service> resultList = query.list();
2403
2404         if (resultList.isEmpty()) {
2405                 return new ArrayList<>();
2406         }
2407         resultList.sort(new MavenLikeVersioningComparator());
2408         Collections.reverse (resultList);
2409         Service service = resultList.get(0);
2410         //now just call the method that takes the version - the service object will have the highest version
2411         return this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2412     }
2413     public List<VnfResourceCustomization> getAllVnfsByServiceModelInvariantUuid(String serviceModelInvariantUuid, String serviceModelVersion) {
2414         long startTime = System.currentTimeMillis();
2415         LOGGER.debug("Catalog database: getAllVnfsByServiceModelInvariantUuid - " + serviceModelInvariantUuid + ", version=" + serviceModelVersion);
2416
2417         Query query = getSession().createQuery(
2418             "FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid and version = :serviceModelVersion");
2419         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2420         query.setParameter("serviceModelVersion", serviceModelVersion);
2421
2422         @SuppressWarnings("unchecked")
2423         List<Service> resultList = query.list();
2424
2425         if (resultList.isEmpty()) {
2426                 return new ArrayList<>();
2427                 }
2428         resultList.sort(new MavenLikeVersioningComparator());
2429         Collections.reverse (resultList);
2430         Service service = resultList.get(0);
2431         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVnfsByServiceModelInvariantUuid", null);
2432         return this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2433             }
2434
2435     public List<VnfResourceCustomization> getAllVnfsByServiceName(String serviceName, String serviceVersion)  {
2436         LOGGER.debug("Catalog database: getAllVnfsByServiceName - " + serviceName + ", version=" + serviceVersion);
2437         if (serviceVersion == null || serviceVersion.equals("")) {
2438             return this.getAllVnfsByServiceName(serviceName);
2439         }
2440
2441         Query query = getSession().createQuery(
2442             "FROM Service WHERE modelName = :serviceName and version = :serviceVersion");
2443         query.setParameter("serviceName", serviceName);
2444         query.setParameter("serviceVersion", serviceVersion);
2445
2446         @SuppressWarnings("unchecked")
2447         List<Service> resultList = query.list();
2448
2449         if (resultList.isEmpty()) {
2450             return Collections.EMPTY_LIST;
2451         }
2452         Service service = resultList.get(0);
2453         return this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2454     }
2455     public List<VnfResourceCustomization> getAllVnfsByServiceName(String serviceName) {
2456         LOGGER.debug("Catalog database: getAllVnfsByServiceName - " + serviceName);
2457
2458         Query query = getSession().createQuery("FROM Service WHERE modelName = :serviceName");
2459         query.setParameter("serviceName", serviceName);
2460
2461         @SuppressWarnings("unchecked")
2462         List<Service> resultList = query.list();
2463
2464         if (resultList.isEmpty()) {
2465             return Collections.EMPTY_LIST;
2466         }
2467         resultList.sort(new MavenLikeVersioningComparator());
2468         Collections.reverse (resultList);
2469         Service service = resultList.get(0);
2470
2471         return this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2472     }
2473
2474     public List<VnfResourceCustomization> getAllVnfsByVnfModelCustomizationUuid(String vnfModelCustomizationUuid) {
2475         long startTime = System.currentTimeMillis();
2476         LOGGER.debug("Catalog database: getAllVnfsByVnfModelCustomizationUuid - " + vnfModelCustomizationUuid);
2477
2478         Query query1 = getSession().createQuery("FROM VnfResourceCustomization WHERE modelCustomizationUuid = :vrcmcu");
2479         query1.setParameter("vrcmcu", vnfModelCustomizationUuid);
2480         @SuppressWarnings("unchecked")
2481         List<VnfResourceCustomization> resultList1 = query1.list();
2482
2483         if (resultList1.isEmpty()) {
2484             LOGGER.debug("Found no records matching " + vnfModelCustomizationUuid);
2485             return Collections.EMPTY_LIST;
2486         }
2487
2488         for (VnfResourceCustomization vrc : resultList1) {
2489             VnfResource vr = this.getVnfResourceByModelUuid(vrc.getVnfResourceModelUuid());
2490             vrc.setVnfResource(vr);
2491             vrc.setVfModuleCustomizations(this.getAllVfmcForVrc(vrc));
2492         }
2493
2494         LOGGER.debug("Returning " + resultList1.size() + " vnf modules");
2495         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVnfsByVnfModelCustomizationUuid", null);
2496         return resultList1;
2497     }
2498
2499     //1702 API Spec cont'd - Query for all allotted resources in a Service
2500
2501     public List<AllottedResourceCustomization> getAllAllottedResourcesByServiceModelUuid(String serviceModelUuid) {
2502         long startTime = System.currentTimeMillis();
2503         LOGGER.debug("Catalog database: getAllAllottedResourcesByServiceModelUuid - " + serviceModelUuid);
2504
2505         List<ServiceToResourceCustomization> strcs = this.getSTR(serviceModelUuid, null, "allottedResource");
2506         if (strcs == null || strcs.isEmpty()) {
2507                 LOGGER.debug("No AR entries found for " + serviceModelUuid);
2508             return new ArrayList<>();
2509         }
2510         LOGGER.debug("Found " + strcs.size() + " entries in ServiceToResourceCustomizations with smu=" + serviceModelUuid + ", allottedResource"); 
2511
2512         ArrayList<AllottedResourceCustomization> masterList = new ArrayList<>();
2513         for (ServiceToResourceCustomization star : strcs) {
2514                 String arModelCustomizationUuid = star.getResourceModelCustomizationUUID();
2515             LOGGER.debug("Now searching for AllottedResourceCustomization for " + arModelCustomizationUuid);
2516             List<AllottedResourceCustomization> resultSet = this.getAllAllottedResourcesByArModelCustomizationUuid(arModelCustomizationUuid);
2517             masterList.addAll(resultSet);
2518         }
2519         LOGGER.debug("Returning " + masterList.size() + " ARC records");
2520         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllAllottedResourcesByServiceModelUuid", null);
2521         return masterList;
2522     }
2523
2524     public List<AllottedResourceCustomization> getAllAllottedResourcesByServiceModelInvariantUuid(String serviceModelInvariantUuid) {
2525         LOGGER.debug("Catalog database: getAllAllottedResourcesByServiceModelInvariantUuid - " + serviceModelInvariantUuid);
2526
2527         Query query = getSession().createQuery("FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid");
2528         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2529         @SuppressWarnings("unchecked")
2530         List<Service> serviceList = query.list();
2531
2532         if (serviceList.isEmpty()) {
2533             LOGGER.debug("Could not find Service for " + serviceModelInvariantUuid);
2534             return new ArrayList<>();
2535         }
2536
2537         serviceList.sort(new MavenLikeVersioningComparator());
2538         Collections.reverse (serviceList);
2539         Service service = serviceList.get(0);
2540
2541         String serviceModelUuid = service.getModelUUID();
2542         LOGGER.debug("The highest version for the Service " + serviceModelInvariantUuid + " is " + serviceModelUuid);
2543
2544         return this.getAllAllottedResourcesByServiceModelUuid(serviceModelUuid);
2545     }
2546
2547     public List<AllottedResourceCustomization> getAllAllottedResourcesByServiceModelInvariantUuid(String serviceModelInvariantUuid, String serviceModelVersion) {
2548         LOGGER.debug("Catalog database: getAllAllottedResourcesByServiceModelInvariantUuid - " + serviceModelInvariantUuid + ", version=" + serviceModelVersion);
2549
2550         Query query = getSession().createQuery(
2551             "FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid and version = :serviceModelVersion");
2552         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2553         query.setParameter("serviceModelVersion", serviceModelVersion);
2554
2555         @SuppressWarnings("unchecked")
2556         List<Service> serviceList = query.list();
2557
2558         if (serviceList.isEmpty()) {
2559             LOGGER.debug("No Service found with smu=" + serviceModelInvariantUuid + " and smv=" + serviceModelVersion);
2560             return new ArrayList<>();
2561         }
2562
2563         serviceList.sort(new MavenLikeVersioningComparator());
2564         Collections.reverse (serviceList);
2565         Service service = serviceList.get(0);
2566
2567         String serviceModelUuid = service.getModelUUID();
2568
2569         return this.getAllAllottedResourcesByServiceModelUuid(serviceModelUuid);
2570     }
2571
2572     public List<AllottedResourceCustomization> getAllAllottedResourcesByArModelCustomizationUuid(String arModelCustomizationUuid) {
2573         long startTime = System.currentTimeMillis();
2574         LOGGER.debug("Catalog database: getAllAllottedResourcesByArModelCustomizationUuid - " + arModelCustomizationUuid);
2575
2576         Query query = getSession().createQuery(
2577             "FROM AllottedResourceCustomization WHERE modelCustomizationUuid = :arModelCustomizationUuid");
2578         query.setParameter("arModelCustomizationUuid", arModelCustomizationUuid);
2579
2580         @SuppressWarnings("unchecked")
2581         List<AllottedResourceCustomization> resultList = query.list();
2582
2583         if (resultList.isEmpty()) {
2584                 LOGGER.debug("No ARC found with arc_mcu=" + arModelCustomizationUuid);
2585                 return new ArrayList<>();
2586         }
2587         // There should only be one - but we'll handle if multiple
2588         for (AllottedResourceCustomization arc : resultList) {
2589                 AllottedResource ar = this.getAllottedResourceByModelUuid(arc.getArModelUuid());
2590                 arc.setAllottedResource(ar);
2591         }
2592         
2593         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllAllottedResourcesByArModelCustomizationUuid", null);
2594         return resultList;
2595     }
2596
2597     public AllottedResource getAllottedResourceByModelUuid(String arModelUuid) {
2598         long startTime = System.currentTimeMillis ();
2599         LOGGER.debug ("Catalog database - get Allotted Resource with modelUuid= " + arModelUuid);
2600
2601         String hql = "FROM AllottedResource WHERE modelUuid = :arModelUuid";
2602         Query query = getSession ().createQuery (hql);
2603         query.setParameter ("arModelUuid", arModelUuid);
2604
2605         @SuppressWarnings("unchecked")
2606         List <AllottedResource> resultList = query.list ();
2607
2608         // See if something came back. Name is unique, so
2609         if (resultList.isEmpty ()) {
2610             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. AllottedResource not found", "CatalogDB", "getAllottedResourceByModelUuid", null);
2611             return null;
2612         }
2613         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllottedResourceByModelUuid", null);
2614         return resultList.get (0);
2615         
2616     }
2617     
2618     //1702 API Spec cont'd - Query for all resources in a Service:
2619     public ServiceMacroHolder getAllResourcesByServiceModelUuid(String serviceModelUuid) {
2620         long startTime = System.currentTimeMillis();
2621         LOGGER.debug("Catalog database: getAllResourcesByServiceModelUuid - " + serviceModelUuid);
2622
2623         StringBuilder hql = new StringBuilder("FROM Service WHERE modelUUID = :serviceModelUuid");
2624         Query query = getSession().createQuery(hql.toString());
2625         query.setParameter("serviceModelUuid", serviceModelUuid);
2626         LOGGER.debug("Query: " + hql.toString() + ", smu=" + serviceModelUuid);
2627         @SuppressWarnings("unchecked")
2628         List<Service> serviceList = query.list();
2629
2630         if (serviceList.isEmpty()) {
2631             LOGGER.debug("Unable to find a Service with serviceModelUuid=" + serviceModelUuid);
2632             return new ServiceMacroHolder();
2633         }
2634
2635         serviceList.sort(new MavenLikeVersioningComparator());
2636         Collections.reverse (serviceList);
2637         Service service = serviceList.get(0);
2638
2639         ServiceMacroHolder smh = new ServiceMacroHolder(service);
2640         ArrayList<NetworkResourceCustomization> nrcList = (ArrayList<NetworkResourceCustomization>) this.getAllNetworksByServiceModelUuid(serviceModelUuid);
2641         smh.setNetworkResourceCustomization(nrcList);
2642         ArrayList<AllottedResourceCustomization> arcList = (ArrayList<AllottedResourceCustomization>) this.getAllAllottedResourcesByServiceModelUuid(serviceModelUuid);
2643         smh.setAllottedResourceCustomization(arcList);
2644         ArrayList<VnfResourceCustomization> vnfList = (ArrayList<VnfResourceCustomization>) this.getAllVnfsByServiceModelUuid(serviceModelUuid);
2645         smh.setVnfResourceCustomizations(vnfList);
2646
2647         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllResourcesByServiceModelUuid", null);
2648         return smh;
2649     }
2650     public ServiceMacroHolder getAllResourcesByServiceModelInvariantUuid(String serviceModelInvariantUuid) {
2651         long startTime = System.currentTimeMillis();
2652         LOGGER.debug("Catalog database: getAllResourcesByServiceModelInvariantUuid - " + serviceModelInvariantUuid);
2653
2654         Query query = getSession().createQuery("FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid");
2655         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2656         @SuppressWarnings("unchecked")
2657         List<Service> serviceList = query.list();
2658
2659         if (serviceList.isEmpty()) {
2660             LOGGER.debug("Unable to find a Service with serviceModelInvariantUuid=" + serviceModelInvariantUuid);
2661             return new ServiceMacroHolder();
2662         }
2663
2664         serviceList.sort(new MavenLikeVersioningComparator());
2665         Collections.reverse (serviceList);
2666         Service service = serviceList.get(0);
2667
2668         ServiceMacroHolder smh = new ServiceMacroHolder(service);
2669         ArrayList<NetworkResourceCustomization> nrcList = (ArrayList<NetworkResourceCustomization>) this.getAllNetworksByServiceModelUuid(service.getModelUUID());
2670         smh.setNetworkResourceCustomization(nrcList);
2671         ArrayList<AllottedResourceCustomization> arcList = (ArrayList<AllottedResourceCustomization>) this.getAllAllottedResourcesByServiceModelUuid(service.getModelUUID());
2672         smh.setAllottedResourceCustomization(arcList);
2673         ArrayList<VnfResourceCustomization> vnfList = (ArrayList<VnfResourceCustomization>) this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2674         smh.setVnfResourceCustomizations(vnfList);
2675
2676         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllResourcesByServiceModelInvariantUuid", null);
2677         return smh;
2678
2679     }
2680     public ServiceMacroHolder getAllResourcesByServiceModelInvariantUuid(String serviceModelInvariantUuid, String serviceModelVersion) {
2681         long startTime = System.currentTimeMillis();
2682         LOGGER.debug("Catalog database: getAllResourcesByServiceModelInvariantUuid - " + serviceModelInvariantUuid + ", version=" + serviceModelVersion);
2683
2684         Query query = getSession().createQuery(
2685             "FROM Service WHERE modelInvariantUUID = :serviceModelInvariantUuid and version = :serviceModelVersion");
2686         query.setParameter("serviceModelInvariantUuid", serviceModelInvariantUuid);
2687         query.setParameter("serviceModelVersion", serviceModelVersion);
2688         //TODO make this a unique query
2689         @SuppressWarnings("unchecked")
2690         List<Service> serviceList = query.list();
2691
2692         if (serviceList.isEmpty()) {
2693             LOGGER.debug("Unable to find a Service with serviceModelInvariantUuid=" + serviceModelInvariantUuid + " and serviceModelVersion=" + serviceModelVersion);
2694             return new ServiceMacroHolder();
2695         }
2696
2697         serviceList.sort(new MavenLikeVersioningComparator());
2698         Collections.reverse (serviceList);
2699         Service service = serviceList.get(0);
2700
2701         ServiceMacroHolder smh = new ServiceMacroHolder(service);
2702         ArrayList<NetworkResourceCustomization> nrcList = (ArrayList<NetworkResourceCustomization>) this.getAllNetworksByServiceModelUuid(service.getModelUUID());
2703         smh.setNetworkResourceCustomization(nrcList);
2704         ArrayList<AllottedResourceCustomization> arcList = (ArrayList<AllottedResourceCustomization>) this.getAllAllottedResourcesByServiceModelUuid(service.getModelUUID());
2705         smh.setAllottedResourceCustomization(arcList);
2706         ArrayList<VnfResourceCustomization> vnfList = (ArrayList<VnfResourceCustomization>) this.getAllVnfsByServiceModelUuid(service.getModelUUID());
2707         smh.setVnfResourceCustomizations(vnfList);
2708
2709         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllResourcesByServiceModelUuid with version", null);
2710         return smh;
2711     }
2712
2713     // 1707 New API queries
2714     public NetworkResourceCustomization getSingleNetworkByModelCustomizationUuid(String modelCustomizationUuid) {
2715         LOGGER.debug("Catalog database; getSingleNetworkByModelCustomizationUuid - " + modelCustomizationUuid);
2716         List<NetworkResourceCustomization> resultList = this.getAllNetworksByNetworkModelCustomizationUuid(modelCustomizationUuid);
2717         if (resultList == null || resultList.isEmpty()) {
2718             return null;
2719         }
2720         return resultList.get(0);
2721     }
2722     public AllottedResourceCustomization getSingleAllottedResourceByModelCustomizationUuid(String modelCustomizationUuid) {
2723         LOGGER.debug("Catalog database; getSingleAllottedResourceByModelCustomizationUuid - " + modelCustomizationUuid);
2724         List<AllottedResourceCustomization> resultList = this.getAllAllottedResourcesByArModelCustomizationUuid(modelCustomizationUuid);
2725         if (resultList == null || resultList.isEmpty()) {
2726             return null;
2727         }
2728         return resultList.get(0);
2729     }
2730     @Deprecated
2731     public VnfResource getSingleVnfResourceByModelCustomizationUuid(String modelCustomizationUuid) {
2732         /*
2733         long startTime = System.currentTimeMillis();
2734         LOGGER.debug("Catalog database; getSingleVnfResourceByModelCustomizationUuid - " + modelCustomizationUuid);
2735         List<VnfResource> resultList = this.getAllVnfsByVnfModelCustomizationUuid(modelCustomizationUuid);
2736         if (resultList == null || resultList.size() < 1) {
2737             return null;
2738         }
2739         return resultList.get(0);
2740         */
2741         return null;
2742     }
2743
2744     private void populateNetworkResourceType(List<NetworkResourceCustomization> resultList) {
2745         HashMap<String, NetworkResource> networkResources = new HashMap<>();
2746
2747         for (NetworkResourceCustomization nrc : resultList) {
2748                 String network_id = nrc.getNetworkResourceModelUuid();
2749             if (network_id == null) {
2750                 nrc.setNetworkResource(null);
2751                 nrc.setNetworkType("UNKNOWN_NETWORK_ID_NULL");
2752                 continue;
2753             }
2754             if (networkResources.containsKey(network_id)) {
2755                 nrc.setNetworkResource(networkResources.get(network_id));
2756                         nrc.setNetworkType(networkResources.get(network_id).getModelName());
2757             } else {
2758                 NetworkResource nr = this.getNetworkResourceById(network_id);
2759                 if (nr == null) {
2760                     nrc.setNetworkType("INVALID_NETWORK_TYPE_ID_NOT_FOUND");
2761                 } else {
2762                                 nrc.setNetworkType(nr.getModelName());
2763                     nrc.setNetworkResource(nr);
2764                     networkResources.put(network_id, nr);
2765                 }
2766             }
2767         }
2768     }
2769
2770     /**
2771      * Return a VNF recipe that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME, and ACTION
2772      * first query VF_MODULE table by type, and then use the ID to query
2773      * VNF_RECIPE by VF_MODULE_ID and ACTION
2774      *
2775      * @param vnfType
2776      * @parm vfModuleModelName
2777      * @param action
2778      * @return VnfRecipe object or null if none found
2779      */
2780     public VnfRecipe getVfModuleRecipe (String vnfType, String vfModuleModelName, String action) {
2781         String vfModuleType = vnfType + "::" + vfModuleModelName;
2782
2783         long startTime = System.currentTimeMillis ();
2784         LOGGER.debug ("Catalog database - get VF MODULE  with type " + vfModuleType);
2785
2786         Query query = getSession ().createQuery ("FROM VfModule WHERE type = :type ");
2787         query.setParameter (TYPE, vfModuleType);
2788
2789         @SuppressWarnings("unchecked")
2790         List <VfModule> resultList = query.list ();
2791
2792         if (resultList.isEmpty ()) {
2793             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF Module Entry not found", "CatalogDB", "getVfModuleRecipe", null);
2794             return null;
2795         }
2796
2797         resultList.sort(new MavenLikeVersioningComparator());
2798         Collections.reverse (resultList);
2799
2800         VfModule vfMod = resultList.get(0);
2801
2802         String vfModuleId = vfMod.getModelUUID();
2803
2804         LOGGER.debug ("Catalog database - get VNF recipe with vf module id " + vfModuleId
2805                                       + " and action "
2806                                       + action);
2807
2808         Query query1 = getSession ().createQuery ("FROM VnfRecipe WHERE vfModuleId = :vfModuleId AND action = :action ");
2809         query1.setParameter (VF_MODULE_MODEL_UUID, vfModuleId);
2810         query1.setParameter (ACTION, action);
2811
2812         @SuppressWarnings("unchecked")
2813         List <VnfRecipe> resultList1 = query1.list ();
2814
2815         if (resultList1.isEmpty ()) {
2816             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVfModuleRecipe", null);
2817             return null;
2818         }
2819
2820         resultList1.sort(new MavenLikeVersioningComparator());
2821         Collections.reverse (resultList1);
2822
2823         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe found", "CatalogDB", "getVfModuleRecipe", null);
2824         return resultList1.get (0);
2825     }
2826
2827     /**
2828      * Return a VNF Module List that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME,
2829      * ASDC_SERVICE_MODEL_VERSION, MODEL_VERSION, and ACTION
2830      *
2831      * @param vfModuleType
2832      * @parm modelCustomizationUuid
2833      * @param asdcServiceModelVersion
2834      * @param modelVersion
2835      * @param action
2836      * @return VfModule list
2837      */
2838     public List<VfModule> getVfModule (String vfModuleType, String modelCustomizationUuid, String asdcServiceModelVersion, String modelVersion, String action) {
2839         StringBuilder hql;
2840         Query query;
2841         if(modelCustomizationUuid != null){
2842             hql = new StringBuilder ("FROM VfModule WHERE modelCustomizationUuid = :modelCustomizationUuid AND version = :version");
2843
2844             LOGGER.debug ("Catalog database - get VF MODULE  with type " + vfModuleType + ", asdcServiceModelVersion " + asdcServiceModelVersion + ", modelVersion " + modelVersion);
2845
2846             query = getSession ().createQuery (hql.toString ());
2847             query.setParameter ("modelCustomizationUuid", modelCustomizationUuid);
2848             query.setParameter ("version", asdcServiceModelVersion);
2849         }else{
2850             hql = new StringBuilder ("FROM VfModule WHERE type = :type AND version = :version AND modelVersion = :modelVersion");
2851
2852             LOGGER.debug ("Catalog database - get VF MODULE  with type " + vfModuleType + ", asdcServiceModelVersion " + asdcServiceModelVersion + ", modelVersion " + modelVersion);
2853
2854             query = getSession ().createQuery (hql.toString ());
2855             query.setParameter (TYPE, vfModuleType);
2856             query.setParameter ("version", asdcServiceModelVersion);
2857             query.setParameter ("modelVersion", modelVersion);
2858         }
2859
2860         @SuppressWarnings("unchecked")
2861         List <VfModule> resultList = query.list ();
2862         return resultList;
2863     }
2864
2865     
2866     /**
2867      * Return a VNF COMPONENTSrecipe that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME,
2868      * MODEL_CUSTOMIZATION_UUID, ASDC_SERVICE_MODEL_VERSION, MODEL_VERSION, and ACTION
2869      * first query VF_MODULE table by type, and then use the ID to query
2870      * VNF_COMPONENTS_RECIPE by VF_MODULE_ID and ACTION
2871      *
2872      * @param vnfType
2873      * @parm vfModuleModelName
2874      * @param action
2875      * @return VnfRecipe object or null if none found
2876      */
2877     public VnfComponentsRecipe getVnfComponentsRecipe (String vnfType, String vfModuleModelName, String modelCustomizationUuid, String asdcServiceModelVersion, String modelVersion, String action) {
2878         String vfModuleType = vnfType + "::" + vfModuleModelName;
2879         long startTime = System.currentTimeMillis ();
2880         List <VfModule> resultList = getVfModule(vfModuleType, modelCustomizationUuid,  asdcServiceModelVersion,  modelVersion,  action);
2881
2882         if (resultList.isEmpty ()) {
2883             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF Module Entry not found", "CatalogDB", "getVnfComponentsRecipe", null);
2884             return null;
2885         }
2886
2887         resultList.sort(new MavenLikeVersioningComparator());
2888         Collections.reverse (resultList);
2889
2890         VfModule vfMod = resultList.get(0);
2891
2892         String vfModuleId = vfMod.getModelUUID();
2893
2894         LOGGER.debug ("Catalog database - get Vnf Components recipe with vf module id " + vfModuleId
2895                 + " and action "
2896                 + action);
2897
2898         Query query1 = getSession ().createQuery (
2899             "FROM VnfComponentsRecipe WHERE vfModuleId = :vfModuleId AND action = :action ");
2900         query1.setParameter (VF_MODULE_MODEL_UUID, vfModuleId);
2901         query1.setParameter (ACTION, action);
2902
2903         @SuppressWarnings("unchecked")
2904         List <VnfComponentsRecipe> resultList1 = query1.list ();
2905
2906         if (resultList1.isEmpty ()) {
2907             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfComponentsRecipe", null);
2908             return null;
2909         }
2910
2911         resultList1.sort(new MavenLikeVersioningComparator());
2912         Collections.reverse (resultList1);
2913
2914         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe found", "CatalogDB", "getVnfComponentsRecipe", null);
2915         if (resultList1.size() > 1 && (!resultList1. get (0).getOrchestrationUri().equals(resultList1.get (1).getOrchestrationUri ()))) {
2916             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);
2917             return null;
2918         }
2919         return resultList1.get (0);
2920     }
2921
2922     /**
2923      * Return a VNF COMPONENTSrecipe that matches a given VNF_TYPE, VF_MODULE_MODEL_NAME,
2924      * ASDC_SERVICE_MODEL_VERSION, MODEL_VERSION, and ACTION
2925      * first query VF_MODULE table by type, and then use the ID to query
2926      * VNF_COMPONENTS_RECIPE by VF_MODULE_ID and ACTION
2927      *
2928      * @param vnfType
2929      * @parm vfModuleModelName
2930      * @param action
2931      * @return VnfRecipe object or null if none found
2932      */
2933     public VnfComponentsRecipe getVnfComponentsRecipeByVfModule(List <VfModule> resultList,  String action) {
2934         long startTime = System.currentTimeMillis ();
2935
2936         if (resultList.isEmpty ()) {
2937             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF Module Entry not found", "CatalogDB", "getVnfComponentsRecipe", null);
2938             return null;
2939         }
2940
2941         resultList.sort(new MavenLikeVersioningComparator());
2942         Collections.reverse (resultList);
2943
2944         VfModule vfMod = resultList.get(0);
2945
2946         String vfModuleId = vfMod.getModelName();
2947
2948         LOGGER.debug ("Catalog database - get Vnf Components recipe with vf module id " + vfModuleId
2949                                       + " and action "
2950                                       + action);
2951
2952         Query query1 = getSession ().createQuery (
2953             "FROM VnfComponentsRecipe WHERE vfModuleId = :vfModuleId AND action = :action ");
2954         query1.setParameter (VF_MODULE_MODEL_UUID, vfModuleId);
2955         query1.setParameter (ACTION, action);
2956
2957         @SuppressWarnings("unchecked")
2958         List <VnfComponentsRecipe> resultList1 = query1.list ();
2959
2960         if (resultList1.isEmpty ()) {
2961             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfComponentsRecipe", null);
2962             return null;
2963         }
2964
2965         resultList1.sort(new MavenLikeVersioningComparator());
2966         Collections.reverse (resultList1);
2967
2968         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe found", "CatalogDB", "getVnfComponentsRecipe", null);
2969         if (resultList1.size() > 1 && (!resultList1. get (0).getOrchestrationUri().equals(resultList1.get (1).getOrchestrationUri ()))) {
2970             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);
2971             return null;
2972         }
2973         return resultList1.get (0);
2974     }
2975
2976
2977     /**
2978      * Return all VNF Resources in the Catalog DB
2979      *
2980      * @return A list of VnfResource objects
2981      */
2982     @SuppressWarnings("unchecked")
2983     public List <VnfResource> getAllVnfResources () {
2984
2985         long startTime = System.currentTimeMillis ();
2986         LOGGER.debug ("Catalog database - get all VNF resources");
2987
2988         String hql = "FROM VnfResource";
2989         Query query = getSession ().createQuery (hql);
2990
2991         List <VnfResource> result = query.list ();
2992         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVnfResources", null);
2993         return result;
2994     }
2995
2996     /**
2997      * Return VNF Resources in the Catalog DB that match a given VNF role
2998      *
2999      * @return A list of VnfResource objects
3000      */
3001     @SuppressWarnings("unchecked")
3002     @Deprecated // vnfRole is no longer in VnfResource
3003     public List <VnfResource> getVnfResourcesByRole (String vnfRole) {
3004
3005         long startTime = System.currentTimeMillis ();
3006         LOGGER.debug ("Catalog database - get all VNF resources for role " + vnfRole);
3007
3008         String hql = "FROM VnfResource WHERE vnfRole = :vnfRole";
3009         Query query = getSession ().createQuery (hql);
3010         query.setParameter ("vnfRole", vnfRole);
3011
3012         List <VnfResource> resources = query.list ();
3013         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourcesByRole", null);
3014         return resources;
3015     }
3016
3017     /**
3018      * Return VNF Resources in the Catalog DB that match a given VNF role
3019      *
3020      * @return A list of VnfResource objects
3021      */
3022     @SuppressWarnings("unchecked")
3023     public List<VnfResourceCustomization> getVnfResourceCustomizationsByRole(String vnfRole) {
3024         long startTime = System.currentTimeMillis ();
3025         LOGGER.debug ("Catalog database - get all VNF resource customizations for role " + vnfRole);
3026
3027         String hql = "FROM VnfResourceCustomization WHERE nfRole = :vnfRole";
3028         Query query = getSession ().createQuery (hql);
3029         query.setParameter ("vnfRole", vnfRole);
3030
3031         List <VnfResourceCustomization> resources = query.list ();
3032         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfResourceCustomizationsByRole", null);
3033         return resources;
3034     }
3035
3036     /**
3037      * Return all Network Resources in the Catalog DB
3038      *
3039      * @return A list of NetworkResource objects
3040      */
3041     @SuppressWarnings("unchecked")
3042     public List <NetworkResource> getAllNetworkResources () {
3043
3044         long startTime = System.currentTimeMillis ();
3045         LOGGER.debug ("Catalog database - get all network resources");
3046
3047         String hql = "FROM NetworkResource";
3048         Query query = getSession ().createQuery (hql);
3049
3050         List <NetworkResource> result = query.list ();
3051         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworkResources", null);
3052         return result;
3053     }
3054
3055     @SuppressWarnings("unchecked")
3056     public List<NetworkResourceCustomization> getAllNetworkResourceCustomizations() {
3057         long startTime = System.currentTimeMillis ();
3058         LOGGER.debug ("Catalog database - get all network resource customizations");
3059
3060         String hql = "FROM NetworkResourceCustomization";
3061         Query query = getSession ().createQuery (hql);
3062
3063         List <NetworkResourceCustomization> result = query.list ();
3064         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllNetworkResourceCustomizations", null);
3065         return result;  
3066     }
3067     
3068     /**
3069      * Return all VF Modules in the Catalog DB
3070      *
3071      * @return A list of VfModule objects
3072      */
3073     @SuppressWarnings("unchecked")
3074     public List <VfModule> getAllVfModules () {
3075
3076         long startTime = System.currentTimeMillis ();
3077         LOGGER.debug ("Catalog database - get all vf modules");
3078
3079         String hql = "FROM VfModule";
3080         Query query = getSession ().createQuery (hql);
3081
3082         List <VfModule> result = query.list ();
3083         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVfModules", null);
3084         return result;
3085     }
3086
3087    @SuppressWarnings("unchecked")
3088    public List <VfModuleCustomization> getAllVfModuleCustomizations () {
3089
3090        long startTime = System.currentTimeMillis ();
3091        LOGGER.debug ("Catalog database - get all vf module customizations");
3092
3093        String hql = "FROM VfModuleCustomization";
3094        Query query = getSession ().createQuery (hql);
3095
3096        List <VfModuleCustomization> result = query.list ();
3097        LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllVfModuleCustomizations", null);
3098        return result;
3099    }
3100     
3101
3102     /**
3103      * Return all HeatEnvironment in the Catalog DB
3104      *
3105      * @return A list of HeatEnvironment objects
3106      */
3107     @SuppressWarnings("unchecked")
3108     public List <HeatEnvironment> getAllHeatEnvironment () {
3109
3110         long startTime = System.currentTimeMillis ();
3111         LOGGER.debug ("Catalog database - get all Heat environments");
3112
3113         String hql = "FROM HeatEnvironment";
3114         Query query = getSession ().createQuery (hql);
3115
3116         List <HeatEnvironment> result = query.list ();
3117         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getAllHeatEnvironment", null);
3118         return result;
3119     }
3120
3121     /**
3122      * Fetch the Environment by Environment ID - 1510
3123      */
3124     @Deprecated // no longer in heat envt table
3125     public HeatEnvironment getHeatEnvironment (int id) {
3126
3127         long startTime = System.currentTimeMillis ();
3128         LOGGER.debug ("Catalog database - get Heat environment with id " + id);
3129
3130         String hql = "FROM HeatEnvironment WHERE id = :idValue";
3131
3132         LOGGER.debug ("getHeatEnvironment called with id=" + id);
3133
3134         Query query = getSession ().createQuery (hql);
3135         query.setParameter ("idValue", id);
3136
3137         @SuppressWarnings("unchecked")
3138         List <HeatEnvironment> resultList = query.list ();
3139
3140         // See if something came back.
3141         if (resultList.isEmpty ()) {
3142             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat environment not found", "CatalogDB", "getHeatEnvironment", null);
3143             return null;
3144         }
3145         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatEnvironment", null);
3146         return resultList.get (0);
3147     }
3148
3149     /**
3150      * Fetch the nested templates - 1510
3151      */
3152
3153     @Deprecated
3154     public Map <String, Object> getNestedTemplates (int templateId) {
3155         Map <String, Object> nestedTemplates;
3156         long startTime = System.currentTimeMillis ();
3157         LOGGER.debug ("Catalog database - getNestedTemplates called with templateId " + templateId);
3158
3159         String hql = "FROM HeatNestedTemplate where parent_template_id = :parentIdValue";
3160
3161         Query query = getSession ().createQuery (hql);
3162         query.setParameter ("parentIdValue", templateId);
3163
3164         @SuppressWarnings("unchecked")
3165         List <HeatNestedTemplate> resultList = query.list ();
3166         // If nothing comes back, there are no nested templates
3167         if (resultList.isEmpty ()) {
3168             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No nestedTemplate found", "CatalogDB", "getNestedTemplates", null);
3169             LOGGER.debug ("No nestedTemplates found for templateId=" + templateId + ", " + hql);
3170             return null;
3171         }
3172         // Now, for each entry in NESTED_HEAT_TEMPLATES, we need to grab the template body from HEAT_TEMPLATE
3173         nestedTemplates = new HashMap <> ();
3174         for (HeatNestedTemplate hnt : resultList) {
3175             LOGGER.debug ("Querying for " + hnt);
3176             HeatTemplate ht = this.getHeatTemplate (hnt.getChildTemplateId ());
3177             if (ht == null) {
3178                 LOGGER.debug ("No template found matching childTemplateId=" + hnt.getChildTemplateId ());
3179                 continue;
3180             }
3181             String providerResourceFile = hnt.getProviderResourceFile ();
3182             String heatTemplateBody = ht.getTemplateBody ();
3183             if (providerResourceFile != null && heatTemplateBody != null) {
3184                 nestedTemplates.put (providerResourceFile, heatTemplateBody);
3185             } else {
3186                 LOGGER.debug ("providerResourceFile or heatTemplateBody were null - do not add to HashMap!");
3187             }
3188         }
3189         // Make sure we're not returning an empty map - if so, just return null
3190         if (nestedTemplates.isEmpty ()) {
3191             LOGGER.debug ("nestedTemplates is empty - just return null");
3192             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Nested template is empty", "CatalogDB", "getNestedTemplate", null);
3193             return null;
3194         }
3195         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedTemplate", null);
3196         return nestedTemplates;
3197     }
3198     /**
3199      * Return a Map<String, Object> for returning the child templates and their contents
3200      * 
3201      * @param parentHeatTemplateId
3202      * @return Map<String,Object> or null if none found
3203      */
3204     public Map <String, Object> getNestedTemplates (String parentHeatTemplateId) {
3205         Map <String, Object> nestedTemplates;
3206         long startTime = System.currentTimeMillis ();
3207         LOGGER.debug ("Catalog database - getNestedTemplates called with parentTemplateId " + parentHeatTemplateId);
3208
3209         String hql = "FROM HeatNestedTemplate where parentTemplateId = :parentHeatTemplateId";
3210
3211         Query query = getSession ().createQuery (hql);
3212         query.setParameter ("parentHeatTemplateId", parentHeatTemplateId);
3213
3214         @SuppressWarnings("unchecked")
3215         List <HeatNestedTemplate> resultList = query.list ();
3216         // If nothing comes back, there are no nested templates
3217         if (resultList.isEmpty ()) {
3218             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No nestedTemplate found", "CatalogDB", "getNestedTemplates", null);
3219             LOGGER.debug ("No nestedTemplates found for templateId=" + parentHeatTemplateId + ", " + hql);
3220             return null;
3221         }
3222         // Now, for each entry in NESTED_HEAT_TEMPLATES, we need to grab the template body from HEAT_TEMPLATE
3223         nestedTemplates = new HashMap <> ();
3224         for (HeatNestedTemplate hnt : resultList) {
3225             LOGGER.debug ("Querying for " + hnt);
3226             HeatTemplate ht = this.getHeatTemplateByArtifactUuid (hnt.getChildTemplateId ());
3227             if (ht == null) {
3228                 LOGGER.debug ("No template found matching childTemplateId=" + hnt.getChildTemplateId ());
3229                 continue;
3230             }
3231             String providerResourceFile = hnt.getProviderResourceFile ();
3232             String heatTemplateBody = ht.getTemplateBody ();
3233             if (providerResourceFile != null && heatTemplateBody != null) {
3234                 nestedTemplates.put (providerResourceFile, heatTemplateBody);
3235             } else {
3236                 LOGGER.debug ("providerResourceFile or heatTemplateBody were null - do not add to HashMap!");
3237             }
3238         }
3239         // Make sure we're not returning an empty map - if so, just return null
3240         if (nestedTemplates.isEmpty ()) {
3241             LOGGER.debug ("nestedTemplates is empty - just return null");
3242             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Nested template is empty", "CatalogDB", "getNestedTemplate", null);
3243             return null;
3244         }
3245         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedTemplate", null);
3246         return nestedTemplates;
3247     }
3248
3249     /*
3250      * Fetch any files in the HEAT_FILES table 1510
3251      */
3252     @Deprecated
3253     public Map <String, HeatFiles> getHeatFiles (int vnfResourceId) {
3254        Map <String, HeatFiles> heatFiles;
3255
3256         long startTime = System.currentTimeMillis ();
3257         LOGGER.debug ("Catalog database - getHeatFiles called with vnfResourceId " + vnfResourceId);
3258         String hql = "FROM HeatFiles where vnf_resource_id = :vnfResourceIdValue";
3259
3260         Query query = getSession ().createQuery (hql);
3261         query.setParameter ("vnfResourceIdValue", vnfResourceId);
3262
3263         @SuppressWarnings("unchecked")
3264         List <HeatFiles> resultList = query.list ();
3265         // If nothing comes back, there are no heat files
3266         if (resultList.isEmpty ()) {
3267             LOGGER.debug ("No heatFiles found for vnfResourceId=" + vnfResourceId);
3268             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No heat files", "CatalogDB", "getHeatFiles", null);
3269             return null;
3270         }
3271         // Now, we just need to return a HashMap (key=fileName, object=fileBody)
3272         heatFiles = new HashMap <> ();
3273         for (HeatFiles hf : resultList) {
3274             LOGGER.debug ("Adding " + hf.getFileName () + "->" + hf.getFileBody ());
3275             heatFiles.put (hf.getFileName (), hf);
3276         }
3277         // Make sure we're not returning an empty map - if so, just return null
3278         if (heatFiles.isEmpty ()) {
3279             LOGGER.debug ("heatFiles is empty - just return null");
3280             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat files is empty", "CatalogDB", "getHeatFiles", null);
3281             return null;
3282         }
3283         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFiles", null);
3284         return heatFiles;
3285     }
3286
3287     // New 1607 - with modularization, use new table to determine which HEAT_FILES entries to attach
3288     @Deprecated
3289     public Map <String, HeatFiles> getHeatFilesForVfModule(int vfModuleId) {
3290         /*
3291         Map <String, HeatFiles> heatFiles = null;
3292
3293         long startTime = System.currentTimeMillis ();
3294         LOGGER.debug ("Catalog database - getHeatFilesForVfModule called with vfModuleId " + vfModuleId);
3295         String hql = "FROM VfModuleToHeatFiles where vf_module_id = :vfModuleIdValue";
3296
3297         Query query = getSession ().createQuery (hql);
3298         query.setParameter ("vfModuleIdValue", vfModuleId);
3299
3300         List<VfModuleToHeatFiles> mapList = query.list();
3301         if (mapList.isEmpty()) {
3302             LOGGER.debug ("No heatFiles found for vfModuleId=" + vfModuleId);
3303             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No heatfiles found for vfModule", "CatalogDB", "getHeatFilesForVfModule", null);
3304             return null;
3305         }
3306         //Now the fun part - we have a list of the heat files we need to get - could clean this up with a join
3307         heatFiles = new HashMap<String, HeatFiles>();
3308         for (VfModuleToHeatFiles vmthf : mapList) {
3309                 int heatFilesId = vmthf.getHeatFilesId();
3310                 hql = "FROM HeatFiles where id = :id_value";
3311                 query = getSession().createQuery(hql);
3312                 query.setParameter("id_value", heatFilesId);
3313                 List<HeatFiles> fileList = query.list();
3314                 if (fileList.isEmpty()) {
3315                         // Should this throw an exception??
3316                         LOGGER.debug("Unable to find a HEAT_FILES entry at " + heatFilesId);
3317                 String errorString = "_ERROR|" + heatFilesId;
3318                         // The receiving code needs to know to throw an exception for this - or ignore it.
3319                         heatFiles.put(errorString, null);
3320                 } else {
3321                         // Should only ever have 1 result - add it to our Map
3322                         LOGGER.debug("Retrieved " + fileList.size() + " heat file entry at " + heatFilesId);
3323                         for (HeatFiles hf : fileList) {
3324                                 LOGGER.debug("Adding " + hf.getFileName() + "->" + hf.getFileBody());
3325                                 heatFiles.put(hf.getFileName(), hf);
3326                         }
3327                 }
3328         }
3329         if (heatFiles.isEmpty()) {
3330             LOGGER.debug ("heatFiles is empty - just return null");
3331             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles is empty", "CatalogDB", "getHeatFilesForVfModule", null);
3332             return null;
3333         }
3334         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFilesForVfModule", null);
3335         return heatFiles;
3336         */
3337         return null;
3338     }
3339     
3340     /**
3341      * Return a VfModuleToHeatFiles object 
3342      * 
3343      * @param vfModuleModelUuid, heatFilesArtifactUuid
3344      * @return VfModuleToHeatFiles or null if none found
3345      */ 
3346     public VfModuleToHeatFiles getVfModuleToHeatFilesEntry(String vfModuleModelUuid, String heatFilesArtifactUuid) {
3347
3348         LOGGER.debug ("Catalog database - getVfModuleToHeatFilesEntry with vfModuleModelUuid " + vfModuleModelUuid + ", heatFilesArtifactUuid=" + heatFilesArtifactUuid);
3349         String hql = "FROM VfModuleToHeatFiles where vfModuleModelUuid = :vfModuleModelUuidValue and heatFilesArtifactUuid = :heatFilesArtifactUuidValue";
3350         
3351         HashMap<String, String> parameters = new HashMap<>();
3352         parameters.put("vfModuleModelUuidValue", vfModuleModelUuid);
3353         parameters.put("heatFilesArtifactUuidValue", heatFilesArtifactUuid);
3354         
3355         VfModuleToHeatFiles vmthf = null;
3356         
3357         try {
3358                 vmthf = this.executeQuerySingleRow(hql, parameters, true);
3359         } catch (Exception e) {
3360                 throw e;
3361         }
3362         return vmthf;
3363     }
3364
3365     
3366     /**
3367      * Return a ServiceToResourceCustomization object 
3368      * 
3369      * @param serviceModelUuid
3370      * @param resourceModelCustomizationUuid
3371      * @param modelType
3372      * @return VfModuleToHeatFiles or null if none found
3373      */ 
3374     public ServiceToResourceCustomization getServiceToResourceCustomization(String serviceModelUuid, String resourceModelCustomizationUuid, String modelType) {
3375
3376         LOGGER.debug ("Catalog database - getServiceToResourceCustomization with serviceModelUuid=" + serviceModelUuid + ", resourceModelCustomizationUuid=" + resourceModelCustomizationUuid + ", modelType=" + modelType);
3377         String hql = "FROM ServiceToResourceCustomization where serviceModelUUID = :serviceModelUuidValue and resourceModelCustomizationUUID = :resourceModelCustomizationUuidValue and modelType = :modelTypeValue ";
3378         
3379         HashMap<String, String> parameters = new HashMap<>();
3380         parameters.put("serviceModelUuidValue", serviceModelUuid);
3381         parameters.put("resourceModelCustomizationUuidValue", resourceModelCustomizationUuid);
3382         parameters.put("modelTypeValue", modelType);
3383         
3384         ServiceToResourceCustomization strc = null;
3385         
3386         try {
3387                 strc = this.executeQuerySingleRow(hql, parameters, true);
3388         } catch (Exception e) {
3389                 throw e;
3390         }
3391         return strc;
3392     }
3393
3394     /**
3395      * Return a Map<String, HeatFiles> for returning the heat files associated with a vfModule 1707
3396      * 
3397      * @param vfModuleModelUuid
3398      * @return Map<String,Object> or null if none found
3399      */ 
3400     public Map <String, HeatFiles> getHeatFilesForVfModule(String vfModuleModelUuid) {
3401         Map <String, HeatFiles> heatFiles;
3402
3403         long startTime = System.currentTimeMillis ();
3404         LOGGER.debug ("Catalog database - getHeatFilesForVfModule called with vfModuleModelUuid " + vfModuleModelUuid);
3405         String hql = "FROM VfModuleToHeatFiles where vfModuleModelUuid = :vfModuleModelUuidValue";
3406
3407         Query query = getSession ().createQuery (hql);
3408         query.setParameter ("vfModuleModelUuidValue", vfModuleModelUuid);
3409        
3410         @SuppressWarnings("unchecked")
3411         List<VfModuleToHeatFiles> mapList = query.list();
3412         if (mapList.isEmpty()) {
3413             LOGGER.debug ("No heatFiles found for vfModuleModelUuid=" + vfModuleModelUuid);
3414             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. No heatfiles found for vfModule", "CatalogDB", "getHeatFilesForVfModule", null);
3415             return null;
3416         }
3417         //Now the fun part - we have a list of the heat files we need to get - could clean this up with a join
3418         heatFiles = new HashMap<>();
3419         for (VfModuleToHeatFiles vmthf : mapList) {
3420                 String heatFilesUuid = vmthf.getHeatFilesArtifactUuid();
3421                 hql = "FROM HeatFiles where artifactUuid = :heatFilesUuidValue";
3422                 query = getSession().createQuery(hql);
3423                 query.setParameter("heatFilesUuidValue", heatFilesUuid);
3424                 @SuppressWarnings("unchecked")
3425                 List<HeatFiles> fileList = query.list();
3426                 if (fileList.isEmpty()) {
3427                         // Should this throw an exception??
3428                         LOGGER.debug("Unable to find a HEAT_FILES entry at " + heatFilesUuid);
3429                 String errorString = "_ERROR|" + heatFilesUuid;
3430                         // The receiving code needs to know to throw an exception for this - or ignore it.
3431                         heatFiles.put(errorString, null);
3432                 } else {
3433                         // Should only ever have 1 result - add it to our Map
3434                         LOGGER.debug("Retrieved " + fileList.size() + " heat file entry at " + heatFilesUuid);
3435                         for (HeatFiles hf : fileList) {
3436                                 LOGGER.debug("Adding " + hf.getFileName() + "->" + hf.getFileBody());
3437                                 heatFiles.put(hf.getFileName(), hf);
3438                         }
3439                 }
3440         }
3441         if (heatFiles.isEmpty()) {
3442             LOGGER.debug ("heatFiles is empty - just return null");
3443             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles is empty", "CatalogDB", "getHeatFilesForVfModule", null);
3444             return null;
3445         }
3446         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFilesForVfModule", null);
3447         return heatFiles;       
3448     }
3449
3450     /**
3451      * Get the heat template object based on asdc attributes
3452      *
3453      * @param templateName The template name, generally the yaml filename. "example.yaml"
3454      * @param version The version as specified by ASDC. "1.1"
3455      * @param asdcResourceName The ASDC resource name provided in the ASDC artifact
3456      *
3457      * @return The HeatTemplate
3458      */
3459     @Deprecated // asdcResourceName is no longer in heatTeamplate
3460     public HeatTemplate getHeatTemplate (String templateName, String version, String asdcResourceName) {
3461
3462         long startTime = System.currentTimeMillis ();
3463         LOGGER.debug ("Catalog database - getHeatTemplate with name " + templateName
3464                                       + " and version "
3465                                       + version
3466                                       + " and ASDC resource name "
3467                                       + asdcResourceName);
3468
3469         String hql = "FROM HeatTemplate WHERE templateName = :template_name AND version = :version AND asdcResourceName = :asdcResourceName";
3470         Query query = getSession ().createQuery (hql);
3471         query.setParameter ("template_name", templateName);
3472         query.setParameter ("version", version);
3473         query.setParameter ("asdcResourceName", asdcResourceName);
3474
3475         @SuppressWarnings("unchecked")
3476         List <HeatTemplate> resultList = query.list ();
3477
3478         // See if something came back.
3479         if (resultList.isEmpty ()) {
3480             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Heat template not found", "CatalogDB", "getHeatTemplate", null);
3481             return null;
3482         }
3483         // Name + Version is unique, so should only be one element
3484         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
3485         return resultList.get (0);
3486     }
3487
3488
3489     /**
3490      * Save the Heat Template
3491      *
3492      * @param heat The heat template
3493      * @param paramSet The list of heat template parameters
3494      */
3495     public void saveHeatTemplate (HeatTemplate heat, Set <HeatTemplateParam> paramSet) {
3496
3497         long startTime = System.currentTimeMillis ();
3498         LOGGER.debug ("Catalog database - save Heat Template with name " + heat.getTemplateName() + ", artifactUUID=" + heat.getArtifactUuid());
3499
3500         heat.setParameters(null);
3501         try {
3502             
3503             HeatTemplate heatTemp = this.getHeatTemplateByArtifactUuidRegularQuery(heat.getArtifactUuid());
3504             
3505             if (heatTemp == null) {
3506                 this.getSession ().save (heat);
3507
3508                 if (paramSet != null) {
3509                         StringBuilder sb = new StringBuilder("Parameters: ");
3510                     for (HeatTemplateParam param : paramSet) {
3511                         param.setHeatTemplateArtifactUuid(heat.getArtifactUuid());
3512                         sb.append(param.getParamName()).append(", ");
3513                     }
3514                     LOGGER.debug(sb.toString());
3515                     heat.setParameters (paramSet);
3516                     try {
3517                         Session session = this.getSession();
3518                         if (!(session.isConnected() && session.isOpen())) {
3519                                 LOGGER.debug("Initial session is not connected or open - get another");
3520                                 session = this.getSession();
3521                         }
3522                         session.save(heat);
3523                     } catch (HibernateException he1) {
3524                         LOGGER.debug("Hibernate Exception encountered on first attempt at save(heat) - try again..." + he1.getMessage(), he1);
3525                         try {
3526                                 Session session = this.getSession();
3527                                 session.save(heat);
3528                         } catch (HibernateException he2) {
3529                                 LOGGER.debug("Hibernate Exception encountered on second attempt at save(heat)" + he2.getMessage());
3530                                 LOGGER.debug(Arrays.toString(he2.getStackTrace()));
3531                                 throw he2;
3532                         } catch (Exception e2) {
3533                                 LOGGER.debug("General Exception encountered on second attempt at save(heat)..." + e2.getMessage(),e2);
3534                                 LOGGER.debug(Arrays.toString(e2.getStackTrace()));
3535                                 throw e2;
3536                         }
3537                         
3538                     } catch (Exception e1) {
3539                         LOGGER.debug("General Exception encountered on first attempt at save(heat) - try again..." + e1.getMessage(), e1);
3540                         LOGGER.debug(Arrays.toString(e1.getStackTrace()));
3541                         try {
3542                                 Session session = this.getSession();
3543                                 session.save(heat);
3544                         } catch (HibernateException he2) {
3545                                 LOGGER.debug("General Exception encountered on second attempt at save(heat)" + he2.getMessage(), he2);
3546                                 LOGGER.debug(Arrays.toString(he2.getStackTrace()));
3547                                 throw he2;
3548                         } catch (Exception e2) {
3549                                 LOGGER.debug("General Exception encountered on second attempt at save(heat)..." + e2.getMessage(), e2);
3550                                 LOGGER.debug(Arrays.toString(e2.getStackTrace()));
3551                                 throw e2;
3552                         }
3553                     }
3554                 }
3555
3556             } else {
3557                 heat.setArtifactUuid(heatTemp.getArtifactUuid());
3558             }
3559         } finally {
3560             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
3561         }
3562     }
3563
3564     /**
3565      * Retrieves a Heat environment from DB based on its unique key.
3566      *
3567      * @param name the environment artifact name
3568      * @param version the environment resource version
3569      * @param asdcResourceName the environment resource name
3570      * @return the heat environment from DB or null if not found
3571      */
3572     @Deprecated
3573     public HeatEnvironment getHeatEnvironment (String name, String version, String asdcResourceName) {
3574         long startTime = System.currentTimeMillis ();
3575         LOGGER.debug ("Catalog database - get Heat environment with name " + name
3576                                       + " and version "
3577                                       + version
3578                                       + " and ASDC resource name "
3579                                       + asdcResourceName);
3580
3581         String hql = "FROM HeatEnvironment WHERE name=:name AND version=:version AND asdcResourceName=:asdcResourceName";
3582         Query query = getSession ().createQuery (hql);
3583         query.setParameter ("name", name);
3584         query.setParameter ("version", version);
3585         query.setParameter ("asdcResourceName", asdcResourceName);
3586         HeatEnvironment env = null;
3587         try {
3588                 env = (HeatEnvironment) query.uniqueResult ();
3589         } catch (org.hibernate.NonUniqueResultException nure) {
3590                 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, nure);
3591                 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);
3592                 env = null;
3593         } catch (org.hibernate.HibernateException he) {
3594                 LOGGER.debug("Hibernate Exception - while searching for: envName='" + name + "', asdc_service_model_version='" + version + "' and asdcResourceName=" + asdcResourceName, he);
3595                 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);
3596                 env = null;
3597         } catch (Exception e) {
3598                 LOGGER.debug("Generic Exception - while searching for: envName='" + name + "', asdc_service_model_version='" + version + "' and asdcResourceName=" + asdcResourceName, e);
3599                 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);
3600                 env = null;
3601         }
3602         if (env == null) {
3603                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getHeatTemplate", null);
3604         } else {
3605                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
3606         }
3607         return env;
3608     }
3609
3610     /**
3611      * Retrieves a Heat environment from DB based on its unique key. 1707
3612      *
3613      * @param artifactUuid the environment artifact name
3614      * @param version the environment resource version
3615      * @return the heat environment from DB or null if not found
3616      */
3617     public HeatEnvironment getHeatEnvironment (String artifactUuid, String version) {
3618         long startTime = System.currentTimeMillis ();
3619         LOGGER.debug ("Catalog database - get Heat environment with uuid " + artifactUuid
3620                                       + " and version "
3621                                       + version);
3622
3623         String hql = "FROM HeatEnvironment WHERE artifactUuid=:artifactUuid AND version=:version";
3624         Query query = getSession ().createQuery (hql);
3625         query.setParameter ("artifactUuid", artifactUuid);
3626         query.setParameter ("version", version);
3627         HeatEnvironment env = null;
3628         try {
3629                 env = (HeatEnvironment) query.uniqueResult ();
3630         } catch (org.hibernate.NonUniqueResultException nure) {
3631                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: envName='" + artifactUuid + "', version='" + version);
3632                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for artifactUUID=" + artifactUuid + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "non unique result for ArtifactUUID=" + artifactUuid);
3633                 throw nure;
3634         } catch (org.hibernate.HibernateException he) {
3635                 LOGGER.debug("Hibernate Exception - while searching for: artifactUUID='" + artifactUuid + "', asdc_service_model_version='" + version + " " + he.getMessage() );
3636                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for artifactUUID=" + artifactUuid + " and version=" + version , "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for artifactUUID=" + artifactUuid);
3637                 throw he;
3638         } catch (Exception e) {
3639                 LOGGER.debug("Generic Exception - while searching for: artifactUUID='" + artifactUuid + "', asdc_service_model_version='" + version  + " " + e.getMessage());
3640                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for artifactUUID=" + artifactUuid + " and version=" + version, "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for artifactUUID=" + artifactUuid);
3641                 throw e;
3642         }
3643         if (env == null) {
3644                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getHeatTemplate", null);
3645         } else {
3646                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatTemplate", null);
3647         }
3648         return env;
3649     }
3650
3651     /**
3652      * Save the HeatEnvironment
3653      *
3654      * @param env The Environment
3655      */
3656     public void saveHeatEnvironment (HeatEnvironment env) {
3657         long startTime = System.currentTimeMillis ();
3658         LOGGER.debug ("Catalog database - save Heat environment with name "
3659                                       + env.getEnvironment() + " and ArtifactUUID " + env.getArtifactUuid());
3660         try {
3661             HeatEnvironment dbEnv = getHeatEnvironment (env.getArtifactUuid(), env.getVersion ());
3662             if (dbEnv == null) {
3663
3664                 this.getSession ().save (env);
3665
3666             } else {
3667                 env.setArtifactUuid(dbEnv.getArtifactUuid());
3668             }
3669
3670         } finally {
3671             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
3672         }
3673     }
3674
3675     /**
3676      * Save the heatTemplate
3677      *
3678      * @param heat The heat template
3679      */
3680     public void saveHeatTemplate (HeatTemplate heat) {
3681         long startTime = System.currentTimeMillis ();
3682         LOGGER.debug ("Catalog database - save Heat template with name " + heat.getTemplateName ());
3683         try {
3684             this.getSession ().update (heat);
3685         } finally {
3686             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatTemplate", null);
3687         }
3688     }
3689
3690     public void saveHeatFile (HeatFiles heatFile) {
3691         long startTime = System.currentTimeMillis ();
3692         LOGGER.debug ("Catalog database - save Heat file with name " + heatFile.getFileName ());
3693         try {
3694             this.getSession ().save (heatFile);
3695         } finally {
3696             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatFile", null);
3697         }
3698     }
3699
3700     public void saveVnfRecipe (VnfRecipe vnfRecipe) {
3701         long startTime = System.currentTimeMillis ();
3702         LOGGER.debug ("Catalog database - save VNF recipe with VNF type " + vnfRecipe.getVnfType ());
3703         try {
3704             this.getSession ().save (vnfRecipe);
3705         } finally {
3706             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfRecipe", null);
3707         }
3708     }
3709
3710     public void saveVnfComponentsRecipe (VnfComponentsRecipe vnfComponentsRecipe) {
3711         long startTime = System.currentTimeMillis ();
3712         LOGGER.debug ("Catalog database - save VNF Component recipe with VNF type " + vnfComponentsRecipe.getVnfType ());
3713         try {
3714             this.getSession ().save (vnfComponentsRecipe);
3715         } finally {
3716             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfComponentsRecipe", null);
3717         }
3718     }
3719
3720
3721     public void saveOrUpdateVnfResource (VnfResource vnfResource) {
3722         long startTime = System.currentTimeMillis ();
3723         LOGGER.debug ("Catalog database - save VNF Resource with VNF type " + vnfResource.getModelName());
3724         try {
3725
3726                 VnfResource existing = this.getVnfResourceByModelUuid(vnfResource.getModelUuid());
3727                 if (existing == null) {
3728                         LOGGER.debug("No existing entry found - attempting to save...");
3729                 this.getSession ().save (vnfResource);
3730                 } else {
3731                         LOGGER.debug("Existing vnf resource found!");
3732             }
3733
3734         } finally {
3735             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVnfResource", null);
3736         }
3737     }
3738
3739     public boolean saveVnfResourceCustomization (VnfResourceCustomization vnfResourceCustomization) {
3740         long startTime = System.currentTimeMillis ();
3741         LOGGER.debug ("Catalog database - save VNF Resource Customization with Name " + vnfResourceCustomization.getModelInstanceName());
3742         try {
3743                 LOGGER.debug(vnfResourceCustomization.toString());
3744         } catch (Exception e) {
3745                 LOGGER.debug("Unable to print VRC " + e.getMessage(), e);
3746         }
3747         try {
3748                          // Check if NetworkResourceCustomzation record already exists.  If so, skip saving it.
3749                         // List<NetworkResource> networkResourceList = getAllNetworksByNetworkModelCustomizationUuid(networkResourceCustomization.getModelCustomizationUuid());
3750                          // Do any matching customization records exist?
3751                         // if(networkResourceList.size() == 0){
3752                                                  
3753                                 // networkResourceCustomization.setNetworkResourceModelUuid(networkResource.getModelUuid());
3754         //      this.getSession().flush();
3755         //      this.getSession().clear();
3756                 
3757                 VnfResourceCustomization existing = this.getVnfResourceCustomizationByModelCustomizationUuid(vnfResourceCustomization.getModelCustomizationUuid());
3758                 
3759                 if (existing == null) {
3760                         LOGGER.debug("No existing entry found...attempting to save...");
3761                         this.getSession ().save (vnfResourceCustomization);
3762                         return true;
3763                 }else {
3764                         try {
3765                                 LOGGER.debug("Existing VRC entry found\n" + existing.toString());
3766                         } catch (Exception e) {
3767                                 LOGGER.debug("Unable to print VRC2 " + e.getMessage(), e);
3768                         }
3769                         return false;
3770                 }
3771                                                  
3772         } finally {
3773             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfResourceCustomization", null);
3774         }
3775     }
3776     
3777     public void saveAllottedResourceCustomization (AllottedResourceCustomization resourceCustomization) {
3778         long startTime = System.currentTimeMillis ();
3779         LOGGER.debug ("Catalog database - save Allotted Resource with Name " + resourceCustomization.getModelInstanceName());
3780         try {
3781             List<AllottedResourceCustomization> allottedResourcesList = getAllAllottedResourcesByArModelCustomizationUuid(resourceCustomization.getModelCustomizationUuid());
3782
3783             if(allottedResourcesList.isEmpty()){
3784                 this.getSession ().save(resourceCustomization);
3785             }
3786
3787         } finally {
3788             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateAllottedResourceCustomization", null);
3789         }
3790     }
3791
3792     public void saveAllottedResource (AllottedResource allottedResource) {
3793         long startTime = System.currentTimeMillis ();
3794         LOGGER.debug ("Catalog database - save Allotted Resource with Name " + allottedResource.getModelName());
3795         try { 
3796                 AllottedResource existing = this.getAllottedResourceByModelUuid(allottedResource.getModelUuid());
3797                 if (existing == null) {
3798                         this.getSession ().save (allottedResource);
3799                 } else {
3800                         LOGGER.debug("Found existing allottedResource with this modelUuid - no need to save");
3801                 }
3802          
3803         } finally {
3804             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateAllottedResourceCustomization", null);
3805         }
3806     }
3807     
3808     public void saveNetworkResource (NetworkResource networkResource) throws RecordNotFoundException {
3809         long startTime = System.currentTimeMillis ();
3810         LOGGER.debug ("Catalog database - save Network Resource with Network Name " + networkResource.getModelName());
3811         try {
3812                          // Check if NetworkResourceCustomzation record already exists.  If so, skip saving it.
3813                         // List<NetworkResource> networkResourceList = getAllNetworksByNetworkModelCustomizationUuid(networkResourceCustomization.getModelCustomizationUuid());
3814                          // Do any matching customization records exist?
3815                         if(getNetworkResourceByModelUuid(networkResource.getModelUUID()) == null){
3816                                  this.getSession ().save(networkResource);
3817                         }
3818   
3819         
3820         } finally {
3821             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNetworkResourceCustomization", null);
3822         }
3823     }
3824     
3825     public void saveToscaCsar (ToscaCsar toscaCsar) throws RecordNotFoundException {
3826         
3827
3828         long startTime = System.currentTimeMillis ();
3829         LOGGER.debug ("Catalog database - save Tosca Csar with Name " + toscaCsar.getName());
3830         try {
3831                 
3832                 if(getToscaCsar(toscaCsar.getArtifactChecksum()) == null){
3833                         this.getSession ().save (toscaCsar);
3834                 }
3835                 LOGGER.debug("Temporarily disabling saveToscaCsar pending further investigation 2017-06-02");
3836         
3837         } finally {
3838             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveToscaCsar", null);
3839         }
3840     }
3841     
3842
3843     /**
3844      * Return the newest version of a specific Tosca CSAR Record resource (queried by Name).
3845      *
3846      * @param artifactChecksum
3847      * @return ToscaCsar object or null if none found
3848      */
3849     public ToscaCsar getToscaCsar (String artifactChecksum) {
3850
3851         long startTime = System.currentTimeMillis ();
3852         LOGGER.debug ("Catalog database - get Tosca CSAR record with artifactChecksum " + artifactChecksum);
3853
3854         String hql = "FROM ToscaCsar WHERE artifactChecksum = :artifactChecksum";
3855         Query query = getSession ().createQuery (hql);
3856         query.setParameter ("artifactChecksum", artifactChecksum);
3857
3858         @SuppressWarnings("unchecked")
3859         List <ToscaCsar> resultList = query.list ();
3860
3861         // See if something came back. Name is unique, so
3862         if (resultList.isEmpty ()) {
3863             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Tosca Csar not found", "CatalogDB", "getToscaCsar", null);
3864             return null;
3865         }
3866
3867         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getToscaCsar", null);
3868         return resultList.get (0);
3869     }
3870     
3871     /**
3872      * Return a specific Tosca CSAR Record resource (queried by atrifact uuid).
3873      *
3874      * @param toscaCsarArtifactUUID the artifact uuid of the tosca csar
3875      * @return ToscaCsar object or null if none found
3876      */
3877     public ToscaCsar getToscaCsarByUUID(String toscaCsarArtifactUUID){
3878         long startTime = System.currentTimeMillis ();
3879         LOGGER.debug ("Catalog database - get Tosca CSAR record with artifactUUID " + toscaCsarArtifactUUID);
3880
3881         String hql = "FROM ToscaCsar WHERE artifactUUID = :toscaCsarArtifactUUID";
3882         Query query = getSession ().createQuery (hql);
3883         query.setParameter ("toscaCsarArtifactUUID", toscaCsarArtifactUUID);
3884
3885         @SuppressWarnings("unchecked")
3886         List <ToscaCsar> resultList = query.list ();
3887
3888         // See if something came back. Name is unique, so
3889         if (resultList.isEmpty ()) {
3890             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Tosca Csar not found", "CatalogDB", "getToscaCsarByUUID", null);
3891             return null;
3892         }
3893
3894         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getToscaCsarByUUID", null);
3895         return resultList.get (0);
3896     }
3897
3898     /**
3899      * Return a specific Tosca CSAR Record resource (queried by service model uuid).
3900      * <br>
3901      * 
3902      * @param serviceModelUUID the service model uuid
3903      * @return ToscaCsar object or null if none found
3904      * @since ONAP Beijing Release
3905      */
3906     public ToscaCsar getToscaCsarByServiceModelUUID(String serviceModelUUID){
3907         long startTime = System.currentTimeMillis ();
3908         LOGGER.debug ("Catalog database - get Tosca CSAR record with serviceModelUUID " + serviceModelUUID);
3909         Service service = getServiceByModelUUID(serviceModelUUID);
3910         if(null == service){
3911             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Service not found", "CatalogDB", "getToscaCsarByServiceModelUUID", null);
3912             return null;
3913         }
3914         ToscaCsar csar = getToscaCsarByUUID(service.getToscaCsarArtifactUUID());
3915         if(null == csar){
3916             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Tosca csar of the service not found", "CatalogDB", "getToscaCsarByServiceModelUUID", null);
3917             return null;
3918         }
3919         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getToscaCsarByServiceModelUUID", null);
3920         return csar;
3921     }
3922     
3923     public void saveTempNetworkHeatTemplateLookup (TempNetworkHeatTemplateLookup tempNetworkHeatTemplateLookup) {
3924         long startTime = System.currentTimeMillis ();
3925         LOGGER.debug ("Catalog database - save TempNetworkHeatTemplateLookup with Network Model Name " + tempNetworkHeatTemplateLookup.getNetworkResourceModelName() +
3926                               " and Heat Template Artifact UUID " + tempNetworkHeatTemplateLookup.getHeatTemplateArtifactUuid());
3927         try {
3928                  this.getSession ().save (tempNetworkHeatTemplateLookup);
3929       
3930         } finally {
3931             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveTempNetworkHeatTemplateLookup", null); 
3932         }
3933     }
3934     
3935     public void saveVfModuleToHeatFiles (VfModuleToHeatFiles vfModuleToHeatFiles) {
3936         long startTime = System.currentTimeMillis ();
3937         LOGGER.debug ("Catalog database - save VfModuleToHeatFiles with VF Module UUID " + vfModuleToHeatFiles.getVfModuleModelUuid() +
3938                               " and Heat Files Artifact UUID " + vfModuleToHeatFiles.getHeatFilesArtifactUuid());
3939         try {
3940                 
3941                 this.getSession ().save (vfModuleToHeatFiles);
3942       
3943         } finally {
3944             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVFModuleToHeatFiles", null); 
3945         }
3946     }
3947     
3948     public void saveVnfResourceToVfModuleCustomization(VnfResourceCustomization vnfResourceCustomizationUUID, VfModuleCustomization vfModuleCustomizationUUID) throws RecordNotFoundException {
3949         long startTime = System.currentTimeMillis ();
3950         VnfResCustomToVfModuleCustom vnfResCustomToVfModuleCustom = new VnfResCustomToVfModuleCustom();
3951         
3952         if(vnfResourceCustomizationUUID != null && vfModuleCustomizationUUID != null){
3953                 vnfResCustomToVfModuleCustom.setVnfResourceCustModelCustomizationUuid(vnfResourceCustomizationUUID.getModelCustomizationUuid());
3954                 vnfResCustomToVfModuleCustom.setVfModuleCustModelCustomizationUuid(vfModuleCustomizationUUID.getModelCustomizationUuid());
3955                 String vnfId = vnfResourceCustomizationUUID.getModelCustomizationUuid();
3956                 String vfId = vfModuleCustomizationUUID.getModelCustomizationUuid();
3957                 LOGGER.debug ("Catalog database - save VnfResCustomToVfModuleCustom with vnf=" + vnfId + ", vf=" + vfId);
3958                 try {
3959                         VnfResCustomToVfModuleCustom existing = this.getVnfResCustomToVfModule(vnfId, vfId);
3960                         if (existing == null) {
3961                                 LOGGER.debug("No existing entry found - will now try to save");
3962                                 this.getSession ().save (vnfResCustomToVfModuleCustom);
3963                         } else {
3964                                 LOGGER.debug("Existing entry already found - no save needed");
3965                         }
3966                 } finally {
3967                         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVnfResourceToVfModuleCustomization", null);
3968                 }
3969         }
3970     }
3971     
3972     public void saveNetworkResourceCustomization (NetworkResourceCustomization networkResourceCustomization) throws RecordNotFoundException {
3973         long startTime = System.currentTimeMillis ();
3974         LOGGER.debug ("Catalog database - save Network Resource Customization with Network Name " + networkResourceCustomization.getModelInstanceName());
3975         try {
3976             // Check if NetworkResourceCustomzation record already exists.  If so, skip saving it.
3977             List<NetworkResourceCustomization> networkResourceCustomizationList = getAllNetworksByNetworkModelCustomizationUuid(networkResourceCustomization.getModelCustomizationUuid());
3978             // Do any matching customization records exist?
3979             if(networkResourceCustomizationList.isEmpty()){
3980
3981                 // Retreive the record from the Network_Resource table associated to the Customization record based on ModelName
3982                         // ?? is it modelInstanceName with 1707?
3983                         NetworkResource networkResource = getNetworkResource(networkResourceCustomization.getModelInstanceName());
3984
3985                 if(networkResource == null){
3986                                 throw new RecordNotFoundException("No record found in NETWORK_RESOURCE table for model name " + networkResourceCustomization.getModelInstanceName());
3987                 }
3988
3989                         networkResourceCustomization.setNetworkResourceModelUuid(networkResource.getModelUUID());
3990
3991                 this.getSession ().save(networkResourceCustomization);
3992             }
3993
3994
3995         } finally {
3996             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNetworkResourceCustomization", null);
3997         }
3998     }
3999
4000     @Deprecated  // table is gone - mapped to ServiceToResource
4001     public void saveServiceToNetworks (ServiceToNetworks serviceToNetworks) {
4002         long startTime = System.currentTimeMillis ();
4003         LOGGER.debug ("Catalog database - save to ServiceToNetworks table with NetworkModelCustomizationUUID of " + serviceToNetworks.getNetworkModelCustomizationUuid() + " and ServiceModelUUID of " + serviceToNetworks.getServiceModelUuid());
4004         try {
4005             this.getSession ().save(serviceToNetworks);
4006
4007         } finally {
4008             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNetworkResourceCustomization", null);
4009         }
4010     }
4011
4012     public void saveServiceToResourceCustomization(ServiceToResourceCustomization serviceToResource) {
4013         long startTime = System.currentTimeMillis ();
4014         LOGGER.debug ("Catalog database - save to ServiceToResourceCustomization table with ServiceModelUuid of " + serviceToResource.getServiceModelUUID() + ", ResourceModelUUID of " + serviceToResource.getResourceModelCustomizationUUID() + " and model_type=" + serviceToResource.getModelType());
4015         ServiceToResourceCustomization strc = this.getServiceToResourceCustomization(serviceToResource.getServiceModelUUID(), serviceToResource.getResourceModelCustomizationUUID(), serviceToResource.getModelType());
4016         try {
4017                 if (strc != null) {
4018                         LOGGER.debug("**This ServiceToResourceCustomization record already exists - no need to save");
4019                 } else {
4020                  this.getSession ().save(serviceToResource);
4021                 }
4022         } finally {
4023             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveServiceToResourceCustomization", null);
4024         }
4025     }
4026     
4027     @Deprecated // table is gone - mapped to ServiceToResourceCustomization
4028     public void saveServiceToAllottedResources (ServiceToAllottedResources serviceToAllottedResources) {
4029         long startTime = System.currentTimeMillis ();
4030         LOGGER.debug ("Catalog database - save to serviceToAllottedResources table with ARModelCustomizationUUID of " + serviceToAllottedResources.getArModelCustomizationUuid() + " and ServiceModelUUID of " + serviceToAllottedResources.getServiceModelUuid());
4031         try {
4032             this.getSession ().save(serviceToAllottedResources);
4033
4034         } finally {
4035             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveServiceToAllottedResources", null);
4036         }
4037     }
4038
4039     public void saveService (Service service) {
4040         long startTime = System.currentTimeMillis ();
4041         LOGGER.debug ("Catalog database - save Service with ServiceName/Version/serviceUUID(SERVICE_NAME_VERSION_ID)" + service.getModelName()+"/"+service.getVersion()+"/"+service.getModelUUID());
4042         try {
4043             Service serviceInvariantDB = null;
4044             // Retrieve existing service record by nameVersionId
4045                 Service serviceDB = this.getServiceByModelUUID(service.getModelUUID());
4046             if (serviceDB == null) {
4047                 // Check to see if a record with the same modelInvariantId already exists.  This tells us that a previous version exists and we can copy its recipe Record for the new service record.
4048                 serviceInvariantDB = this.getServiceByInvariantUUID(service.getModelInvariantUUID());
4049                 // Save the new Service record
4050                 this.getSession ().save (service);
4051             }
4052
4053             if(serviceInvariantDB != null){  // existing modelInvariantId was found.
4054                 // copy the recipe record with the matching invariant id.  We will duplicate this for the new service record
4055                 List<ServiceRecipe> serviceRecipes = getServiceRecipes(serviceInvariantDB.getModelUUID());
4056
4057                 if(serviceRecipes != null && ! serviceRecipes.isEmpty()){
4058                     for(ServiceRecipe serviceRecipe : serviceRecipes){
4059                         if(serviceRecipe != null){
4060                             // Fetch the service record that we just added.  We do this so we can extract its Id column value, this will be the foreign key we use in the service recipe table.
4061                                         Service newService = this.getServiceByModelUUID(service.getModelUUID());
4062                             // Create a new ServiceRecipe record based on the existing one we just copied from the DB.
4063                             ServiceRecipe newServiceRecipe = new ServiceRecipe();
4064                             newServiceRecipe.setAction(serviceRecipe.getAction());
4065                             newServiceRecipe.setDescription(serviceRecipe.getDescription());
4066                             newServiceRecipe.setOrchestrationUri(serviceRecipe.getOrchestrationUri());
4067                             newServiceRecipe.setRecipeTimeout(serviceRecipe.getRecipeTimeout());
4068                             newServiceRecipe.setServiceParamXSD(serviceRecipe.getServiceParamXSD());
4069                                         newServiceRecipe.setServiceModelUUID(newService.getModelUUID());
4070                             newServiceRecipe.setVersion(serviceRecipe.getVersion());
4071                                         // Check recipe does not exist before inserting
4072                                         ServiceRecipe recipe = getServiceRecipeByModelUUID(newServiceRecipe.getServiceModelUUID(), newServiceRecipe.getAction());
4073                             // Save the new recipe record in the service_recipe table and associate it to the new service record that we just added.
4074                                         if(recipe == null){
4075                             this.getSession ().save (newServiceRecipe);
4076                         }
4077                     }
4078                 }
4079               }
4080             }
4081
4082                
4083         } finally {
4084             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateService", null);
4085         }
4086     }
4087
4088     public void saveOrUpdateVfModule (VfModule vfModule) {
4089         long startTime = System.currentTimeMillis ();
4090         LOGGER.debug ("Catalog database - save or update VF Module with VF Model Name " + vfModule.getModelName());
4091         VfModule vfModuleInvariantDB = null;
4092         try {
4093                 LOGGER.debug("heat template id = " + vfModule.getHeatTemplateArtifactUUId() + ", vol template id = "+ vfModule.getVolHeatTemplateArtifactUUId());
4094                 LOGGER.debug(vfModule.toString());
4095         } catch (Exception e) {
4096                 LOGGER.debug("unable to print vfmodule " + e.getMessage(), e);
4097         }
4098         try {
4099                 VfModule existing = this.getVfModuleByModelUUID(vfModule.getModelUUID());
4100                 if (existing == null) {
4101                         // Check to see if a record with the same modelInvariantId already exists.  This tells us that a previous version exists and we can copy its recipe Record for the new service record.
4102                         vfModuleInvariantDB = this.getVfModuleByModelInvariantUuid(vfModule.getModelInvariantUUID());
4103                         LOGGER.debug("No existing entry found, attempting to save...");
4104                 this.getSession ().save (vfModule);
4105                 } else {
4106                         try {
4107                                 LOGGER.debug("Found an existing vf module!\n" + existing.toString());
4108                         } catch (Exception e) {
4109                                 LOGGER.debug("unable to print vfmodule2 " + e.getMessage(), e);
4110             }
4111                 }
4112                 
4113             if(vfModuleInvariantDB != null){  // existing modelInvariantId was found.
4114                 // copy the recipe record with the matching invariant id.  We will duplicate this for the new service record                    
4115                 List<VnfComponentsRecipe> vfRecipes = getVnfComponentRecipes(vfModuleInvariantDB.getModelUUID());
4116
4117                 
4118                 if(vfRecipes != null && ! vfRecipes.isEmpty()){
4119                         for(VnfComponentsRecipe vfRecipe : vfRecipes){
4120                                 if(vfRecipe != null){
4121                                         // Fetch the service record that we just added.  We do this so we can extract its Id column value, this will be the foreign key we use in the service recipe table.
4122                                         VfModule newRecipe = this.getVfModuleByModelUUID(vfModule.getModelUUID());
4123                                         // Create a new ServiceRecipe record based on the existing one we just copied from the DB.
4124                                         VnfComponentsRecipe newVnfRecipe = new VnfComponentsRecipe();
4125                                         newVnfRecipe.setAction(vfRecipe.getAction());
4126                                         newVnfRecipe.setDescription(vfRecipe.getDescription());
4127                                         newVnfRecipe.setOrchestrationUri(vfRecipe.getOrchestrationUri());
4128                                         newVnfRecipe.setRecipeTimeout(vfRecipe.getRecipeTimeout());
4129                                         newVnfRecipe.setParamXSD(vfRecipe.getParamXSD());
4130                                         newVnfRecipe.setVfModuleModelUUId(newRecipe.getModelUUID());
4131                                         newVnfRecipe.setVersion(vfRecipe.getVersion());
4132                                         newVnfRecipe.setVnfComponentType(vfRecipe.getVnfComponentType());
4133                                         newVnfRecipe.setVnfType(vfRecipe.getVnfType());
4134                                         // Check recipe does not exist before inserting
4135          //                             VnfComponentsRecipe recipe = getVnfComponentRecipes(newVnfRecipe.getVfModuleModelUUId());
4136                                         List<VnfComponentsRecipe> recipe = getVnfComponentRecipes(newVnfRecipe.getVfModuleModelUUId());
4137                                         // Save the new recipe record in the service_recipe table and associate it to the new service record that we just added.
4138         //                              if(recipe == null){
4139                                                 this.getSession ().save (newVnfRecipe);
4140         //                              }
4141                                 }
4142                         }
4143                 }
4144   
4145              }
4146
4147         } finally {
4148             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVfModule", null);
4149         }
4150     }
4151
4152     public void saveOrUpdateVfModuleCustomization (VfModuleCustomization vfModuleCustomization) {
4153         long startTime = System.currentTimeMillis ();
4154         LOGGER.debug ("Catalog database - save VF Module Customization with VF Customization Model Name UUID " + vfModuleCustomization.getVfModuleModelUuid());
4155         try {
4156                 LOGGER.debug("env id = " + vfModuleCustomization.getHeatEnvironmentArtifactUuid() + ", vol Env=" + vfModuleCustomization.getVolEnvironmentArtifactUuid());
4157                 LOGGER.debug(vfModuleCustomization.toString());
4158         } catch (Exception e) {
4159                 LOGGER.debug("unable to print vfmodulecust " + e.getMessage(), e);
4160         }
4161         try {
4162                 VfModuleCustomization existing = this.getVfModuleCustomizationByModelCustomizationId(vfModuleCustomization.getModelCustomizationUuid());
4163                 if (existing == null) {
4164                         LOGGER.debug("No existing entry found, attempting to save...");
4165                 this.getSession ().save (vfModuleCustomization);
4166                 } else {
4167                         try {
4168                                 LOGGER.debug("Found an existing vf module customization entry\n" + existing.toString());
4169                         } catch (Exception e) {
4170                                 LOGGER.debug("unable to print vfmodulecust2 " + e.getMessage(), e);
4171                 }
4172                 }
4173       
4174         } finally {
4175             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVfModuleCustomization", null); 
4176         }
4177     }
4178
4179     @Deprecated
4180     public HeatNestedTemplate getNestedHeatTemplate(int parentTemplateId, int childTemplateId) {
4181           long startTime = System.currentTimeMillis ();
4182           LOGGER.debug ("Catalog database - get nested Heat template with PerentId-Child Id "
4183                                         + parentTemplateId +"-"+childTemplateId);
4184           try {
4185               HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
4186 //              nestedTemplate.setParentTemplateId (parentTemplateId);
4187 //              nestedTemplate.setChildTemplateId (childTemplateId);
4188               
4189               return (HeatNestedTemplate)session.get (HeatNestedTemplate.class,nestedTemplate);
4190           } finally {
4191               LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedHeatTemplate", null);
4192           }
4193     }
4194     
4195     // 1707 version
4196     public HeatNestedTemplate getNestedHeatTemplate(String parentTemplateId, String childTemplateId) {
4197           long startTime = System.currentTimeMillis ();
4198         LOGGER.debug ("Catalog database - get nested Heat template with PerentId="
4199                                       + parentTemplateId +", ChildId="+childTemplateId);
4200         try {
4201             HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
4202               nestedTemplate.setParentTemplateId (parentTemplateId);
4203               nestedTemplate.setChildTemplateId (childTemplateId);
4204
4205               return (HeatNestedTemplate)session.get (HeatNestedTemplate.class,nestedTemplate);
4206           } finally {
4207               LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNestedHeatTemplate", null);
4208           }
4209     }
4210
4211     @Deprecated
4212     public void saveNestedHeatTemplate (int parentTemplateId, HeatTemplate childTemplate, String yamlFile) {
4213         /*
4214         long startTime = System.currentTimeMillis ();
4215         LOGGER.debug ("Catalog database - save nested Heat template with name "
4216                                       + childTemplate.getTemplateName ());
4217         try {
4218
4219                 saveHeatTemplate(childTemplate, childTemplate.getParameters());
4220                 if (getNestedHeatTemplate(parentTemplateId,childTemplate.getId()) == null) {
4221                     HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
4222                     nestedTemplate.setParentTemplateId (parentTemplateId);
4223                     nestedTemplate.setChildTemplateId (childTemplate.getId ());
4224                     nestedTemplate.setProviderResourceFile (yamlFile);
4225                     session.save (nestedTemplate);
4226                 }
4227         } finally {
4228             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNestedHeatTemplate", null);
4229         }
4230         */
4231     }
4232     
4233     // 1707
4234     public void saveNestedHeatTemplate (String parentTemplateId, HeatTemplate childTemplate, String yamlFile) {
4235         long startTime = System.currentTimeMillis ();
4236         LOGGER.debug ("Catalog database - save nested Heat template with name "
4237                                       + childTemplate.getTemplateName () + ",parentId=" + parentTemplateId + ",childId=" + childTemplate.getArtifactUuid() + ", providerResourceFile=" + yamlFile);
4238         try {
4239       
4240                 saveHeatTemplate(childTemplate, childTemplate.getParameters());
4241                 if (getNestedHeatTemplate(parentTemplateId,childTemplate.getArtifactUuid()) == null) { 
4242                     HeatNestedTemplate nestedTemplate = new HeatNestedTemplate ();
4243                     nestedTemplate.setParentTemplateId (parentTemplateId);
4244                     nestedTemplate.setChildTemplateId (childTemplate.getArtifactUuid ());
4245                     nestedTemplate.setProviderResourceFile (yamlFile);
4246                     session.flush();
4247                     session.save (nestedTemplate);
4248                 }
4249         } finally {
4250             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveNestedHeatTemplate", null);
4251         }
4252     }
4253
4254     @Deprecated
4255     public HeatFiles getHeatFiles(int vnfResourceId,String fileName,String asdcResourceName, String version) {
4256           long startTime = System.currentTimeMillis ();
4257           LOGGER.debug ("Catalog database - getHeatFiles with name " + fileName
4258                                         + " and vnfResourceID "
4259                                         + vnfResourceId
4260 //                                        + " and ASDC resource name "
4261                                         + asdcResourceName
4262                                         + " and version "
4263                                         + version);
4264
4265           String hql = "FROM HeatFiles WHERE fileName = :fileName AND vnfResourceId = :vnfResourceId AND asdcResourceName = :asdcResourceName AND version = :version";
4266           Query query = getSession ().createQuery (hql);
4267           query.setParameter ("fileName", fileName);
4268           query.setParameter ("vnfResourceId", vnfResourceId);
4269           query.setParameter ("asdcResourceName", asdcResourceName);
4270           query.setParameter ("version", version);
4271
4272           @SuppressWarnings("unchecked")
4273
4274           HeatFiles heatFilesResult = null;
4275           try {
4276                   heatFilesResult = (HeatFiles) query.uniqueResult ();
4277           } catch (org.hibernate.NonUniqueResultException nure) {
4278                 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);
4279                 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);
4280                 throw nure;
4281           } catch (org.hibernate.HibernateException he) {
4282                 LOGGER.debug("Hibernate Exception - while searching for: fileName='" + fileName + "', vnfResourceId='" + vnfResourceId + "' and asdcResourceName=" + asdcResourceName + " and version=" + version + " " + he.getMessage());
4283                 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);
4284                 throw he;
4285           } catch (Exception e) {
4286                 LOGGER.debug("Generic Exception - while searching for: fileName='" + fileName + "', vnfResourceId='" + vnfResourceId + "' and asdcResourceName=" + asdcResourceName + " and version=" + version + " " + e.getMessage());
4287                 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);
4288                 throw e;
4289           }
4290
4291           // See if something came back.
4292           if (heatFilesResult == null) {
4293               LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles not found", "CatalogDB", "getHeatFiles", null);
4294               return null;
4295           }
4296           // Name + Version is unique, so should only be one element
4297           LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFiles", null);
4298           return heatFilesResult;
4299     }
4300
4301     public HeatFiles getHeatFiles(String artifactUuid) {
4302           long startTime = System.currentTimeMillis ();
4303         LOGGER.debug ("Catalog database - getHeatFiles with artifactUuid " + artifactUuid);
4304
4305         String hql = "FROM HeatFiles WHERE artifactUuid = :artifactUuid";
4306         Query query = getSession ().createQuery (hql);
4307         query.setParameter ("artifactUuid", artifactUuid);
4308
4309         @SuppressWarnings("unchecked")
4310       
4311         HeatFiles heatFilesResult = null;
4312         try {
4313           heatFilesResult = (HeatFiles) query.uniqueResult ();
4314         } catch (org.hibernate.NonUniqueResultException nure) {
4315                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: artifactUuid='" + artifactUuid );
4316                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for artifactUuid=" + artifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for artifactUuid=" + artifactUuid);
4317                 throw nure;
4318         } catch (org.hibernate.HibernateException he) {
4319                 LOGGER.debug("Hibernate Exception - while searching for: artifactUuid='" + artifactUuid + " " + he.getMessage());
4320                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception searching for artifactUuid=" + artifactUuid, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for artifactUuid=" + artifactUuid);
4321                 throw he;
4322         } catch (Exception e) {
4323                 LOGGER.debug("Generic Exception - while searching for: artifactUuid='" + artifactUuid  + " " + e.getMessage());
4324                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception searching for artifactUuid=" + artifactUuid , "", "", MsoLogger.ErrorCode.DataError, "Generic exception searching for artifactUuid=" + artifactUuid);
4325                 throw e;
4326         } 
4327         
4328         // See if something came back.
4329         if (heatFilesResult == null) {
4330             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. HeatFiles not found", "CatalogDB", "getHeatFiles", null);
4331             return null;
4332         }
4333         // Name + Version is unique, so should only be one element
4334         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getHeatFiles", null);
4335         return heatFilesResult;
4336   }
4337     
4338     public void saveHeatFiles (HeatFiles childFile) {
4339          long startTime = System.currentTimeMillis ();
4340          LOGGER.debug ("Catalog database - save Heat File with name "
4341                                        + childFile.getFileName());
4342          try {
4343 //             HeatFiles heatFiles = getHeatFiles (childFile.getVnfResourceId(), childFile.getFileName(), childFile.getAsdcResourceName (),childFile.getVersion());
4344              HeatFiles heatFiles = getHeatFiles (childFile.getArtifactUuid());
4345              if (heatFiles == null) {
4346
4347                  // asdc_heat_files_save
4348                  this.getSession ().save (childFile);
4349
4350              } else {
4351                  /* replaced 'heatFiles' by 'childFile'
4352                     Based on following comment:
4353                                         It must be childFile.setId instead of heatFiles.setId, we must return the ID if it exists in DB.
4354                                  */
4355                  childFile.setArtifactUuid(heatFiles.getArtifactUuid());
4356              }
4357
4358          } finally {
4359              LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveHeatFiles", null);
4360          }
4361     }
4362
4363     @Deprecated
4364     public void saveVfModuleToHeatFiles (int parentVfModuleId, HeatFiles childFile) {
4365         /*
4366         long startTime = System.currentTimeMillis ();
4367         LOGGER.debug ("Catalog database - save Heat File to VFmodule link "
4368                                       + childFile.getFileName());
4369         try {
4370             saveHeatFiles (childFile);
4371             VfModuleToHeatFiles vfModuleToHeatFile = new VfModuleToHeatFiles ();
4372                 vfModuleToHeatFile.setVfModuleId(parentVfModuleId);
4373                 vfModuleToHeatFile.setHeatFilesId(childFile.getId());
4374
4375                 session.save (vfModuleToHeatFile);
4376
4377         } finally {
4378             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVfModuleToHeatFiles", null);
4379         }
4380         */
4381     }
4382     
4383     public void saveVfModuleToHeatFiles (String parentVfModuleId, HeatFiles childFile) {
4384         long startTime = System.currentTimeMillis ();
4385         LOGGER.debug ("Catalog database - save Heat File to VFmodule link "
4386                                       + childFile.getFileName());
4387         try {
4388             saveHeatFiles (childFile);
4389             VfModuleToHeatFiles checkExistingEntry = this.getVfModuleToHeatFilesEntry(parentVfModuleId, childFile.getArtifactUuid());
4390             if (checkExistingEntry == null) {
4391                 VfModuleToHeatFiles vfModuleToHeatFile = new VfModuleToHeatFiles ();
4392                         vfModuleToHeatFile.setVfModuleModelUuid(parentVfModuleId);
4393                         vfModuleToHeatFile.setHeatFilesArtifactUuid(childFile.getArtifactUuid());
4394                         session.flush();
4395                         session.save (vfModuleToHeatFile);
4396             } else {
4397                 LOGGER.debug("**Found existing VfModuleToHeatFiles entry for " + checkExistingEntry.toString());
4398                 LOGGER.debug("No need to save...");
4399             }
4400           
4401         } finally {
4402             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveVfModuleToHeatFiles", null);
4403         }
4404     }
4405
4406     /**
4407      * Return a Network Resource that matches the Network Customization defined by given MODEL_CUSTOMIZATION_UUID
4408      *
4409      * @param modelUUID
4410      * @return NetworkRecipe object or null if none found
4411      */
4412     public NetworkResource getNetworkResourceByModelUuid(String modelUUID) {
4413
4414         long startTime = System.currentTimeMillis ();
4415         LOGGER.debug ("Catalog database - get network resource with modelUUID " + modelUUID);
4416
4417         try {
4418             String hql =  "FROM NetworkResource WHERE modelUUID=:modelUUID";
4419             Query query = getSession ().createQuery (hql);
4420             query.setParameter (MODEL_UUID, modelUUID);
4421
4422             @SuppressWarnings("unchecked")
4423             List <NetworkResource> resultList = query.list ();
4424
4425             if (resultList.isEmpty ()) {
4426                 return null;
4427             }
4428             
4429             resultList.sort(new MavenLikeVersioningComparator());
4430             Collections.reverse (resultList);
4431             
4432             return resultList.get (0);
4433         } catch (Exception e) {
4434                 LOGGER.debug("Error trying to find Network Resource with " + modelUUID +", " + e.getMessage(),e);
4435         } finally {
4436             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResourceByModelUuid", null);
4437         }
4438         return null;
4439     }
4440
4441
4442     /**
4443      * Return a Network recipe that matches a given NETWORK_TYPE, ACTION, and, if specified, SERVICE_TYPE
4444      *
4445      * @param networkType
4446      * @param action
4447      * @param serviceType
4448      * @return NetworkRecipe object or null if none found
4449      */
4450     public NetworkRecipe getNetworkRecipe (String networkType, String action, String serviceType) {
4451
4452         long startTime = System.currentTimeMillis ();
4453         LOGGER.debug ("Catalog database - get network recipe with network type " + networkType
4454                                       + " and action "
4455                                       + action
4456                                       + " and service type "
4457                                       + serviceType);
4458
4459         try {
4460             String hql;
4461             if (serviceType == null) {
4462                 hql = "FROM NetworkRecipe WHERE networkType = :networkType AND action = :action AND serviceType IS NULL ";
4463             } else {
4464                 hql = "FROM NetworkRecipe WHERE networkType = :networkType AND action = :action AND serviceType = :serviceType ";
4465             }
4466             Query query = getSession ().createQuery (hql);
4467             query.setParameter (NETWORK_TYPE, networkType);
4468             query.setParameter (ACTION, action);
4469             if (serviceType != null) {
4470                 query.setParameter ("serviceType", serviceType);
4471             }
4472
4473             @SuppressWarnings("unchecked")
4474             List <NetworkRecipe> resultList = query.list ();
4475
4476             if (resultList.isEmpty ()) {
4477                 return null;
4478             }
4479
4480             resultList.sort(new MavenLikeVersioningComparator());
4481             Collections.reverse (resultList);
4482
4483             return resultList.get (0);
4484         } finally {
4485             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
4486         }
4487     }
4488
4489     /**
4490      * Return a Network recipe that matches a given MODEL_UUID and ACTION
4491      *
4492      * @param modelName
4493      * @param action
4494      * @return NetworkRecipe object or null if none found
4495      */
4496     public NetworkRecipe getNetworkRecipeByModuleUuid (String networkModelUuid, String action) {
4497         LOGGER.debug ("Catalog database - get network recipe with network model uuid " + networkModelUuid
4498                 + " and action "
4499                 + action
4500                 );
4501         NetworkResource networkResource = getNetworkResourceByModelUuid(networkModelUuid);
4502         if(null == networkResource){
4503             return null;
4504         }
4505         
4506         NetworkRecipe recipe = getNetworkRecipeByNameVersion(networkResource.getModelName(), networkResource.getModelVersion(), action);
4507         return recipe;        
4508     }
4509     
4510     /**
4511      * Return a Network recipe that matches a given MODEL_NAME and ACTION
4512      *
4513      * @param modelName
4514      * @param action
4515      * @return NetworkRecipe object or null if none found
4516      */
4517     public NetworkRecipe getNetworkRecipe (String modelName, String action) {
4518
4519         long startTime = System.currentTimeMillis ();
4520         LOGGER.debug ("Catalog database - get network recipe with network model name " + modelName
4521                                       + " and action "
4522                                       + action
4523                                       );
4524
4525         try {
4526             String hql = "FROM NetworkRecipe WHERE modelName = :modelName AND action = :action";
4527
4528             Query query = getSession ().createQuery (hql);
4529             query.setParameter (MODEL_NAME, modelName);
4530             query.setParameter (ACTION, action);
4531
4532             @SuppressWarnings("unchecked")
4533             List <NetworkRecipe> resultList = query.list ();
4534
4535             if (resultList.isEmpty ()) {
4536                 return null;
4537             }
4538
4539             resultList.sort(new MavenLikeVersioningComparator());
4540             Collections.reverse (resultList);
4541
4542             return resultList.get (0);
4543         } finally {
4544             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
4545         }
4546     }
4547
4548     /**
4549      * get network recipe by module name and version and action.
4550      * <br>
4551      * 
4552      * @param modelName
4553      * @param modelVersion
4554      * @param action
4555      * @return
4556      * @since ONAP Beijing Release
4557      */
4558     public NetworkRecipe getNetworkRecipeByNameVersion(String modelName, String modelVersion, String action) {
4559
4560         long startTime = System.currentTimeMillis ();
4561         LOGGER.debug ("Catalog database - get network recipe with network model name " + modelName
4562                                       +"model version " + modelVersion + " and action " + action);
4563
4564         try {
4565             String hql = "FROM NetworkRecipe WHERE modelName = :modelName AND version=:version AND action = :action";
4566
4567             Query query = getSession ().createQuery (hql);
4568             query.setParameter (MODEL_NAME, modelName);
4569             query.setParameter (MODEL_VERSION, modelVersion);
4570             query.setParameter (ACTION, action);
4571
4572             @SuppressWarnings("unchecked")
4573             List <NetworkRecipe> resultList = query.list ();
4574
4575             if (resultList.isEmpty ()) {
4576                 return null;
4577             }
4578
4579             resultList.sort(new MavenLikeVersioningComparator());
4580             Collections.reverse (resultList);
4581
4582             return resultList.get (0);
4583         } finally {
4584             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
4585         }
4586     }
4587     
4588     /**
4589      * Return a Network Resource that matches the Network Customization defined by given MODEL_CUSTOMIZATION_UUID
4590      *
4591      * @param modelCustomizationUuid
4592      * @return NetworkRecipe object or null if none found
4593      */
4594     public NetworkResource getNetworkResourceByModelCustUuid(String modelCustomizationUuid) {
4595
4596         long startTime = System.currentTimeMillis ();
4597         LOGGER.debug ("Catalog database - get network resource with modelCustomizationUuid " + modelCustomizationUuid);
4598
4599         try {
4600             String hql =  "select n FROM NetworkResource n, NetworkResourceCustomization c WHERE n.modelUUID=c.networkResourceModelUuid and c.modelCustomizationUuid = :modelCustomizationUuid";
4601             Query query = getSession ().createQuery (hql);
4602             query.setParameter (MODEL_CUSTOMIZATION_UUID, modelCustomizationUuid);
4603
4604             @SuppressWarnings("unchecked")
4605             List <NetworkResource> resultList = query.list ();
4606
4607             if (resultList.isEmpty ()) {
4608                 return null;
4609             }
4610
4611             resultList.sort(new MavenLikeVersioningComparator());
4612             Collections.reverse (resultList);
4613
4614             return resultList.get (0);
4615         } catch (Exception e) {
4616                 LOGGER.debug("Error trying to find Network Resource with " + modelCustomizationUuid +", " + e.getMessage(),e);
4617         } finally {
4618             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResourceByModelCustUuid", null);
4619         }
4620         return null;
4621     }
4622
4623     /**
4624      * Return a VnfComponents recipe that matches a given VNF_TYPE, VNF_COMPONENT_TYPE, ACTION, and, if specified,
4625      * SERVICE_TYPE
4626      *
4627      * @param vnfType
4628      * @param vnfComponentType
4629      * @param action
4630      * @param serviceType
4631      * @return VnfComponentsRecipe object or null if none found
4632      */
4633     public VnfComponentsRecipe getVnfComponentsRecipe (String vnfType,
4634                                                        String vnfComponentType,
4635                                                        String action,
4636                                                        String serviceType) {
4637
4638         long startTime = System.currentTimeMillis ();
4639         LOGGER.debug ("Catalog database - get Vnf Component recipe with network type " + vnfType
4640                                       + " and component type "
4641                                       + vnfComponentType
4642                                       + " and action "
4643                                       + action
4644                                       + " and service type "
4645                                       + serviceType);
4646
4647         try {
4648             String hql;
4649             if (serviceType == null) {
4650                 hql = "FROM VnfComponentsRecipe WHERE vnfType = :vnfType AND vnfComponentType = :vnfComponentType AND action = :action AND serviceType IS NULL ";
4651             } else {
4652                 hql = "FROM VnfComponentsRecipe WHERE vnfType = :vnfType AND vnfComponentType = :vnfComponentType AND action = :action AND serviceType = :serviceType ";
4653             }
4654             Query query = getSession ().createQuery (hql);
4655             query.setParameter (VNF_TYPE, vnfType);
4656             query.setParameter (VNF_COMPONENT_TYPE, vnfComponentType);
4657             query.setParameter (ACTION, action);
4658             if (serviceType != null) {
4659                 query.setParameter ("serviceType", serviceType);
4660             }
4661
4662             @SuppressWarnings("unchecked")
4663             List <VnfComponentsRecipe> resultList = query.list ();
4664
4665             if (resultList.isEmpty ()) {
4666                 return null;
4667             }
4668             resultList.sort(new MavenLikeVersioningComparator());
4669             Collections.reverse (resultList);
4670
4671             return resultList.get (0);
4672         } finally {
4673             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponentsRecipe", null);
4674         }
4675     }
4676
4677     /**
4678      * Return a VnfComponents recipe that matches a given VF_MODULE_ID, VNF_COMPONENT_TYPE, ACTION
4679      *
4680      * @param vfModuleModelUUId
4681      * @param vnfComponentType
4682      * @param action
4683      * @return VnfComponentsRecipe object or null if none found
4684      */
4685     public VnfComponentsRecipe getVnfComponentsRecipeByVfModuleModelUUId (String vfModuleModelUUId,
4686                                                        String vnfComponentType,
4687                                                        String action) {
4688
4689         long startTime = System.currentTimeMillis ();
4690         LOGGER.debug ("Catalog database - get Vnf Component recipe with vfModuleModelUUId " + vfModuleModelUUId
4691                                       + " and component type "
4692                                       + vnfComponentType
4693                                       + " and action "
4694                                       + action);
4695
4696         try {
4697             String hql;
4698             hql = "FROM VnfComponentsRecipe WHERE vfModuleModelUUId = :vfModuleModelUUId AND vnfComponentType = :vnfComponentType AND action = :action ";
4699
4700             Query query = getSession ().createQuery (hql);
4701             query.setParameter (VF_MODULE_MODEL_UUID, vfModuleModelUUId);
4702             query.setParameter (VNF_COMPONENT_TYPE, vnfComponentType);
4703             query.setParameter (ACTION, action);
4704
4705             @SuppressWarnings("unchecked")
4706             List <VnfComponentsRecipe> resultList = query.list ();
4707
4708             if (resultList.isEmpty ()) {
4709                 return null;
4710             }
4711             resultList.sort(new MavenLikeVersioningComparator());
4712             Collections.reverse (resultList);
4713
4714             return resultList.get (0);
4715         } finally {
4716             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfComponentsRecipeByVfModuleModelUUId", null);
4717         }
4718     }
4719     
4720     public List<VnfComponentsRecipe> getVnfComponentRecipes (String vfModuleModelUUId) {
4721         
4722         StringBuilder hql = null;
4723         
4724         hql = new StringBuilder ("FROM VnfComponentsRecipe WHERE vfModuleModelUUId = :vfModuleModelUUId");
4725         
4726         long startTime = System.currentTimeMillis ();
4727         LOGGER.debug ("Catalog database - get Service recipe with vfModuleModelUUId " + vfModuleModelUUId);
4728
4729         Query query = getSession ().createQuery (hql.toString ());
4730         query.setParameter ("vfModuleModelUUId", vfModuleModelUUId);
4731         
4732         @SuppressWarnings("unchecked")
4733         List <VnfComponentsRecipe> resultList = query.list ();
4734
4735         if (resultList.isEmpty ()) {
4736             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Service recipe not found", "CatalogDB", "getVfModuleRecipes", null);
4737             return Collections.EMPTY_LIST;
4738         }
4739         
4740         resultList.sort(new MavenLikeVersioningComparator());
4741         Collections.reverse (resultList);
4742
4743         LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleRecipes", null);
4744         return resultList;
4745     }
4746
4747
4748
4749     public void saveOrUpdateVnfComponent (VnfComponent vnfComponent) {
4750         long startTime = System.currentTimeMillis ();
4751
4752         LOGGER.debug ("Catalog database - save VnfComponent where vnfId="+ vnfComponent.getVnfId()+ " AND componentType="+ vnfComponent.getComponentType());
4753
4754         VnfComponent vnfComponentDb = this.getVnfComponent(vnfComponent.getVnfId(), vnfComponent.getComponentType());
4755
4756         try {
4757
4758                 this.getSession ().save (vnfComponent);
4759
4760         } finally {
4761             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "saveOrUpdateVnfComponent", null);
4762         }
4763     }
4764
4765     /**
4766      * Return a VfModule record that matches a given MODEL_NAME
4767      *
4768      * @param modelName
4769      * @return VfModule object or null if none found
4770      */
4771     public VfModule getVfModule (String modelName) {
4772
4773         long startTime = System.currentTimeMillis ();
4774         LOGGER.debug ("Catalog database - get vf module with model name " + modelName);
4775
4776         try {
4777             String hql;
4778
4779             hql = "FROM VfModule WHERE modelName = :modelName";
4780
4781             Query query = getSession ().createQuery (hql);
4782             query.setParameter (MODEL_NAME, modelName);
4783
4784             @SuppressWarnings("unchecked")
4785             List <VfModule> resultList = query.list ();
4786
4787             if (resultList.isEmpty ()) {
4788                 return null;
4789             }
4790             resultList.sort(new MavenLikeVersioningComparator());
4791             Collections.reverse (resultList);
4792
4793             return resultList.get (0);
4794         } finally {
4795             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModule", null);
4796         }
4797     }
4798
4799     /**
4800      * Return a VfModule record that matches a given MODEL_NAME
4801      *
4802      * @param modelUUID
4803      * @return VfModule object or null if none found
4804      */
4805     public VfModule getVfModuleByModelUUID (String modelUUID) {
4806
4807         long startTime = System.currentTimeMillis ();
4808         LOGGER.debug ("Catalog database - get vf module with modelUUID " + modelUUID);
4809
4810         try {
4811             String hql;
4812
4813             hql = "FROM VfModule WHERE modelUUID = :modelUUID";
4814
4815             Query query = getSession ().createQuery (hql);
4816             query.setParameter (MODEL_UUID, modelUUID);
4817
4818             @SuppressWarnings("unchecked")
4819             List <VfModule> resultList = query.list ();
4820
4821             if (resultList.isEmpty ()) {
4822                 return null;
4823             }
4824             resultList.sort(new MavenLikeVersioningComparator());
4825             Collections.reverse (resultList);
4826
4827             return resultList.get (0);
4828         } finally {
4829             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleByModelUUID", null);
4830         }
4831     }
4832     
4833     /**
4834      * Return a Service recipe that matches a given service ModelUUID and action
4835      * (modelUUID) and ACTION
4836      *
4837      * @param modelUUID
4838      * @param action    
4839      * @return ServiceRecipe object or null if none found
4840      */
4841     public ServiceRecipe getServiceRecipeByModelUUID(String modelUUID, String action) {                     
4842
4843         long startTime = System.currentTimeMillis();
4844         LOGGER.debug("Catalog database - get Service recipe with modelUUID=" + modelUUID + " and action=" + action);
4845
4846         try {
4847                         String hql;
4848                         // based on the new SERVICE_RECIPE schema where SERVICE_MODEL_UUID == MODEL_UUID, a JOIN with the SERVICE table is no longer needed
4849 //                      hql = "SELECT new ServiceRecipe(SR.id, SR.serviceModelUUID, SR.action, SR.description, " +
4850 //                                      "SR.orchestrationUri, SR.serviceParamXSD, case when SR.recipeTimeout is null then 0 else SR.recipeTimeout end, " +
4851 //                                      "case when SR.serviceTimeoutInterim is null then 0 else SR.serviceTimeoutInterim end, SR.created) " +
4852 //                                      "FROM Service as S RIGHT OUTER JOIN S.recipes SR " +
4853 //                                      "WHERE SR.serviceModelUUID = :modelUUID AND SR.action = :action";
4854                         hql = "FROM ServiceRecipe WHERE serviceModelUUID = :modelUUID AND action = :action";
4855                         Query query = getSession().createQuery(hql);
4856                         query.setParameter(MODEL_UUID, modelUUID);
4857                         query.setParameter(ACTION, action);
4858
4859                         @SuppressWarnings("unchecked")
4860                         List<ServiceRecipe> recipeResultList = query.list();
4861                         if (recipeResultList.isEmpty()) {
4862                                 LOGGER.debug("Catalog database - recipeResultList is null");
4863                                 return null;
4864                         }
4865                         recipeResultList.sort(new MavenLikeVersioningComparator());
4866                         Collections.reverse(recipeResultList);
4867                         LOGGER.debug("Catalog database - recipeResultList contains " + recipeResultList.get(0).toString());
4868
4869                         return recipeResultList.get(0);
4870         } finally {
4871             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipeByModelUUID", null);
4872         }
4873     }
4874     
4875     /**
4876      * Return a Service recipe that matches a given SERVICE_NAME_VERSION_ID
4877      * (MODEL_VERSION_ID) and ACTION
4878      *
4879      * @param modelVersionId
4880      * @param action    
4881      * @return ServiceRecipe object or null if none found
4882      */
4883     @Deprecated
4884     public ServiceRecipe getServiceRecipe(String modelVersionId,
4885                                        String action) {                     
4886
4887         long startTime = System.currentTimeMillis();
4888         LOGGER.debug("Catalog database - get Service recipe with modeVersionId=" + modelVersionId
4889                                       + " and action=" + action);
4890
4891         try {
4892                         String hql;
4893                         // Note: Even with the implementation of the HQL JOIN below, the code for the two separate
4894                         //       SELECTs will be retained/commented for now in the event some subsequent JOIN issue arises
4895                         // 1st query to get the Service record for the given SERVICE_NAME_VERSION_ID (MODEL_VERSION_ID)
4896 /*                      hql = "FROM Service WHERE serviceNameVersionId = :serviceNameVersionId";
4897                         Query query = getSession().createQuery(hql);
4898                         query.setParameter(SERVICE_NAME_VERSION_ID, modelVersionId);
4899
4900                         @SuppressWarnings("unchecked")
4901                         List<Service> serviceResultList = query.list();
4902                         if (serviceResultList.isEmpty()) {
4903                                 LOGGER.debug("Catalog database - serviceResultList is null");
4904                                 return null;
4905                         }
4906                         Collections.sort(serviceResultList, new MavenLikeVersioningComparator());
4907                         Collections.reverse(serviceResultList);
4908                         LOGGER.debug("Catalog database - serviceResultList contains " + serviceResultList.get(0).toString());
4909
4910                         // 2nd query to get the ServiceRecipe record corresponding to the Service from the 1st query
4911                         hql = "FROM ServiceRecipe WHERE serviceModelUUID = :serviceModelUUID AND action = :action";
4912                         query = getSession().createQuery(hql);
4913                         // The SERVICE table 'id' field maps to the SERVICE_RECIPE table 'SERVICE_ID' field
4914                         query.setParameter(SERVICE_ID, serviceResultList.get(0).getId());
4915                         query.setParameter(ACTION, action);
4916 */
4917                         // The following SELECT performs a JOIN across the SERVICE and SERVICE_RECIPE tables. It required a new
4918                         // CTR in the ServiceRecipe Class to populate that object (the other option was to parse the Object[]
4919                         // returned by createQuery() and manually populate the ServiceRecipe object). Two of the 'int' fields in the
4920                         // SERVICE_RECIPE DB schema (the timeouts) permit NULL values which required some additional code in the
4921                         // SELECT to generate a default of 0 (needed by the CTR) in the cases where the value is NULL.
4922                         hql = "SELECT new ServiceRecipe(SR.id, SR.serviceModelUUID, SR.action, SR.description, " +
4923                                         "SR.orchestrationUri, SR.serviceParamXSD, case when SR.recipeTimeout is null then 0 else SR.recipeTimeout end, " +
4924                                         "case when SR.serviceTimeoutInterim is null then 0 else SR.serviceTimeoutInterim end, SR.created) " +
4925                                         "FROM Service as S RIGHT OUTER JOIN S.recipes SR " +
4926                                         "WHERE SR.serviceModelUUID = S.id AND S.serviceNameVersionId = :serviceNameVersionId AND SR.action = :action";
4927                         Query query = getSession().createQuery(hql);
4928                         query.setParameter(MODEL_UUID, modelVersionId);
4929                         query.setParameter(ACTION, action);
4930
4931                         @SuppressWarnings("unchecked")
4932                         List<ServiceRecipe> recipeResultList = query.list();
4933                         if (recipeResultList.isEmpty()) {
4934                                 LOGGER.debug("Catalog database - recipeResultList is null");
4935                                 return null;
4936                         }
4937                         recipeResultList.sort(new MavenLikeVersioningComparator());
4938                         Collections.reverse(recipeResultList);
4939                         LOGGER.debug("Catalog database - recipeResultList contains " + recipeResultList.get(0).toString());
4940
4941                         return recipeResultList.get(0);
4942         } finally {
4943             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getServiceRecipe", null);
4944         }
4945     }
4946
4947     /**
4948      * Return a Model recipe that matches a given MODEL_TYPE, MODEL_VERSION_ID, ACTION
4949      * Note: This method is not currently used but was retained in the event the
4950      *       architecture moves back to a MODEL/MODEL_RECIPE structure.
4951      *
4952      * @param modelType
4953      * @param modelVersionId
4954      * @param action
4955      * @return ModelRecipe object or null if none found
4956      */
4957     public ModelRecipe getModelRecipe(String modelType,
4958                                       String modelVersionId,
4959                                       String action) {
4960
4961         long startTime = System.currentTimeMillis();
4962         LOGGER.debug("Catalog database - get Model recipe with modelType=" + modelType
4963                 + " and modeVersionId=" + modelVersionId
4964                 + " and action=" + action);
4965
4966         try {
4967             String hql;
4968             // TBD - at some point it would be desirable to figure out how to do a  HQL JOIN across
4969             //       the MODEL and MODEL_RECIPE tables in HQL instead of 2 separate queries.
4970             //       There seems to be 2 issues: formatting a hql query that executes successfully
4971             //       and then being able to generate a result that will fit into the ModelRecipe class.
4972
4973             // 1st query to get the Model record for the given MODEL_TYPE and MODEL_VERSION_ID
4974             hql = "FROM Model WHERE modelType = :modelType AND modelVersionId = :modelVersionId";
4975             Query query = getSession().createQuery(hql);
4976             query.setParameter(MODEL_TYPE, modelType);
4977             query.setParameter(MODEL_VERSION_ID, modelVersionId);
4978
4979             @SuppressWarnings("unchecked")
4980             List<Model> modelResultList = query.list();
4981             if (modelResultList.isEmpty()) {
4982                 LOGGER.debug("Catalog database - modelResultList is null");
4983                 return null;
4984             }
4985             modelResultList.sort(new MavenLikeVersioningComparator());
4986             Collections.reverse(modelResultList);
4987             LOGGER.debug("Catalog database - modelResultList contains " + modelResultList.get(0).toString());
4988
4989             // 2nd query to get the ModelRecipe record corresponding to the Model from the 1st query
4990             hql = "FROM ModelRecipe WHERE modelId = :modelId AND action = :action";
4991             query = getSession().createQuery(hql);
4992             // The MODEL table 'id' field maps to the MODEL_RECIPE table 'MODEL_ID' field
4993             query.setParameter(MODEL_ID, modelResultList.get(0).getId());
4994             query.setParameter(ACTION, action);
4995
4996             @SuppressWarnings("unchecked")
4997             List<ModelRecipe> recipeResultList = query.list();
4998             if (recipeResultList.isEmpty()) {
4999                 LOGGER.debug("Catalog database - recipeResultList is null");
5000                 return null;
5001             }
5002             recipeResultList.sort(new MavenLikeVersioningComparator());
5003             Collections.reverse(recipeResultList);
5004             LOGGER.debug("Catalog database - recipeResultList contains " + recipeResultList.get(0).toString());
5005
5006             return recipeResultList.get(0);
5007         } finally {
5008             LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getModelRecipe", null);
5009         }
5010     }
5011
5012
5013     /**
5014      * Verify the health of the DB.
5015      *
5016      * @return boolean value indicate whether DB is healthy
5017      */
5018     public boolean healthCheck () {
5019         long startTime = System.currentTimeMillis ();
5020         Session session = this.getSession ();
5021
5022         // Query query = session.createQuery (" from ActiveRequests ");
5023         Query query = session.createSQLQuery (" show tables ");
5024
5025         List<?> list = query.list();
5026         LOGGER.debug("healthCheck CatalogDB - Successful");
5027         return true;
5028     }
5029     
5030     public < E > E executeQuerySingleRow(String hql, HashMap<String, String> variables, boolean retry) {
5031         long startTime = System.currentTimeMillis();
5032         LOGGER.debug("Catalog database - executeQuery: " + hql + (retry ? ", retry=true" : ", retry=false"));
5033         Query query = getSession().createQuery(hql);
5034
5035         StringBuilder sb = new StringBuilder();
5036         if (variables != null) {
5037                 for(Map.Entry<String, String> entry : variables.entrySet()){
5038                         sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
5039                         query.setParameter(entry.getKey(), entry.getValue());
5040                 }
5041         }
5042         LOGGER.debug("Variables:\n" + sb.toString());
5043
5044         E theObject = null;
5045         try {
5046             theObject = (E) query.uniqueResult();
5047         } catch (org.hibernate.NonUniqueResultException nure) {
5048                 LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row");
5049                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for " + hql, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for " + hql );
5050                 throw nure;
5051         } catch (org.hibernate.HibernateException he) {
5052                 LOGGER.debug("Hibernate Exception - while performing " + hql + "; he message:" + he.getMessage());
5053                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception while performing hql=" + hql, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for hql=" + hql);
5054                 if (retry) {
5055                         LOGGER.debug("***WILL RETRY***");
5056                         return this.executeQuerySingleRow(hql, variables, false);
5057                 } else {
5058                         throw he;
5059                 }
5060         } catch (Exception e) {
5061                 LOGGER.debug("Generic Exception - while performing '" + hql + "'");
5062                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception performing " + hql, "", "", MsoLogger.ErrorCode.DataError, "Generic exception performing " + hql);
5063                 if (retry) {
5064                         LOGGER.debug("***WILL RETRY***");
5065                         return this.executeQuerySingleRow(hql, variables, false);
5066                 } else {
5067                         throw e;
5068                 }
5069         }
5070
5071         if (theObject == null) {
5072                 LOGGER.debug("Returning null");
5073                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "executeQuerySingleRow", null);
5074         } else {
5075                 LOGGER.debug("Returning an Object");
5076                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "executeQuerySingleRow", null);
5077         }
5078         return theObject;
5079     }
5080     
5081     public < E > List<E> executeQueryMultipleRows(String hql, HashMap<String, String> variables, boolean retry) {
5082         long startTime = System.currentTimeMillis ();
5083         LOGGER.debug("Catalog database - executeQuery: " + hql + (retry ? ", retry=true" : ", retry=false"));
5084         Query query = getSession().createQuery(hql);
5085
5086         StringBuilder sb = new StringBuilder();
5087         if (variables != null) {
5088                 for(Map.Entry<String, String> entry : variables.entrySet()){
5089                         sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
5090                         query.setParameter(entry.getKey(), entry.getValue());
5091                 }
5092         }
5093         LOGGER.debug("Variables:\n" + sb.toString());
5094
5095         List<E> theObjects = null;
5096         try {
5097                 theObjects = (List<E>) query.list ();
5098         } catch (org.hibernate.HibernateException he) {
5099                 LOGGER.debug("Hibernate Exception - while performing " + hql + "; he message:" + he.getMessage());
5100                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Hibernate exception while performing hql=" + hql, "", "", MsoLogger.ErrorCode.DataError, "Hibernate exception searching for hql=" + hql);
5101                 if (retry) {
5102                         LOGGER.debug("***WILL RETRY***");
5103                         return this.executeQuerySingleRow(hql, variables, false);
5104                 } else {
5105                         throw he;
5106                 }
5107         } catch (Exception e) {
5108                 LOGGER.debug("Generic Exception - while performing '" + hql + "'");
5109                 LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " Generic exception performing " + hql, "", "", MsoLogger.ErrorCode.DataError, "Generic exception performing " + hql);
5110                 if (retry) {
5111                         LOGGER.debug("***WILL RETRY***");
5112                         return this.executeQuerySingleRow(hql, variables, false);
5113                 } else {
5114                         throw e;
5115                 }
5116         }
5117
5118         if (theObjects == null) {
5119                 LOGGER.debug("Returning null");
5120                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "executeQuerySingleRow", null);
5121         } else {
5122                 try {
5123                         LOGGER.debug("Returning theObjects:" + theObjects.size());
5124                 } catch (Exception e) {
5125                         LOGGER.debug("Returning theObjects",e);
5126                 }
5127                 LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "executeQuerySingleRow", null);
5128         }
5129         return theObjects;
5130     }
5131     
5132     
5133     /**
5134      * get allotted resource recipe by module name and version and action.
5135      * <br>
5136      * 
5137      * @param modelName
5138      * @param modelVersion
5139      * @param action
5140      * @return
5141      * @since ONAP Beijing Release
5142      */
5143     public ArRecipe getArRecipeByNameVersion(String modelName, String modelVersion, String action) {
5144
5145         long startTime = System.currentTimeMillis ();
5146         LOGGER.debug ("Catalog database - get ar recipe with ar model name " + modelName
5147                                       +"model version " + modelVersion + " and action " + action);
5148
5149         try {
5150             String hql = "FROM ArRecipe WHERE modelName = :modelName AND version=:version AND action = :action";
5151
5152             Query query = getSession ().createQuery (hql);
5153             query.setParameter (MODEL_NAME, modelName);
5154             query.setParameter (MODEL_VERSION, modelVersion);
5155             query.setParameter (ACTION, action);
5156
5157             @SuppressWarnings("unchecked")
5158             List <ArRecipe> resultList = query.list ();
5159
5160             if (resultList.isEmpty ()) {
5161                 return null;
5162             }
5163
5164             resultList.sort(new MavenLikeVersioningComparator());
5165             Collections.reverse (resultList);
5166
5167             return resultList.get (0);
5168         } finally {
5169             LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkRecipe", null);
5170         }
5171     }
5172     
5173     /**
5174      * Return a allotted resource recipe that matches a given MODEL_UUID and ACTION
5175      *
5176      * @param modelName
5177      * @param action
5178      * @return ArRecipe object or null if none found
5179      */
5180     public ArRecipe getArRecipeByModuleUuid (String ArModelUuid, String action) {
5181         LOGGER.debug ("Catalog database - get ar recipe with ar model uuid " + ArModelUuid
5182                 + " and action "
5183                 + action
5184                 );
5185         AllottedResource arResource = this.getAllottedResourceByModelUuid(ArModelUuid);
5186         if(null == arResource){
5187             return null;
5188         }
5189         
5190         ArRecipe recipe = getArRecipeByNameVersion(arResource.getModelName(), arResource.getModelVersion(), action);
5191         return recipe;        
5192     }
5193     
5194 }