2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.openecomp.sdc.be.servlets;
22 import com.fasterxml.jackson.annotation.JsonFilter;
23 import com.fasterxml.jackson.annotation.JsonInclude;
24 import com.fasterxml.jackson.databind.DeserializationFeature;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.databind.SerializationFeature;
27 import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter.SerializeExceptFilter;
28 import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
29 import com.google.common.collect.ImmutableMap;
30 import com.google.gson.Gson;
31 import com.google.gson.JsonElement;
32 import com.google.gson.JsonObject;
33 import java.io.IOException;
34 import java.util.ArrayList;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
40 import org.apache.commons.lang3.StringUtils;
41 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
42 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager;
44 import org.openecomp.sdc.be.dao.api.ActionStatus;
45 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
46 import org.openecomp.sdc.be.model.ArtifactDefinition;
47 import org.openecomp.sdc.be.model.InterfaceDefinition;
48 import org.openecomp.sdc.be.model.Resource;
49 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
50 import org.openecomp.sdc.common.api.Constants;
51 import org.openecomp.sdc.common.log.wrappers.Logger;
53 public class RepresentationUtils {
55 private static final Logger log = Logger.getLogger(RepresentationUtils.class);
56 private static final String EMPTY = "empty";
57 private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections";
58 private static final ImmutableMap<Class<?>, Class<?>> IS_EMPTY_FILTER_MIXIN = ImmutableMap.<Class<?>, Class<?>>builder()
59 .put(Collection.class, IsEmptyFilterMixIn.class).put(List.class, IsEmptyFilterMixIn.class).put(Set.class, IsEmptyFilterMixIn.class)
60 .put(HashMap.class, IsEmptyFilterMixIn.class).put(ArrayList.class, IsEmptyFilterMixIn.class).put(HashSet.class, IsEmptyFilterMixIn.class)
61 .put(InterfaceDefinition.class, IsEmptyFilterMixIn.class).put(Resource.class, IsEmptyFilterMixIn.class)
62 .put(ToscaDataDefinition.class, IsEmptyFilterMixIn.class).build();
64 public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
65 JsonObject jsonElement = new JsonObject();
66 ArtifactDefinition resourceInfo = null;
68 Gson gson = new Gson();
69 jsonElement = gson.fromJson(content, jsonElement.getClass());
70 String payload = null;
71 jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
72 //in update the group type is ignored but this spagheti code makes it too complex to remove this field.
73 jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
74 JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
75 if (artifactPayload != null && !artifactPayload.isJsonNull()) {
76 payload = artifactPayload.getAsString();
78 jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
79 String json = gson.toJson(jsonElement);
80 ObjectMapper mapper = new ObjectMapper();
81 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
82 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
83 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
84 resourceInfo = mapper.readValue(json, clazz);
85 resourceInfo.setPayloadData(payload);
86 } catch (Exception e) {
87 BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
88 log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
94 * Build Representation of given Object
96 * @param elementToRepresent
100 public static <T> Object toRepresentation(T elementToRepresent) throws IOException {
101 ObjectMapper mapper = new ObjectMapper();
102 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
103 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
104 return mapper.writeValueAsString(elementToRepresent);
107 public static <T> T fromRepresentation(String json, Class<T> clazz) {
108 ObjectMapper mapper = new ObjectMapper();
110 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
111 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
112 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
114 object = mapper.readValue(json, clazz);
115 } catch (Exception e) {
116 log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
117 } // return null in case of exception
121 public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz, boolean validateTimeout) {
122 JsonObject jsonElement = new JsonObject();
123 ArtifactDefinition resourceInfo = null;
124 if (StringUtils.isEmpty(content)) {
125 throw new ByActionStatusComponentException(ActionStatus.MISSING_BODY);
128 Gson gson = new Gson();
129 jsonElement = gson.fromJson(content, jsonElement.getClass());
130 JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE);
131 HashMap<String, JsonElement> elementsToValidate = new HashMap<>();
132 elementsToValidate.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupValue);
133 elementsToValidate.put(Constants.ARTIFACT_TYPE, jsonElement.get(Constants.ARTIFACT_TYPE));
134 elementsToValidate.put(Constants.ARTIFACT_LABEL, (jsonElement.get(Constants.ARTIFACT_LABEL)));
135 if (validateTimeout) {
136 elementsToValidate.put(Constants.ARTIFACT_TIMEOUT, jsonElement.get(Constants.ARTIFACT_TIMEOUT));
138 validateMandatoryProperties(elementsToValidate);
139 if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) {
140 String groupValueUpper = artifactGroupValue.getAsString().toUpperCase();
141 if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) {
142 StringBuilder sb = new StringBuilder();
143 for (String value : ArtifactGroupTypeEnum.getAllTypes()) {
144 sb.append(value).append(", ");
146 log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb);
149 jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
150 jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, groupValueUpper);
153 String payload = null;
154 JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
155 if (artifactPayload != null && !artifactPayload.isJsonNull()) {
156 payload = artifactPayload.getAsString();
158 jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
159 String json = gson.toJson(jsonElement);
160 ObjectMapper mapper = new ObjectMapper();
161 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
162 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
163 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
164 resourceInfo = mapper.readValue(json, clazz);
165 resourceInfo.setPayloadData(payload);
166 } catch (ComponentException ce) {
167 BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
168 log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), ce);
170 } catch (Exception e) {
171 BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
172 log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
177 private static void validateMandatoryProperties(HashMap<String, JsonElement> elementsByName) {
178 elementsByName.forEach((name, element) -> {
179 if (element == null) {
180 throw new ByActionStatusComponentException(ActionStatus.MISSING_MANDATORY_PROPERTY, name);
182 if (element.isJsonNull()) {
183 throw new ByActionStatusComponentException(ActionStatus.MANDATORY_PROPERTY_MISSING_VALUE, name);
188 public static <T> Object toFilteredRepresentation(T elementToRepresent) throws IOException {
189 ObjectMapper mapper = new ObjectMapper();
190 mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
191 mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
192 mapper.setMixIns(IS_EMPTY_FILTER_MIXIN);
194 .writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER, SerializeExceptFilter.serializeAllExcept(EMPTY)))
195 .writeValueAsString(elementToRepresent);
198 public static class ResourceRep {
202 @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER)
203 private static class IsEmptyFilterMixIn {