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