[SDC] rebase 1710
[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 java.io.IOException;
24
25 import org.codehaus.jackson.JsonGenerationException;
26 import org.codehaus.jackson.map.DeserializationConfig;
27 import org.codehaus.jackson.map.JsonMappingException;
28 import org.codehaus.jackson.map.ObjectMapper;
29 import org.codehaus.jackson.map.SerializationConfig.Feature;
30 import org.codehaus.jackson.map.annotate.JsonSerialize;
31 import org.openecomp.sdc.be.config.BeEcompErrorManager;
32 import org.openecomp.sdc.be.model.ArtifactDefinition;
33 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
34 import org.openecomp.sdc.common.api.Constants;
35 import org.openecomp.sdc.common.config.EcompErrorName;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.gson.Gson;
40 import com.google.gson.JsonElement;
41 import com.google.gson.JsonObject;
42
43 public class RepresentationUtils {
44
45         private static Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName());
46
47         public static ArtifactDefinition convertJsonToArtifactDefinitionForUpdate(String content, Class<ArtifactDefinition> clazz) {
48
49                 JsonObject jsonElement = new JsonObject();
50                 ArtifactDefinition resourceInfo = null;
51
52                 try {
53                         Gson gson = new Gson();
54                         jsonElement = gson.fromJson(content, jsonElement.getClass());
55                         String payload = null;
56                         jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD);
57                         //in update the group type is ignored but this spagheti code makes it too complex to remove this field.
58                         jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, ArtifactGroupTypeEnum.INFORMATIONAL.getType());
59                         JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
60                         if (artifactPayload != null && !artifactPayload.isJsonNull()) {
61                                 payload = artifactPayload.getAsString();
62                         }
63                         jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
64                         String json = gson.toJson(jsonElement);
65                         ObjectMapper mapper = new ObjectMapper();
66                         mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
67                         mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
68                         mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
69
70                         resourceInfo = mapper.readValue(json, clazz);
71                         resourceInfo.setPayloadData(payload);
72
73                 } catch (Exception e) {
74                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update");
75                         BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
76                         log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
77                 }
78
79                 return resourceInfo;
80         }
81
82
83         public static class ResourceRep {
84
85         }
86
87         /**
88          * Build Representation of given Object
89          * 
90          * @param elementToRepresent
91          * @return
92          * @throws IOException
93          * @throws JsonGenerationException
94          * @throws JsonMappingException
95          */
96         public static <T> Object toRepresentation(T elementToRepresent) throws IOException, JsonGenerationException, JsonMappingException {
97
98                 // return theResource;
99                 ObjectMapper mapper = new ObjectMapper();
100                 mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
101                 mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
102                 return mapper.writeValueAsString(elementToRepresent);
103         }
104
105         public static <T> T fromRepresentation(String json, Class<T> clazz) {
106                 ObjectMapper mapper = new ObjectMapper();
107                 T object = null;
108                 mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
109                 mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
110                 mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
111                 try {
112                         object = mapper.readValue(json, clazz);
113                 } catch (Exception e) {
114                         log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e);
115                 } // return null in case of exception
116
117                 return object;
118         }
119
120         public static ArtifactDefinition convertJsonToArtifactDefinition(String content, Class<ArtifactDefinition> clazz) {
121
122                 JsonObject jsonElement = new JsonObject();
123                 ArtifactDefinition resourceInfo = null;
124                 
125                 try {
126                         Gson gson = new Gson();
127                         jsonElement = gson.fromJson(content, jsonElement.getClass());
128                         JsonElement artifactGroupValue = jsonElement.get(Constants.ARTIFACT_GROUP_TYPE_FIELD);
129                         if (artifactGroupValue != null && !artifactGroupValue.isJsonNull()) {
130                                 String groupValueUpper = artifactGroupValue.getAsString().toUpperCase();
131                                 if (!ArtifactGroupTypeEnum.getAllTypes().contains(groupValueUpper)) {
132                                         StringBuilder sb = new StringBuilder();
133                                         for (String value : ArtifactGroupTypeEnum.getAllTypes()) {
134                                                 sb.append(value).append(", ");
135                                         }
136                                         log.debug("artifactGroupType is {}. valid values are: {}", groupValueUpper, sb.toString());
137                                         return null;
138                                 } else {
139                                         jsonElement.remove(Constants.ARTIFACT_GROUP_TYPE_FIELD);
140                                         jsonElement.addProperty(Constants.ARTIFACT_GROUP_TYPE_FIELD, groupValueUpper);
141                                 }
142                         }
143                         String payload = null;
144                         JsonElement artifactPayload = jsonElement.get(Constants.ARTIFACT_PAYLOAD_DATA);
145                         if (artifactPayload != null && !artifactPayload.isJsonNull()) {
146                                 payload = artifactPayload.getAsString();
147                         }
148                         jsonElement.remove(Constants.ARTIFACT_PAYLOAD_DATA);
149                         String json = gson.toJson(jsonElement);
150                         ObjectMapper mapper = new ObjectMapper();
151                         mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
152                         mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
153                         mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
154                         
155                         resourceInfo = mapper.readValue(json, clazz);
156                         resourceInfo.setPayloadData(payload);
157
158                 } catch (Exception e) {
159                         BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactInformationInvalidError, "Artifact Upload / Update");
160                         BeEcompErrorManager.getInstance().logBeArtifactInformationInvalidError("Artifact Upload / Update");
161                         log.debug("Failed to convert the content {} to object.", content.substring(0, Math.min(50, content.length())), e);
162                 }
163
164                 return resourceInfo;
165         }
166
167 }