aboutsummaryrefslogtreecommitdiffstats
path: root/runtime/src/main/java/org/onap/policy/clamp/clds/client/DcaeInventoryServices.java
blob: 8431070403f98dc0a983dab73bd2e93ca8c09b8b (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP POLICY-CLAMP
 * ================================================================================
 * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END============================================
 * Modifications copyright (c) 2018 Nokia
 * ===================================================================
 *
 */

package org.onap.policy.clamp.clds.client;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import java.io.IOException;
import java.util.Date;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.ExchangeBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.onap.policy.clamp.clds.config.ClampProperties;
import org.onap.policy.clamp.clds.model.dcae.DcaeInventoryResponse;
import org.onap.policy.clamp.clds.util.JsonUtils;
import org.onap.policy.clamp.clds.util.LoggingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * This class implements the communication with DCAE for the service inventory.
 */
@Component
public class DcaeInventoryServices {

    @Autowired
    CamelContext camelContext;

    protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);
    protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
    public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";
    public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";
    public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";
    private final ClampProperties refProp;

    /**
     * Constructor.
     */
    @Autowired
    public DcaeInventoryServices(ClampProperties refProp) {
        this.refProp = refProp;
    }

    private int getTotalCountFromDcaeInventoryResponse(String responseStr) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj0 = parser.parse(responseStr);
        JSONObject jsonObj = (JSONObject) obj0;
        Long totalCount = (Long) jsonObj.get("totalCount");
        return totalCount.intValue();
    }

    private DcaeInventoryResponse getItemsFromDcaeInventoryResponse(String responseStr) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj0 = parser.parse(responseStr);
        JSONObject jsonObj = (JSONObject) obj0;
        JSONArray itemsArray = (JSONArray) jsonObj.get("items");
        JSONObject dcaeServiceType0 = (JSONObject) itemsArray.get(0);
        return JsonUtils.GSON.fromJson(dcaeServiceType0.toString(), DcaeInventoryResponse.class);
    }

    /**
     * DO a query to DCAE to get some Information.
     *
     * @param artifactName The artifact Name
     * @param serviceUuid  The service UUID
     * @param resourceUuid The resource UUID
     * @return The DCAE inventory for the artifact in DcaeInventoryResponse
     * @throws IOException    In case of issues with the stream
     * @throws ParseException In case of issues with the Json parsing
     */
    public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)
            throws IOException, ParseException, InterruptedException {
        LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");

        int retryInterval = 0;
        int retryLimit = 1;
        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT) != null) {
            retryLimit = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_LIMIT));
        }
        if (refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL) != null) {
            retryInterval = Integer.valueOf(refProp.getStringValue(DCAE_INVENTORY_RETRY_INTERVAL));
        }
        for (int i = 0; i < retryLimit; i++) {
            metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");
            try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) {
                Exchange exchangeResponse = producerTemplate
                        .send("direct:get-dcae-blueprint-inventory", ExchangeBuilder.anExchange(camelContext)
                                .withProperty("blueprintResourceId", resourceUuid)
                                .withProperty("blueprintServiceId", serviceUuid)
                                .withProperty("blueprintName", artifactName)
                                .withProperty("raiseHttpExceptionFlag", false).build());

                if (HttpStatus.valueOf((Integer) exchangeResponse.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE))
                        .is2xxSuccessful()) {
                    String dcaeResponse = (String) exchangeResponse.getIn().getBody();
                    int totalCount = getTotalCountFromDcaeInventoryResponse(dcaeResponse);
                    metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);
                    if (totalCount > 0) {
                        logger.info("getDcaeInformation, answer from DCAE inventory:" + dcaeResponse);
                        LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());
                        Date startTime = new Date();
                        LoggingUtils.setTimeContext(startTime, new Date());
                        return getItemsFromDcaeInventoryResponse(dcaeResponse);
                    } else {
                        logger.info("Dcae inventory totalCount returned is 0, so waiting " + retryInterval
                                + "ms before retrying ...");
                        // wait for a while and try to connect to DCAE again
                        Thread.sleep(retryInterval);
                    }
                }
            }
        }
        logger.warn("Dcae inventory totalCount returned is still 0, after " + retryLimit + " attempts, returning NULL");
        return null;
    }
}