2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2018 Nokia. All rights reserved.s
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=========================================================
22 package org.onap.dcae.restapi;
24 import static java.util.Optional.ofNullable;
25 import static java.util.stream.StreamSupport.stream;
26 import static org.springframework.http.ResponseEntity.ok;
28 import com.att.nsa.clock.SaClock;
29 import com.att.nsa.logging.LoggingContext;
30 import com.att.nsa.logging.log4j.EcompFields;
31 import com.github.fge.jackson.JsonLoader;
32 import com.github.fge.jsonschema.core.report.ProcessingReport;
33 import com.github.fge.jsonschema.main.JsonSchema;
35 import java.util.UUID;
36 import java.util.concurrent.LinkedBlockingQueue;
37 import javax.servlet.http.HttpServletRequest;
39 import org.json.JSONArray;
40 import org.json.JSONObject;
41 import org.onap.dcae.ApplicationSettings;
42 import org.onap.dcae.CollectorSchemas;
43 import org.onap.dcae.commonFunction.VESLogger;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.beans.factory.annotation.Qualifier;
48 import org.springframework.http.MediaType;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.web.bind.annotation.GetMapping;
51 import org.springframework.web.bind.annotation.PostMapping;
52 import org.springframework.web.bind.annotation.RequestBody;
53 import org.springframework.web.bind.annotation.RestController;
56 public class VesRestController {
58 private static final Logger LOG = LoggerFactory.getLogger(VesRestController.class);
60 private static final String FALLBACK_VES_VERSION = "v5";
63 private ApplicationSettings collectorProperties;
66 private CollectorSchemas schemas;
69 @Qualifier("metriclog")
70 private Logger metriclog;
73 @Qualifier("incomingRequestsLogger")
74 private Logger incomingRequestsLogger;
77 @Qualifier("errorLog")
78 private Logger errorLog;
80 private LinkedBlockingQueue<JSONObject> inputQueue;
81 private String version;
84 VesRestController(@Qualifier("incomingRequestsLogger") Logger incomingRequestsLogger,
85 @Qualifier("inputQueue") LinkedBlockingQueue<JSONObject> inputQueue) {
86 this.incomingRequestsLogger = incomingRequestsLogger;
87 this.inputQueue = inputQueue;
92 return "Welcome to VESCollector";
95 //refactor in next iteration
96 @PostMapping(value = {"/eventListener/v1",
97 "/eventListener/v1/eventBatch",
99 "/eventListener/v2/eventBatch",
101 "/eventListener/v3/eventBatch",
103 "/eventListener/v4/eventBatch",
105 "/eventListener/v5/eventBatch"}, consumes = "application/json")
106 ResponseEntity<String> receiveEvent(@RequestBody String jsonPayload, HttpServletRequest httpServletRequest) {
107 String request = httpServletRequest.getRequestURI();
108 extractVersion(request);
110 JSONObject jsonObject;
112 jsonObject = new JSONObject(jsonPayload);
113 } catch (Exception e) {
114 return ResponseEntity.badRequest().body(ApiException.INVALID_JSON_INPUT.toJSON().toString());
117 String uuid = setUpECOMPLoggingForRequest();
118 incomingRequestsLogger.info(String.format(
119 "Received a VESEvent '%s', marked with unique identifier '%s', on api version '%s', from host: '%s'",
120 jsonObject, uuid, version, httpServletRequest.getRemoteHost()));
122 if (collectorProperties.jsonSchemaValidationEnabled()) {
123 if (isBatchRequest(request) && (jsonObject.has("eventList") && (!jsonObject.has("event")))) {
124 if (!conformsToSchema(jsonObject, version)) {
125 return errorResponse(ApiException.SCHEMA_VALIDATION_FAILED);
127 } else if (!isBatchRequest(request) && (!jsonObject.has("eventList") && (jsonObject.has("event")))) {
128 if (!conformsToSchema(jsonObject, version)) {
129 return errorResponse(ApiException.SCHEMA_VALIDATION_FAILED);
132 return errorResponse(ApiException.INVALID_JSON_INPUT);
136 JSONArray commonlyFormatted = convertToJSONArrayCommonFormat(jsonObject, request, uuid, version);
138 if (!putEventsOnProcessingQueue(commonlyFormatted)) {
139 errorLog.error("EVENT_RECEIPT_FAILURE: QueueFull " + ApiException.NO_SERVER_RESOURCES);
140 return errorResponse(ApiException.NO_SERVER_RESOURCES);
142 return ok().contentType(MediaType.APPLICATION_JSON).body("Message Accepted");
145 private void extractVersion(String httpServletRequest) {
146 version = httpServletRequest.split("/")[2];
149 private ResponseEntity<String> errorResponse(ApiException noServerResources) {
150 return ResponseEntity.status(noServerResources.httpStatusCode)
151 .body(noServerResources.toJSON().toString());
154 private boolean putEventsOnProcessingQueue(JSONArray arrayOfEvents) {
155 for (int i = 0; i < arrayOfEvents.length(); i++) {
156 metriclog.info("EVENT_PUBLISH_START");
157 if (!inputQueue.offer((JSONObject) arrayOfEvents.get(i))) {
161 LOG.debug("CommonStartup.handleEvents:EVENTS has been published successfully!");
162 metriclog.info("EVENT_PUBLISH_END");
166 private boolean conformsToSchema(JSONObject payload, String version) {
168 JsonSchema schema = ofNullable(schemas.getJSONSchemasMap(version).get(version))
169 .orElse(schemas.getJSONSchemasMap(version).get(FALLBACK_VES_VERSION));
170 ProcessingReport report = schema.validate(JsonLoader.fromString(payload.toString()));
171 if (!report.isSuccess()) {
172 LOG.warn("Schema validation failed for event: " + payload);
173 stream(report.spliterator(), false).forEach(e -> LOG.warn(e.getMessage()));
176 return report.isSuccess();
177 } catch (Exception e) {
178 throw new RuntimeException("Unable to validate against schema", e);
182 private static JSONArray convertToJSONArrayCommonFormat(JSONObject jsonObject, String request,
183 String uuid, String version) {
184 JSONArray asArrayEvents = new JSONArray();
185 String vesUniqueIdKey = "VESuniqueId";
186 String vesVersionKey = "VESversion";
187 if (isBatchRequest(request)) {
188 JSONArray events = jsonObject.getJSONArray("eventList");
189 for (int i = 0; i < events.length(); i++) {
190 JSONObject event = new JSONObject().put("event", events.getJSONObject(i));
191 event.put(vesUniqueIdKey, uuid + "-" + i);
192 event.put(vesVersionKey, version);
193 asArrayEvents.put(event);
196 jsonObject.put(vesUniqueIdKey, uuid);
197 jsonObject.put(vesVersionKey, version);
198 asArrayEvents = new JSONArray().put(jsonObject);
200 return asArrayEvents;
203 private static String setUpECOMPLoggingForRequest() {
204 final UUID uuid = UUID.randomUUID();
205 LoggingContext localLC = VESLogger.getLoggingContextForThread(uuid);
206 localLC.put(EcompFields.kBeginTimestampMs, SaClock.now());
207 return uuid.toString();
210 private static boolean isBatchRequest(String request) {
211 return request.contains("eventBatch");