aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/main/java/org/onap/policy/api/main/service/ToscaServiceTemplateService.java
blob: 2e8fc9ebcb84ba06c2355563a67fc585c940526d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2022 Bell Canada. All rights reserved.
 *  Modifications Copyright (C) 2022 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.api.main.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.ws.rs.core.Response;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.onap.policy.api.main.repository.ToscaServiceTemplateRepository;
import org.onap.policy.api.main.rest.PolicyFetchMode;
import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter;
import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTypes;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate;
import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider;
import org.onap.policy.models.tosca.utils.ToscaServiceTemplateUtils;
import org.onap.policy.models.tosca.utils.ToscaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RequiredArgsConstructor
public class ToscaServiceTemplateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ToscaServiceTemplateService.class);

    // Recurring string constants
    private static final String POLICY_TYPE = "policy type ";
    private static final String NOT_FOUND = " not found";
    public static final String SERVICE_TEMPLATE_NOT_FOUND_MSG = "service template not found in database";
    public static final String DO_NOT_EXIST_MSG = " do not exist";

    private final ToscaServiceTemplateRepository toscaServiceTemplateRepository;
    private final NodeTemplateService nodeTemplateService;
    private final PdpGroupService pdpGroupService;
    private final PolicyTypeService policyTypeService;
    private final PolicyService policyService;

    /**
     * Retrieves a list of policy types matching specified policy type name and version.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type
     * @return the ToscaServiceTemplate object
     */
    public ToscaServiceTemplate fetchPolicyTypes(final String policyTypeName, final String policyTypeVersion)
        throws PfModelException {
        final var policyTypeFilter =
            ToscaEntityFilter.<ToscaPolicyType>builder().name(policyTypeName).version(policyTypeVersion).build();
        return getFilteredPolicyTypes(policyTypeFilter);
    }

    /**
     * Retrieves a list of policy types with the latest versions.
     *
     * @param policyTypeName the name of policy type
     * @return the ToscaServiceTemplate object
     */
    public ToscaServiceTemplate fetchLatestPolicyTypes(final String policyTypeName) throws PfModelException {
        final var policyTypeFilter = ToscaEntityFilter.<ToscaPolicyType>builder()
            .name(policyTypeName).version(ToscaEntityFilter.LATEST_VERSION).build();
        return getFilteredPolicyTypes(policyTypeFilter);
    }

    /**
     * Creates a new policy type.
     *
     * @param body the entity body of policy type
     * @return the TOSCA service template containing the created policy types
     * @throws PfModelRuntimeException on errors creating policy types
     */
    public ToscaServiceTemplate createPolicyType(@NonNull final ToscaServiceTemplate body)
        throws PfModelRuntimeException {
        final var incomingServiceTemplate = new JpaToscaServiceTemplate(body);
        LOGGER.debug("->createPolicyType: serviceTemplate={}", incomingServiceTemplate);

        // assert incoming body contains policyTypes
        ToscaUtils.assertPolicyTypesExist(incomingServiceTemplate);

        // append the incoming fragment to the DB TOSCA service template
        var dbServiceTemplateOpt = getDefaultJpaToscaServiceTemplateOpt();
        JpaToscaServiceTemplate serviceTemplateToWrite;
        if (dbServiceTemplateOpt.isEmpty()) {
            serviceTemplateToWrite = incomingServiceTemplate;
        } else {
            serviceTemplateToWrite =
                ToscaServiceTemplateUtils.addFragment(dbServiceTemplateOpt.get(), incomingServiceTemplate);
        }

        final var result = serviceTemplateToWrite.validate("service template");
        if (!result.isValid()) {
            throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult());
        } else {
            toscaServiceTemplateRepository.save(serviceTemplateToWrite);
            LOGGER.debug("<-createPolicyType: writtenServiceTemplate={}", serviceTemplateToWrite);
        }
        return body;
    }

    /**
     * Delete the policy type matching specified policy type name and version.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type, if the version of the key is null,
     *                          all versions of the policy type are deleted.
     * @return the TOSCA service template containing the policy types that were deleted
     * @throws PfModelRuntimeException on errors deleting policy types
     */
    public ToscaServiceTemplate deletePolicyType(final String policyTypeName, final String policyTypeVersion)
        throws PfModelRuntimeException {
        final var policyTypeKey = new PfConceptKey(policyTypeName, policyTypeVersion);
        LOGGER.debug("->deletePolicyType: name={}, version={}", policyTypeName, policyTypeVersion);

        // terminate deletion if supported in a PdpGroup
        pdpGroupService.assertPolicyTypeNotSupportedInPdpGroup(policyTypeName, policyTypeVersion);

        final var serviceTemplate = getDefaultJpaToscaServiceTemplate();

        // terminate deletion if not found
        if (!ToscaUtils.doPolicyTypesExist(serviceTemplate)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no policy types found");
        }

        final var policyTypeForDeletion = serviceTemplate.getPolicyTypes().get(policyTypeKey);
        if (policyTypeForDeletion == null) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
                POLICY_TYPE + policyTypeKey.getId() + NOT_FOUND);
        }

        final var result = new BeanValidationResult("policy types", serviceTemplate);

        for (final var policyType : serviceTemplate.getPolicyTypes().getAll(null)) {
            final var ancestorList = ToscaUtils
                .getEntityTypeAncestors(serviceTemplate.getPolicyTypes(), policyType, result);
            // terminate deletion if referenced by another via derived_from property
            if (ancestorList.contains(policyTypeForDeletion)) {
                throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, POLICY_TYPE + policyTypeKey.getId()
                    + " is in use, it is referenced in policy type " + policyType.getId());
            }
        }
        if (ToscaUtils.doPoliciesExist(serviceTemplate)) {
            for (final var policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) {
                // terminate deletion if referenced by a policy
                if (policyTypeKey.equals(policy.getType())) {
                    throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, POLICY_TYPE
                        + policyTypeKey.getId() + " is in use, it is referenced in policy " + policy.getId());
                }
            }
        }

        // remove policyType from service template and write to DB
        serviceTemplate.getPolicyTypes().getConceptMap().remove(policyTypeKey);
        toscaServiceTemplateRepository.save(serviceTemplate);

        // remove the entry from the Policy table
        policyTypeService.deletePolicyType(policyTypeKey);

        // prepare return service template object
        var deletedServiceTemplate = new JpaToscaServiceTemplate();
        deletedServiceTemplate.setPolicyTypes(new JpaToscaPolicyTypes());
        deletedServiceTemplate.getPolicyTypes().getConceptMap().put(policyTypeKey, policyTypeForDeletion);

        LOGGER.debug("<-deletePolicyType: key={}, serviceTemplate={}", policyTypeKey, deletedServiceTemplate);
        return deletedServiceTemplate.toAuthorative();
    }

    /**
     * Retrieves a list of policies matching specified name and version of both policy type and policy.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type
     * @param policyName the name of policy
     * @param policyVersion the version of policy
     * @param mode the fetch mode for policies
     * @return the ToscaServiceTemplate object with the policies found
     * @throws PfModelException on errors getting the policy
     */
    public ToscaServiceTemplate fetchPolicies(final String policyTypeName, final String policyTypeVersion,
        final String policyName, final String policyVersion, final PolicyFetchMode mode) throws PfModelException {
        return getFilteredPolicies(policyTypeName, policyTypeVersion, policyName, policyVersion, mode);
    }

    /**
     * Retrieves a list of policies with the latest versions that match specified policy type id and version.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type
     * @param policyName the name of the policy
     * @param mode the fetch mode for policies
     * @return the ToscaServiceTemplate object with the policies found
     * @throws PfModelException on errors getting the policy
     */
    public ToscaServiceTemplate fetchLatestPolicies(final String policyTypeName, final String policyTypeVersion,
        final String policyName, final PolicyFetchMode mode) throws PfModelException {
        return getFilteredPolicies(policyTypeName, policyTypeVersion, policyName, ToscaTypedEntityFilter.LATEST_VERSION,
            mode);
    }

    /**
     * Creates one or more new policies for the same policy type name and version.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type
     * @param body the entity body of polic(ies)
     * @return the ToscaServiceTemplate object containing the policy types that were created
     * @throws PfModelRuntimeException on errors creating the policy
     */
    public ToscaServiceTemplate createPolicy(final String policyTypeName, final String policyTypeVersion,
        final ToscaServiceTemplate body) throws PfModelRuntimeException {
        return createPolicies(body);
    }

    /**
     * Creates one or more new policies.
     *
     * @param body the entity body of policy
     * @return the ToscaServiceTemplate object containing the policy types that were created
     * @throws PfModelRuntimeException on errors creating the policy
     */
    public ToscaServiceTemplate createPolicies(final ToscaServiceTemplate body) throws PfModelRuntimeException {
        final var incomingServiceTemplate = new JpaToscaServiceTemplate(body);

        // assert incoming body contains policies
        ToscaUtils.assertPoliciesExist(incomingServiceTemplate);

        // append the incoming fragment to the DB TOSCA service template
        var dbServiceTemplateOpt = getDefaultJpaToscaServiceTemplateOpt();
        JpaToscaServiceTemplate serviceTemplateToWrite;
        if (dbServiceTemplateOpt.isEmpty()) {
            serviceTemplateToWrite = incomingServiceTemplate;
        } else {
            serviceTemplateToWrite =
                ToscaServiceTemplateUtils.addFragment(dbServiceTemplateOpt.get(), incomingServiceTemplate);
        }

        final var result = serviceTemplateToWrite.validate("Policies CRUD service template.");
        if (!result.isValid()) {
            throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult());
        }

        toscaServiceTemplateRepository.save(serviceTemplateToWrite);

        LOGGER.debug("<-appendServiceTemplateFragment: returnServiceTemplate={}", serviceTemplateToWrite);
        return body;
    }

    /**
     * Deletes the policy matching specified name and version of both policy type and policy.
     *
     * @param policyTypeName the name of policy type
     * @param policyTypeVersion the version of policy type
     * @param policyName the name of policy
     * @param policyVersion the version of policy
     * @return the ToscaServiceTemplate object containing the policies that were deleted
     * @throws PfModelRuntimeException on errors deleting the policy
     */
    public ToscaServiceTemplate deletePolicy(final String policyTypeName, final String policyTypeVersion,
        final String policyName, final String policyVersion) throws PfModelRuntimeException {
        final var policyKey = new PfConceptKey(policyName, policyVersion);
        LOGGER.debug("->deletePolicy: name={}, version={}", policyName, policyVersion);

        // terminate if deployed in a PdpGroup
        pdpGroupService.assertPolicyNotDeployedInPdpGroup(policyName, policyVersion);

        final var serviceTemplate = getDefaultJpaToscaServiceTemplate();

        // terminate deletion if not found
        if (!ToscaUtils.doPoliciesExist(serviceTemplate)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no policies found");
        }

        final var policyForDeletion = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey);
        if (policyForDeletion == null) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "policy " + policyKey.getId() + NOT_FOUND);
        }

        // remove policy from service template and write to DB
        serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().remove(policyKey);
        toscaServiceTemplateRepository.save(serviceTemplate);

        // remove the entry from the Policy table
        policyService.deletePolicy(policyKey);

        // prepare return service template object
        var deletedServiceTemplate = new JpaToscaServiceTemplate();
        deletedServiceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate());
        deletedServiceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies());
        deletedServiceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policyKey, policyForDeletion);

        LOGGER.debug("<-deletePolicy: key={}, serviceTemplate={}", policyKey, deletedServiceTemplate);
        return deletedServiceTemplate.toAuthorative();
    }

    /**
     * Retrieves TOSCA service template with the specified version of the policy type.
     *
     * @param policyTypeFilter the policy type filter containing name and version of the policy type
     * @return the TOSCA service template containing the specified version of the policy type
     * @throws PfModelException on errors getting the policy type
     */
    public ToscaServiceTemplate getFilteredPolicyTypes(final ToscaEntityFilter<ToscaPolicyType> policyTypeFilter)
        throws PfModelException {
        final var dbServiceTemplate = getDefaultJpaToscaServiceTemplate();
        LOGGER.debug("->getFilteredPolicyTypes: filter={}, serviceTemplate={}", policyTypeFilter, dbServiceTemplate);

        // validate that policyTypes exist in db
        if (!ToscaUtils.doPolicyTypesExist(dbServiceTemplate)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
                "policy types for filter " + policyTypeFilter + DO_NOT_EXIST_MSG);
        }

        var version = ToscaTypedEntityFilter.LATEST_VERSION
            .equals(policyTypeFilter.getVersion()) ? null : policyTypeFilter.getVersion();
        // fetch all polices and filter by policyType, policy name and version
        final var serviceTemplate = new SimpleToscaProvider()
            .getCascadedPolicyTypes(dbServiceTemplate, policyTypeFilter.getName(), version);
        var simpleToscaProvider = new SimpleToscaProvider();

        List<ToscaPolicyType> filteredPolicyTypes = serviceTemplate.getPolicyTypes().toAuthorativeList();
        filteredPolicyTypes = policyTypeFilter.filter(filteredPolicyTypes);

        // validate that filtered policyTypes exist
        if (CollectionUtils.isEmpty(filteredPolicyTypes)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
                "policy types for filter " + policyTypeFilter + DO_NOT_EXIST_MSG);
        }

        // prepare return service template object
        var returnServiceTemplate = new JpaToscaServiceTemplate();
        for (var policyType : filteredPolicyTypes) {
            final var cascadedServiceTemplate = simpleToscaProvider
                .getCascadedPolicyTypes(dbServiceTemplate, policyType.getName(), policyType.getVersion());
            returnServiceTemplate =
                ToscaServiceTemplateUtils.addFragment(returnServiceTemplate, cascadedServiceTemplate);
        }

        LOGGER.debug("<-getFilteredPolicyTypes: filter={}, serviceTemplate={}", policyTypeFilter,
            returnServiceTemplate);
        return returnServiceTemplate.toAuthorative();

    }

    /**
     * Retrieves TOSCA service template with the specified version of the policy.
     *
     * @param policyName the name of the policy
     * @param policyVersion the version of the policy
     * @param mode the fetch mode for policies
     * @return the TOSCA service template containing the specified version of the policy
     * @throws PfModelException on errors getting the policy
     */
    private ToscaServiceTemplate getFilteredPolicies(final String policyTypeName, final String policyTypeVersion,
        final String policyName, final String policyVersion, final PolicyFetchMode mode) throws PfModelException {
        final var policyFilter = ToscaTypedEntityFilter.<ToscaPolicy>builder()
            .name(policyName).version(policyVersion).type(policyTypeName).typeVersion(policyTypeVersion).build();
        final var dbServiceTemplate = getDefaultJpaToscaServiceTemplate();
        LOGGER.debug("<-getFilteredPolicies: filter={}, serviceTemplate={}", policyFilter, dbServiceTemplate);

        // validate that policies exist in db
        if (!ToscaUtils.doPolicyTypesExist(dbServiceTemplate)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
                "policies for filter " + policyFilter + DO_NOT_EXIST_MSG);
        }

        final var version =
            ToscaTypedEntityFilter.LATEST_VERSION.equals(policyFilter.getVersion()) ? null : policyFilter.getVersion();

        // fetch all polices and filter by policyType, policy name and version
        final var simpleToscaProvider = new SimpleToscaProvider();
        final var serviceTemplate =
            simpleToscaProvider.getCascadedPolicies(dbServiceTemplate, policyFilter.getName(), version);

        var filteredPolicies = serviceTemplate.getTopologyTemplate()
            .getPolicies().toAuthorativeList();
        filteredPolicies = policyFilter.filter(filteredPolicies);

        // validate that filtered policies exist
        if (CollectionUtils.isEmpty(filteredPolicies)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND,
                "policies for filter " + policyFilter + DO_NOT_EXIST_MSG);
        }

        // prepare return service template object
        var returnServiceTemplate = new JpaToscaServiceTemplate();
        for (var policy : filteredPolicies) {
            final var cascadedServiceTemplate = simpleToscaProvider
                .getCascadedPolicies(dbServiceTemplate, policy.getName(), policy.getVersion());
            returnServiceTemplate =
                ToscaServiceTemplateUtils.addFragment(returnServiceTemplate, cascadedServiceTemplate);
        }

        if (mode == null || PolicyFetchMode.BARE.equals(mode)) {
            returnServiceTemplate.setPolicyTypes(null);
            returnServiceTemplate.setDataTypes(null);
        }
        LOGGER.debug("<-getFilteredPolicies: filter={}, , serviceTemplate={}", policyFilter, returnServiceTemplate);
        return returnServiceTemplate.toAuthorative();
    }

    /**
     * Write a node template to the database.
     *
     * @param serviceTemplate the service template to be written
     * @return the service template created by this method
     * @throws PfModelException on errors writing the metadataSets
     */
    public ToscaServiceTemplate createToscaNodeTemplates(@NonNull final ToscaServiceTemplate serviceTemplate)
        throws PfModelException {

        LOGGER.debug("->write: tosca nodeTemplates={}", serviceTemplate);
        final var incomingServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate);

        ToscaUtils.assertNodeTemplatesExist(incomingServiceTemplate);

        Optional<JpaToscaNodeTypes> nodeTypes = Optional.ofNullable(incomingServiceTemplate.getNodeTypes());
        for (JpaToscaNodeTemplate nodeTemplate : incomingServiceTemplate.getTopologyTemplate().getNodeTemplates()
            .getAll(null)) {
            // verify node types in the db if mismatch/empty entities in the template
            if (! (nodeTypes.isPresent() && nodeTypes.get().getKeys().contains(nodeTemplate.getType()))) {
                nodeTemplateService.verifyNodeTypeInDbTemplate(nodeTemplate);
            }
        }
        // append the incoming fragment to the DB TOSCA service template
        final var serviceTemplateToWrite =
            ToscaServiceTemplateUtils.addFragment(getDefaultJpaToscaServiceTemplate(), incomingServiceTemplate);

        final var result = serviceTemplateToWrite.validate("service template.");
        if (!result.isValid()) {
            throw new PfModelRuntimeException(Response.Status.NOT_ACCEPTABLE, result.getResult());
        }
        toscaServiceTemplateRepository.save(serviceTemplateToWrite);
        LOGGER.debug("<-createdToscaNodeTemplates: writtenServiceTemplate={}", serviceTemplateToWrite);

        return serviceTemplate;
    }

    /**
     * Update tosca node template.
     *
     * @param serviceTemplate the service template containing the definitions of the node templates to be updated.
     * @return the TOSCA service template containing the node templates that were updated
     * @throws PfModelRuntimeException on errors updating node templates
     */
    public ToscaServiceTemplate updateToscaNodeTemplates(@NonNull final ToscaServiceTemplate serviceTemplate)
        throws PfModelException {
        LOGGER.debug("->updateToscaNodeTemplates: serviceTemplate={}", serviceTemplate);
        final var incomingServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate);

        ToscaUtils.assertNodeTemplatesExist(incomingServiceTemplate);
        nodeTemplateService.updateToscaNodeTemplates(incomingServiceTemplate);

        LOGGER.debug("<-updatedToscaNodeTemplates: serviceTemplate={}", serviceTemplate);
        return incomingServiceTemplate.toAuthorative();
    }


    /**
     * Delete a tosca node template.
     *
     * @param name the name of node template
     * @param version the version of node template
     * @return the TOSCA service template containing the node template that were deleted
     * @throws PfModelException on errors deleting node templates
     */
    public ToscaServiceTemplate deleteToscaNodeTemplate(@NonNull final String name, @Nonnull final String version)
        throws PfModelException {
        LOGGER.debug("->deleteToscaNodeTemplate: name={}, version={}", name, version);

        JpaToscaServiceTemplate dbServiceTemplate = getDefaultJpaToscaServiceTemplate();
        final var nodeTemplateKey = new PfConceptKey(name, version);

        if (!ToscaUtils.doNodeTemplatesExist(dbServiceTemplate)) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "no node templates found");
        }
        JpaToscaNodeTemplate nodeTemplate4Deletion = dbServiceTemplate.getTopologyTemplate().getNodeTemplates()
            .get(new PfConceptKey(name, version));
        if (nodeTemplate4Deletion == null) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "node template " + name + ":" + version
                + NOT_FOUND);
        }
        //Verify if the node template is referenced in the metadata of created policies
        nodeTemplateService.assertNodeTemplateNotUsedInPolicy(name, version, dbServiceTemplate);

        dbServiceTemplate.getTopologyTemplate().getNodeTemplates().getConceptMap().remove(nodeTemplateKey);
        toscaServiceTemplateRepository.save(dbServiceTemplate);

        // remove the entry from the tosca node template table
        nodeTemplateService.deleteNodeTemplate(nodeTemplateKey);

        // prepare the return service template
        var deletedServiceTemplate = new JpaToscaServiceTemplate();
        deletedServiceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate());
        deletedServiceTemplate.getTopologyTemplate().setNodeTemplates(new JpaToscaNodeTemplates());
        deletedServiceTemplate.getTopologyTemplate().getNodeTemplates().getConceptMap()
            .put(nodeTemplateKey, nodeTemplate4Deletion);

        LOGGER.debug("<-deleteToscaNodeTemplate: key={}, serviceTemplate={}", nodeTemplateKey, deletedServiceTemplate);
        return deletedServiceTemplate.toAuthorative();
    }


    /**
     * Get tosca node templates.
     *
     * @param name the name of the node template to get, set to null to get all node templates
     * @param version the version of the node template to get, set to null to get all versions
     * @return the node templates with the specified key
     * @throws PfModelException on errors getting node templates
     */
    public List<ToscaNodeTemplate> fetchToscaNodeTemplates(final String name, final String version)
        throws PfModelException {
        LOGGER.debug("->getNodeTemplate: name={}, version={}", name, version);
        List<ToscaNodeTemplate> nodeTemplates = new ArrayList<>();

        var dbServiceTemplate = getDefaultJpaToscaServiceTemplate();
        //Return empty if no nodeTemplates present in db
        if (!ToscaUtils.doNodeTemplatesExist(dbServiceTemplate)) {
            return nodeTemplates;
        }
        var jpaNodeTemplates = new JpaToscaNodeTemplates(dbServiceTemplate.getTopologyTemplate().getNodeTemplates());

        //Filter specific nodeTemplates
        if (name != null && version != null) {
            var filterKey = new PfConceptKey(name, version);
            jpaNodeTemplates.getConceptMap().entrySet().removeIf(entity -> !entity.getKey().equals(filterKey));
        }
        jpaNodeTemplates.getConceptMap().forEach((key, value) -> nodeTemplates.add(value.toAuthorative()));
        LOGGER.debug("<-getNodeTemplateMetadataSet: name={}, version={}, nodeTemplates={}", name, version,
            nodeTemplates);

        return nodeTemplates;
    }


    /**
     * Get Service Template.
     *
     * @return the Service Template read from the database
     * @throws PfModelRuntimeException if service template if not found in database.
     */
    public JpaToscaServiceTemplate getDefaultJpaToscaServiceTemplate() throws PfModelRuntimeException {
        final var defaultServiceTemplateOpt = getDefaultJpaToscaServiceTemplateOpt();
        if (defaultServiceTemplateOpt.isEmpty()) {
            throw new PfModelRuntimeException(Response.Status.NOT_FOUND, SERVICE_TEMPLATE_NOT_FOUND_MSG);
        }
        LOGGER.debug("<-getDefaultJpaToscaServiceTemplate: serviceTemplate={}", defaultServiceTemplateOpt.get());
        return defaultServiceTemplateOpt.get();
    }

    /**
     * Get Service Template Optional object.
     *
     * @return the Optional object for Service Template read from the database
     */
    private Optional<JpaToscaServiceTemplate> getDefaultJpaToscaServiceTemplateOpt() {
        return toscaServiceTemplateRepository
            .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION));
    }
}