aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/client/req/SdcReq.java
blob: 640d3b0cdf520ae77166e5e394f9e4b3be34e5be (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2017 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============================================
 * ===================================================================
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */

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

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.digest.DigestUtils;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.onap.clamp.clds.client.SdcCatalogServices;
import org.onap.clamp.clds.model.CldsSdcResource;
import org.onap.clamp.clds.model.CldsSdcServiceDetail;
import org.onap.clamp.clds.model.prop.Global;
import org.onap.clamp.clds.model.prop.ModelProperties;
import org.onap.clamp.clds.model.prop.Tca;
import org.onap.clamp.clds.model.refprop.RefProp;

/**
 * Construct a Sdc request given CLDS objects.
 */
public class SdcReq {
    protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(SdcReq.class);
    protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();

    /**
     * Format the Blueprint from a Yaml
     *
     * @param refProp
     *            The RefProp instance containing the Clds config
     * @param prop
     *            The ModelProperties describing the clds model
     * @param docText
     *            The Yaml file that must be converted
     *
     * @return A String containing the BluePrint
     * @throws JsonParseException
     *             In case of issues
     * @throws JsonMappingException
     *             In case of issues
     * @throws IOException
     *             In case of issues
     */
    public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
            throws JsonParseException, JsonMappingException, IOException {

        Global globalProp = prop.getGlobal();
        String service = globalProp.getService();

        String yamlvalue = getYamlvalue(docText);

        String updatedBlueprint = "";
        Tca tca = prop.getType(Tca.class);
        if (tca.isFound()) {
            updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
        }
        logger.info("value of blueprint:" + updatedBlueprint);
        return updatedBlueprint;
    }

    public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
        ObjectMapper objectMapper = new ObjectMapper();
        Global global = prop.getGlobal();
        List<String> locationsList = global.getLocation();
        ArrayNode locationsArrayNode = objectMapper.createArrayNode();
        ObjectNode locationObject = objectMapper.createObjectNode();
        for (String currLocation : locationsList) {
            locationsArrayNode.add(currLocation);
        }
        locationObject.put("artifactName", artifactName);
        locationObject.putPOJO("locations", locationsArrayNode);
        String locationJsonFormat = locationObject.toString();
        logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
        return locationJsonFormat;
    }

    public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
            String artifactType) throws IOException {
        logger.info("artifact=" + payloadData);
        String base64Artifact = base64Encode(payloadData);
        return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
                + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
                + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
                + "} \n";
    }

    public static String getSdcReqUrl(ModelProperties prop, String url) {
        Global globalProps = prop.getGlobal();
        String serviceUUID = "";
        String resourceInstanceName = "";
        if (globalProps != null) {
            List<String> resourceVf = globalProps.getResourceVf();
            if (resourceVf != null && !resourceVf.isEmpty()) {
                resourceInstanceName = resourceVf.get(0);
            }
            if (globalProps.getService() != null) {
                serviceUUID = globalProps.getService();
            }
        }
        String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
        return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
    }

    /**
     * To get List of urls for all vfresources
     *
     * @param prop
     * @param baseUrl
     * @param sdcCatalogServices
     * @return
     */
    public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
            SdcCatalogServices sdcCatalogServices, DelegateExecution execution) {
        // TODO : refact and regroup with very similar code
        List<String> urlList = new ArrayList<>();

        Global globalProps = prop.getGlobal();
        if (globalProps != null) {
            if (globalProps.getService() != null) {
                String serviceInvariantUUID = globalProps.getService();
                execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
                List<String> resourceVfList = globalProps.getResourceVf();
                String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
                String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
                CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
                        .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
                if (cldsSdcServiceDetail != null && resourceVfList != null) {
                    List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
                    if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
                        for (CldsSdcResource CldsSdcResource : cldsSdcResourcesList) {
                            if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
                                    && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
                                    && resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
                                String normalizedResourceInstanceName = normalizeResourceInstanceName(
                                        CldsSdcResource.getResourceInstanceName());
                                String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
                                        + normalizedResourceInstanceName + "/artifacts";
                                urlList.add(svcUrl);
                            }
                        }
                    }
                }
            }
        }

        return urlList;
    }

    /**
     * "Normalize" the resource instance name: - Remove spaces, underscores,
     * dashes, and periods. - make lower case This is required by SDC when using
     * the resource instance name to upload an artifact.
     *
     * @param inText
     * @return
     */
    public static String normalizeResourceInstanceName(String inText) {
        return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
    }

    /**
     * from michael
     *
     * @param data
     * @return
     */
    public static String calculateMD5ByString(String data) {
        String calculatedMd5 = DigestUtils.md5Hex(data);
        // encode base-64 result
        return base64Encode(calculatedMd5.getBytes());
    }

    /**
     * Base 64 encode a String.
     *
     * @param inText
     * @return
     */
    public static String base64Encode(String inText) {
        return base64Encode(stringToByteArray(inText));
    }

    /**
     * Convert String to byte array.
     *
     * @param inText
     * @return
     */
    public static byte[] stringToByteArray(String inText) {
        return inText.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * Base 64 encode a byte array.
     *
     * @param bytes
     * @return
     */
    public static String base64Encode(byte[] bytes) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(bytes);
    }

    /**
     * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
     * dGVzdDoxMjM0NTY=).
     *
     * @return
     */
    public static String getSdcBasicAuth(RefProp refProp) {
        String sdcId = refProp.getStringValue("sdc.serviceUsername");
        String sdcPw = refProp.getStringValue("sdc.servicePassword");
        String idPw = base64Encode(sdcId + ":" + sdcPw);
        return "Basic " + idPw;
    }

    /**
     * Method to get yaml/template properties value from json
     *
     * @param docText
     * @return
     * @throws IOException
     */
    public static String getYamlvalue(String docText) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String yamlFileValue = "";
        ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
        Iterator<Entry<String, JsonNode>> entryItr = root.fields();
        while (entryItr.hasNext()) {
            Entry<String, JsonNode> entry = entryItr.next();
            String key = entry.getKey();
            if (key != null && key.equalsIgnoreCase("global")) {
                ArrayNode arrayNode = (ArrayNode) entry.getValue();
                for (JsonNode anArrayNode : arrayNode) {
                    ObjectNode node = (ObjectNode) anArrayNode;
                    ArrayNode arrayValueNode = (ArrayNode) node.get("value");
                    JsonNode jsonNode = arrayValueNode.get(0);
                    yamlFileValue = jsonNode.asText();
                    logger.info("value:" + yamlFileValue);
                }
                break;
            }
        }
        return yamlFileValue;
    }
}