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