Interface operation feature enhancements
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / servlets / RepresentationUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.be.servlets;
22
23 import com.fasterxml.jackson.annotation.JsonFilter;
24 import com.fasterxml.jackson.annotation.JsonInclude;
25 import com.fasterxml.jackson.databind.DeserializationFeature;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import com.fasterxml.jackson.databind.SerializationFeature;
28 import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter.SerializeExceptFilter;
29 import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
30 import com.google.common.collect.ImmutableMap;
31 import com.google.gson.Gson;
32 import com.google.gson.JsonElement;
33 import com.google.gson.JsonObject;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.Collection;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.List;
40 import java.util.Set;
41 import org.openecomp.sdc.be.config.BeEcompErrorManager;
42 import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition;
43 import org.openecomp.sdc.be.model.ArtifactDefinition;
44 import org.openecomp.sdc.be.model.InterfaceDefinition;
45 import org.openecomp.sdc.be.model.Resource;
46 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
47 import org.openecomp.sdc.common.api.Constants;
48 import org.openecomp.sdc.common.log.wrappers.Logger;
49
50 public class RepresentationUtils {
51
52     private static final Logger log = Logger.getLogger(RepresentationUtils.class);
53
54     public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
55
56         JsonObject jsonElement = new JsonObject();
57         ArtifactDefinition resourceInfo = null;
58
59         try {
60             Gson gson = new Gson();
61             jsonElement = gson.fromJson(content, jsonElement.getClass());
62             String payload = null;
63             jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
64             //in update the group type is ignored but this spagheti code makes it too complex to remove this field.
65             jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
66             JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
67             if (artifactPayload != null && !artifactPayload.isJsonNull()) {
68                 payload = artifactPayload.getAsString();
69             }
70             jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
71             String json = gson.toJson(jsonElement);
72             ObjectMapper mapper = new ObjectMapper();
73             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
74             mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
75             mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
76
77             resourceInfo = mapper.readValue(json, clazz);
78             resourceInfo.setPayloadData(payload);
79
80         } catch (Exception e) {
81             BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
82             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
83         }
84
85         return resourceInfo;
86     }
87
88
89     public static class ResourceRep {
90
91     }
92
93     /**
94      * Build Representation of given Object
95      *
96      * @param elementToRepresent
97      * @return
98      * @throws IOException
99      */
100     public static <T> Object toRepresentation(T elementToRepresent) throws IOException {
101
102         ObjectMapper mapper = new ObjectMapper();
103         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
104         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
105         return mapper.writeValueAsString(elementToRepresent);
106     }
107
108     public static <T> T fromRepresentation(String json, Class<T> clazz) {
109         ObjectMapper mapper = new ObjectMapper();
110         T object = null;
111         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
112         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
113         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
114         try {
115             object = mapper.readValue(json, clazz);
116         } catch (Exception e) {
117             log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
118         } // return null in case of exception
119
120         return object;
121     }
122
123     public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) {
124
125         JsonObject jsonElement = new JsonObject();
126         ArtifactDefinition resourceInfo = null;
127
128         try {
129             Gson gson = new Gson();
130             jsonElement = gson.fromJson(content, jsonElement.getClass());
131             JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE);
132             if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) {
133                 String groupValueUpper = artifactGroupValue.getAsString().toUpperCase();
134                 if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) {
135                     StringBuilder sb = new StringBuilder();
136                     for (String value : ArtifactGroupTypeEnum.getAllTypes()) {
137                         sb.append(value).append(", ");
138                     }
139                     log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb);
140                     return null;
141                 } else {
142                     jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE);
143                     jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE, groupValueUpper);
144                 }
145             }
146             String payload = null;
147             JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
148             if (artifactPayload != null && !artifactPayload.isJsonNull()) {
149                 payload = artifactPayload.getAsString();
150             }
151             jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
152             String json = gson.toJson(jsonElement);
153             ObjectMapper mapper = new ObjectMapper();
154             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
155             mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
156             mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
157
158             resourceInfo = mapper.readValue(json, clazz);
159             resourceInfo.setPayloadData(payload);
160
161         } catch (Exception e) {
162             BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
163             log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
164         }
165
166         return resourceInfo;
167     }
168
169     public static <T> Object toFilteredRepresentation(T elementToRepresent) throws IOException {
170         ObjectMapper mapper = new ObjectMapper();
171         mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
172         mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
173         mapper.setMixIns(IS_EMPTY_FILTER_MIXIN);
174         return mapper.writer(new SimpleFilterProvider().addFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER,
175                 SerializeExceptFilter.serializeAllExcept(EMPTY))).writeValueAsString(elementToRepresent);
176     }
177
178     @JsonFilter(REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER)
179     private static class IsEmptyFilterMixIn {}
180
181     private static final String EMPTY = "empty";
182     private static final String REMOVE_IS_EMPTY_FROM_COLLECTIONS_FILTER = "removeIsEmptyFromCollections";
183     private static final ImmutableMap<Class<?>,Class<?>> IS_EMPTY_FILTER_MIXIN =
184             ImmutableMap.<Class<?>,Class<?>>builder()
185                     .put(Collection.class,IsEmptyFilterMixIn.class)
186                     .put(List.class,IsEmptyFilterMixIn.class)
187                     .put(Set.class,IsEmptyFilterMixIn.class)
188                     .put(HashMap.class,IsEmptyFilterMixIn.class)
189                     .put(ArrayList.class,IsEmptyFilterMixIn.class)
190                     .put(HashSet.class,IsEmptyFilterMixIn.class)
191                     .put(InterfaceDefinition.class,IsEmptyFilterMixIn.class)
192                     .put(Resource.class,IsEmptyFilterMixIn.class)
193                     .put(ToscaDataDefinition.class,IsEmptyFilterMixIn.class)
194                     .build();
195
196 }