6b5cdcd82a2ce67448fd0d9c89c6ddffd602eb3b
[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.OxmModelLoader;
35 import org.onap.schema.EdgeRulesLoader;
36
37 import com.google.gson.Gson;
38 import com.google.gson.JsonElement;
39 import com.google.gson.JsonPrimitive;
40
41 public class CrudServiceUtil {
42
43   private static Gson gson = new Gson();
44   
45   @SuppressWarnings({"unchecked", "rawtypes"})
46   public static Object validateFieldType(String value, Class clazz) throws CrudException {
47     try {
48       if (clazz.isAssignableFrom(Integer.class)) {
49         return Integer.parseInt(value);
50       } else if (clazz.isAssignableFrom(Long.class)) {
51         return Long.parseLong(value);
52       } else if (clazz.isAssignableFrom(Float.class)) {
53         return Float.parseFloat(value);
54       } else if (clazz.isAssignableFrom(Double.class)) {
55         return Double.parseDouble(value);
56       } else if (clazz.isAssignableFrom(Boolean.class)) {
57
58                 // If the value is an IN/OUT direction, this gets seen as a boolean, so
59         // check for that first.
60         if (value.equals("OUT") || value.equals("IN")) {
61           return value;
62         }
63
64         if (!value.equals("true") && !value.equals("false")) {
65           throw new CrudException("Invalid propertry value: " + value, Status.BAD_REQUEST);
66         }
67         return Boolean.parseBoolean(value);
68       } else {
69         return value;
70       }
71     } catch (Exception e) {
72       throw new CrudException("Invalid property value: " + value, Status.BAD_REQUEST);
73     }
74   }
75
76   public static void loadModels() throws CrudException {
77     // load the schemas
78     try {
79       OxmModelLoader.loadModels();
80       EdgeRulesLoader.loadModels ();
81     } catch (Exception e) {
82       throw new CrudException(e);
83     }
84   }
85
86   /**
87    * This method will merge header property from app id in request payload if not already populated
88    * @param propertiesFromRequest
89    * @param headers
90    * @param isAdd
91    * @return
92    */
93     @SuppressWarnings("unchecked")
94     public static JsonElement mergeHeaderInFoToPayload(JsonElement propertiesFromRequest, HttpHeaders headers,
95             boolean isAdd) {
96     String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");  
97     Set<Map.Entry<String, JsonElement>> properties = new HashSet<Map.Entry<String, JsonElement>>();
98     properties.addAll(propertiesFromRequest.getAsJsonObject().entrySet());
99     
100     Set<String> propertyKeys = new HashSet<String>();
101     for(Map.Entry<String, JsonElement> property : properties) {
102       propertyKeys.add(property.getKey());
103     }
104     
105     if(!propertyKeys.contains(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH)) {
106         properties.add(new AbstractMap.SimpleEntry<String, JsonElement>(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH,
107             (new JsonPrimitive(sourceOfTruth))));
108     }
109    
110     if(isAdd && !propertyKeys.contains(AAIProperties.SOURCE_OF_TRUTH)) {
111         properties.add(new AbstractMap.SimpleEntry<String, JsonElement>(AAIProperties.SOURCE_OF_TRUTH,
112             (new JsonPrimitive(sourceOfTruth))));
113     }
114
115     Object[] propArray = properties.toArray();
116     StringBuilder sb = new StringBuilder();
117     sb.append("{");
118     boolean first=true;
119     for(int i=0; i<propArray.length; i++) {
120
121       Map.Entry<String, JsonElement> entry = (Entry<String, JsonElement>) propArray[i];
122       if(!first) {
123         sb.append(",");
124       }
125       sb.append("\"").append(entry.getKey()).append("\"").append(":").append(entry.getValue());
126       first=false;
127     }
128     sb.append("}");
129
130     return gson.fromJson(sb.toString(), JsonElement.class);
131   }
132
133   public static EntityTag getETagFromHeader(MultivaluedMap<String, String> headers) {
134     EntityTag entityTag = null;
135     if (headers != null && headers.containsKey(CrudServiceConstants.CRD_HEADER_ETAG)) {
136       String value = headers.getFirst(CrudServiceConstants.CRD_HEADER_ETAG);
137       entityTag = new EntityTag(value.replace("\"", ""));
138     }
139     return entityTag;
140   }
141
142 }