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