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.BufferedOutputStream;
24 import java.io.ByteArrayInputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.PrintWriter;
27 import java.io.StringWriter;
28 import java.util.Arrays;
29 import java.util.HashSet;
31 import java.util.Scanner;
33 import java.util.concurrent.ConcurrentHashMap;
34 import java.util.zip.ZipEntry;
35 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<>();
106 public Set<EdgeSchema> getEdgeSchemaForSourceTarget(String sourceType, String targetType, String version)
107 throws SchemaProviderException {
108 SchemaInstance inst = getSchemaVersion(version);
110 Set<EdgeSchema> edgeList = inst.getEdgeSchemas(sourceType, targetType);
111 if (edgeList == null) {
112 edgeList = new HashSet<>();
118 public void loadSchema(String payload, String version) throws SchemaProviderException {
119 JsonSchema jsonSchema = JsonSchema.fromJson(payload);
120 SchemaInstance schemaInst = new SchemaInstance();
122 for (JsonVertexSchema jsonVertex : jsonSchema.getNodeTypes()) {
123 FromJsonVertexSchema vSchema = new FromJsonVertexSchema();
124 vSchema.fromJson(jsonVertex, jsonSchema.getDataTypes(), jsonSchema.getCommonProperties());
125 schemaInst.addVertex(vSchema);
128 for (JsonEdgeSchema jsonEdge : jsonSchema.getRelationshipTypes()) {
129 FromJsonEdgeSchema eSchema = new FromJsonEdgeSchema();
130 eSchema.fromJson(jsonEdge);
131 schemaInst.addEdge(eSchema);
134 schemaCache.put(version, schemaInst);
137 private synchronized void fetchSchemaVersion(String version) throws SchemaProviderException {
138 if (schemaCache.get(version) != null) {
143 String url = config.getSchemaServiceBaseUrl() + "/" + version;
145 HttpHeaders headers = new HttpHeaders();
146 headers.put("X-FromAppId", Arrays.asList(config.getServiceName()));
147 headers.put("X-TransactionId", Arrays.asList(java.util.UUID.randomUUID().toString()));
148 headers.setAccept(Arrays.asList(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM));
150 HttpEntity <String> entity = new HttpEntity<>(headers);
152 ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class);
155 if (response.getStatusCodeValue() == HttpStatus.NOT_FOUND.value()) {
156 logger.warn(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "version " + version + " not found");
157 throw new SchemaProviderException("Schema version " + version + " not found");
159 else if (response.getStatusCodeValue() != HttpStatus.OK.value()) {
160 logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "failed to load version " + version + ": " + response.getBody());
161 throw new SchemaProviderException("Error getting schema version " + version + ":" + response.getBody());
165 SchemaServiceResponse resp = SchemaServiceResponse.fromJson(unzipAndGetJSONString(response.getBody()));
166 loadSchema(resp.getData().toJson(), version);
168 catch (Exception ex) {
169 StringWriter writer = new StringWriter();
170 PrintWriter printWriter = new PrintWriter(writer);
171 ex.printStackTrace(printWriter);
172 logger.error(SchemaProviderMsgs.SCHEMA_LOAD_ERROR, "failed to load version " + version + ": "
173 + response.getBody() + "\n" + writer.toString());
174 throw new SchemaProviderException("Error loading schema version " + version + ":" + ex.getMessage());
178 logger.info(SchemaProviderMsgs.LOADED_SCHEMA_FILE, version);
181 static final int BUFFER = 512;
182 static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB
183 static final int TOOMANY = 1024; // Max number of files
185 protected String unzipAndGetJSONString(byte[] inputData) throws java.io.IOException {
190 try (ByteArrayInputStream bis = new ByteArrayInputStream(inputData); ZipInputStream zis = new ZipInputStream(bis)) {
191 while ((entry = zis.getNextEntry()) != null) {
193 byte[] data = new byte[BUFFER];
194 if (entry.isDirectory()) {
197 ByteArrayOutputStream fos = new ByteArrayOutputStream();
198 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
199 while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) {
200 dest.write(data, 0, count);
204 result = fos.toString();
208 if (entries > TOOMANY) {
209 throw new IllegalStateException("Too many files to unzip.");
211 if (total + BUFFER > TOOBIG) {
212 throw new IllegalStateException("File being unzipped is too big.");
219 private SchemaInstance getSchemaVersion(String version) throws SchemaProviderException {
220 // TODO: For now, we are only supporting a single version of the schema. Load that
221 // version regardless of what the client asks for.
222 String versionToLoad = getLatestSchemaVersion();
223 SchemaInstance inst = schemaCache.get(versionToLoad);
226 fetchSchemaVersion(versionToLoad);
227 inst = schemaCache.get(versionToLoad);
229 throw new SchemaProviderException("Unable to find schema version " + versionToLoad);
237 public Map<String, VertexSchema> getVertexMap(String schemaVersion) throws SchemaProviderException {
238 return getSchemaVersion(schemaVersion).getVertexMap();