2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2019 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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.schemaif.json;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.io.StringWriter;
27 import java.util.Arrays;
28 import java.util.HashSet;
30 import java.util.Scanner;
32 import java.util.concurrent.ConcurrentHashMap;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipInputStream;
36 import org.onap.aai.cl.api.Logger;
37 import org.onap.aai.cl.eelf.LoggerFactory;
38 import org.onap.aai.schemaif.SchemaProvider;
39 import org.onap.aai.schemaif.SchemaProviderException;
40 import org.onap.aai.schemaif.SchemaProviderMsgs;
41 import org.onap.aai.schemaif.definitions.EdgeSchema;
42 import org.onap.aai.schemaif.definitions.VertexSchema;
43 import org.onap.aai.schemaif.json.definitions.JsonEdgeSchema;
44 import org.onap.aai.schemaif.json.definitions.JsonSchema;
45 import org.onap.aai.schemaif.json.definitions.JsonVertexSchema;
46 import org.springframework.http.HttpEntity;
47 import org.springframework.http.HttpHeaders;
48 import org.springframework.http.HttpMethod;
49 import org.springframework.http.HttpStatus;
50 import org.springframework.http.ResponseEntity;
51 import org.springframework.web.client.RestTemplate;
54 public class JsonSchemaProvider implements SchemaProvider {
55 Logger logger = LoggerFactory.getInstance().getLogger(JsonSchemaProvider.class.getName());
57 private JsonSchemaProviderConfig config;
58 private Map<String,SchemaInstance> schemaCache = new ConcurrentHashMap<>();
59 private RestTemplate restTemplate = null;
61 public JsonSchemaProvider(JsonSchemaProviderConfig config) {
64 SecureClientHttpRequestFactory fac = new SecureClientHttpRequestFactory(config);
65 fac.setBufferRequestBody(false);
66 this.restTemplate = new RestTemplate(fac);
70 public void loadSchema() throws SchemaProviderException {
71 // Load the latest schema version
72 fetchSchemaVersion(getLatestSchemaVersion());
76 public String getLatestSchemaVersion() throws SchemaProviderException {
81 public VertexSchema getVertexSchema(String vertexName, String schemaVersion) throws SchemaProviderException {
82 SchemaInstance inst = getSchemaVersion(schemaVersion);
83 return inst.getVertexSchema(vertexName);
87 public EdgeSchema getEdgeSchema(String edgeType, String sourceVertex, String targetVertex, String version)
88 throws SchemaProviderException {
89 SchemaInstance inst = getSchemaVersion(version);
90 return inst.getEdgeSchema(sourceVertex, targetVertex, edgeType);
94 public Set<EdgeSchema> getAdjacentEdgeSchema(String vertexType, String version) throws SchemaProviderException {
95 SchemaInstance inst = getSchemaVersion(version);
97 Set<EdgeSchema> edgeList = inst.getEdgeSchema(vertexType);
98 if (edgeList == null) {
99 edgeList = new HashSet<EdgeSchema>();
106 public Set<EdgeSchema> getEdgeSchemaForSourceTarget(String sourceType, String targetType, String version)
107 throws SchemaProviderException {
108 SchemaInstance inst = getSchemaVersion(version);
111 throw new SchemaProviderException("Unable to find schema version " + version);
114 Set<EdgeSchema> edgeList = inst.getEdgeSchemas(sourceType, targetType);
115 if (edgeList == null) {
116 edgeList = new HashSet<EdgeSchema>();
122 public void loadSchema(String payload, String version) throws SchemaProviderException {
123 JsonSchema jsonSchema = JsonSchema.fromJson(payload);
124 SchemaInstance schemaInst = new SchemaInstance();
126 for (JsonVertexSchema jsonVertex : jsonSchema.getNodeTypes()) {
127 FromJsonVertexSchema vSchema = new FromJsonVertexSchema();
128 vSchema.fromJson(jsonVertex, jsonSchema.getDataTypes(), jsonSchema.getCommonProperties());
129 schemaInst.addVertex(vSchema);
132 for (JsonEdgeSchema jsonEdge : jsonSchema.getRelationshipTypes()) {
133 FromJsonEdgeSchema eSchema = new FromJsonEdgeSchema();
134 eSchema.fromJson(jsonEdge);
135 schemaInst.addEdge(eSchema);
138 schemaCache.put(version, schemaInst);
141 private synchronized void fetchSchemaVersion(String version) throws SchemaProviderException {
142 if (schemaCache.get(version) != null) {
147 String url = config.getSchemaServiceBaseUrl() + "/" + version;
149 HttpHeaders headers = new HttpHeaders();
150 headers.put("X-FromAppId", Arrays.asList(config.getServiceName()));
151 headers.put("X-TransactionId", Arrays.asList(java.util.UUID.randomUUID().toString()));
152 headers.setAccept(Arrays.asList(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM));
154 HttpEntity <String> entity = new HttpEntity<String>(headers);
156 ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
159 if (response.getStatusCodeValue() == HttpStatus.NOT_FOUND.value()) {
160 logger.warn(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "version " + version + " not found");
161 throw new SchemaProviderException("Schema version " + version + " not found");
163 else if (response.getStatusCodeValue() != HttpStatus.OK.value()) {
164 logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "failed to load version " + version + ": " + response.getBody());
165 throw new SchemaProviderException("Error getting schema version " + version + ":" + response.getBody());
169 SchemaServiceResponse resp = SchemaServiceResponse.fromJson(unzipAndGetJSONString(response));
170 loadSchema(resp.getData().toJson(), version);
172 catch (Exception ex) {
173 StringWriter writer = new StringWriter();
174 PrintWriter printWriter = new PrintWriter(writer);
175 ex.printStackTrace(printWriter);
176 logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "failed to load version " + version + ": "
177 + response.getBody() + "\n" + writer.toString());
178 throw new SchemaProviderException("Error loading schema version " + version + ":" + ex.getMessage());
182 logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, version);
185 private String unzipAndGetJSONString(ResponseEntity<byte[]> response) throws IOException {
186 StringBuffer sb = new StringBuffer("");
188 ZipInputStream zipStream = null;
191 zipStream = new ZipInputStream(new ByteArrayInputStream(response.getBody()));
192 ZipEntry entry = null;
193 while ((entry = zipStream.getNextEntry()) != null) {
194 Scanner sc = new Scanner(zipStream);
195 while (sc.hasNextLine()) {
196 sb.append(sc.nextLine());
202 zipStream.closeEntry();
204 } catch (Exception e) {
205 logger.warn(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, e.toString());
210 return sb.toString();
213 private SchemaInstance getSchemaVersion(String version) throws SchemaProviderException {
214 // TODO: For now, we are only supporting a single version of the schema. Load that
215 // version regardless of what the client asks for.
216 String versionToLoad = getLatestSchemaVersion();
217 SchemaInstance inst = schemaCache.get(versionToLoad);
220 fetchSchemaVersion(versionToLoad);
221 inst = schemaCache.get(versionToLoad);
223 throw new SchemaProviderException("Unable to find schema version " + versionToLoad);
231 public Map<String, VertexSchema> getVertexMap(String schemaVersion) throws SchemaProviderException {
232 return getSchemaVersion(schemaVersion).getVertexMap();