ed5fe535323f2f8ed66400478dca2821f67d8642
[aai/gizmo.git] / src / main / java / org / onap / crud / util / CrudServiceUtil.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.crud.util;
22
23 import java.util.AbstractMap;
24 import java.util.HashSet;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Set;
28 import javax.ws.rs.core.EntityTag;
29 import javax.ws.rs.core.HttpHeaders;
30 import javax.ws.rs.core.MultivaluedMap;
31 import javax.ws.rs.core.Response.Status;
32 import org.onap.aai.db.props.AAIProperties;
33 import org.onap.crud.exception.CrudException;
34 import org.onap.schema.EdgeRulesLoader;
35 import org.onap.schema.OxmModelLoader;
36 import com.google.gson.Gson;
37 import com.google.gson.JsonElement;
38 import com.google.gson.JsonPrimitive;
39
40 public class CrudServiceUtil {
41
42   private static Gson gson = new Gson();
43   
44   @SuppressWarnings({"unchecked", "rawtypes"})
45   public static Object validateFieldType(String value, Class clazz) throws CrudException {
46     try {
47       if (clazz.isAssignableFrom(Integer.class)) {
48         return Integer.parseInt(value);
49       } else if (clazz.isAssignableFrom(Long.class)) {
50         return Long.parseLong(value);
51       } else if (clazz.isAssignableFrom(Float.class)) {
52         return Float.parseFloat(value);
53       } else if (clazz.isAssignableFrom(Double.class)) {
54         return Double.parseDouble(value);
55       } else if (clazz.isAssignableFrom(Boolean.class)) {
56
57                 // If the value is an IN/OUT direction, this gets seen as a boolean, so
58         // check for that first.
59         if (value.equals("OUT") || value.equals("IN")) {
60           return value;
61         }
62
63         if (!value.equals("true") && !value.equals("false")) {
64           throw new CrudException("Invalid propertry value: " + value, Status.BAD_REQUEST);
65         }
66         return Boolean.parseBoolean(value);
67       } else {
68         return value;
69       }
70     } catch (Exception e) {
71       throw new CrudException("Invalid property value: " + value, Status.BAD_REQUEST);
72     }
73   }
74
75   public static void loadModels() throws CrudException {
76     // load the schemas
77     try {
78       OxmModelLoader.loadModels();
79       EdgeRulesLoader.loadModels ();
80     } catch (Exception e) {
81       throw new CrudException(e);
82     }
83   }
84
85   /**
86    * This method will merge header property from app id in request payload if not already populated
87    * @param propertiesFromRequest
88    * @param headers
89    * @param isAdd
90    * @return
91    */
92     @SuppressWarnings("unchecked")
93     public static JsonElement mergeHeaderInFoToPayload(JsonElement propertiesFromRequest, HttpHeaders headers,
94             boolean isAdd) {
95     String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");  
96     Set<Map.Entry<String, JsonElement>> properties = new HashSet<Map.Entry<String, JsonElement>>();
97     properties.addAll(propertiesFromRequest.getAsJsonObject().entrySet());
98     
99     Set<String> propertyKeys = new HashSet<String>();
100     for(Map.Entry<String, JsonElement> property : properties) {
101       propertyKeys.add(property.getKey());
102     }
103     
104     if(!propertyKeys.contains(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH)) {
105         properties.add(new AbstractMap.SimpleEntry<String, JsonElement>(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH,
106             (new JsonPrimitive(sourceOfTruth))));
107     }
108    
109     if(isAdd && !propertyKeys.contains(AAIProperties.SOURCE_OF_TRUTH)) {
110         properties.add(new AbstractMap.SimpleEntry<String, JsonElement>(AAIProperties.SOURCE_OF_TRUTH,
111             (new JsonPrimitive(sourceOfTruth))));
112     }
113
114     Object[] propArray = properties.toArray();
115     StringBuilder sb = new StringBuilder();
116     sb.append("{");
117     boolean first=true;
118     for(int i=0; i<propArray.length; i++) {
119
120       Map.Entry<String, JsonElement> entry = (Entry<String, JsonElement>) propArray[i];
121       if(!first) {
122         sb.append(",");
123       }
124       sb.append("\"").append(entry.getKey()).append("\"").append(":").append(entry.getValue());
125       first=false;
126     }
127     sb.append("}");
128
129     return gson.fromJson(sb.toString(), JsonElement.class);
130   }
131
132   public static EntityTag getETagFromHeader(MultivaluedMap<String, String> headers) {
133     EntityTag entityTag = null;
134     if (headers != null && headers.containsKey(CrudServiceConstants.CRD_HEADER_ETAG)) {
135       String value = headers.getFirst(CrudServiceConstants.CRD_HEADER_ETAG);
136       entityTag = new EntityTag(value.replace("\"", ""));
137     }
138     return entityTag;
139   }
140
141 }