summaryrefslogtreecommitdiffstats
path: root/src/main
diff options
context:
space:
mode:
authorBogumil Zebek <bogumil.zebek@nokia.com>2020-07-22 08:19:51 +0200
committerBartosz Gardziejewski <bartosz.gardziejewski@nokia.com>2020-08-06 08:07:39 +0200
commitf6260a26de44a9338ca998626a93c0d0fa56abc3 (patch)
tree2a3dffaf850a7a934861c0fd10003168324c9f69 /src/main
parentdc29687c2c83b387718c6a26b227170b17dcf08d (diff)
StndDefined event routing
Route stndDefined events to streams defined in namespace event field. Change-Id: I3963e220095665f8ca3fd1b21c5c20b44057cf76 Issue-ID: DCAEGEN2-1771 Signed-off-by: Zebek Bogumil <bogumil.zebek@nokia.com>
Diffstat (limited to 'src/main')
-rw-r--r--src/main/java/org/onap/dcae/ApplicationSettings.java2
-rw-r--r--src/main/java/org/onap/dcae/JSonSchemasSupplier.java4
-rw-r--r--src/main/java/org/onap/dcae/VesApplication.java2
-rw-r--r--src/main/java/org/onap/dcae/common/EventSender.java52
-rw-r--r--src/main/java/org/onap/dcae/common/EventUpdater.java22
-rw-r--r--src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterHasEmptyValueException.java23
-rw-r--r--src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterNotDefinedException.java24
-rw-r--r--src/main/java/org/onap/dcae/common/model/VesEvent.java120
-rw-r--r--src/main/java/org/onap/dcae/restapi/ApiException.java4
-rw-r--r--src/main/java/org/onap/dcae/restapi/EventValidator.java52
-rw-r--r--src/main/java/org/onap/dcae/restapi/EventValidatorException.java32
-rw-r--r--src/main/java/org/onap/dcae/restapi/VesRestController.java97
12 files changed, 336 insertions, 98 deletions
diff --git a/src/main/java/org/onap/dcae/ApplicationSettings.java b/src/main/java/org/onap/dcae/ApplicationSettings.java
index 8458df8d..33ad5bc7 100644
--- a/src/main/java/org/onap/dcae/ApplicationSettings.java
+++ b/src/main/java/org/onap/dcae/ApplicationSettings.java
@@ -161,7 +161,7 @@ public class ApplicationSettings {
return properties.getString("auth.method", AuthMethodType.NO_AUTH.value());
}
- public Map<String, String[]> dMaaPStreamsMapping() {
+ public Map<String, String[]> getDmaapStreamIds() {
String streamIdsProperty = properties.getString("collector.dmaap.streamid", null);
if (streamIdsProperty == null) {
return HashMap.empty();
diff --git a/src/main/java/org/onap/dcae/JSonSchemasSupplier.java b/src/main/java/org/onap/dcae/JSonSchemasSupplier.java
index d7cd5663..10e74ee5 100644
--- a/src/main/java/org/onap/dcae/JSonSchemasSupplier.java
+++ b/src/main/java/org/onap/dcae/JSonSchemasSupplier.java
@@ -3,7 +3,7 @@
* PROJECT
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2019 Nokia. All rights reserved.s
+ * Copyright (C) 2020 Nokia. All rights reserved.s
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ import java.nio.file.Paths;
import static io.vavr.API.Tuple;
import static java.nio.file.Files.readAllBytes;
-class JSonSchemasSupplier {
+public class JSonSchemasSupplier {
public Map<String, JsonSchema> loadJsonSchemas(String collectorSchemaFile) {
JSONObject jsonObject = new JSONObject(collectorSchemaFile);
diff --git a/src/main/java/org/onap/dcae/VesApplication.java b/src/main/java/org/onap/dcae/VesApplication.java
index bc5b1a8f..9f628b5c 100644
--- a/src/main/java/org/onap/dcae/VesApplication.java
+++ b/src/main/java/org/onap/dcae/VesApplication.java
@@ -133,7 +133,7 @@ public class VesApplication {
@Bean
@Qualifier("eventSender")
public EventSender eventSender() {
- return new EventSender(eventPublisher, applicationSettings);
+ return new EventSender(eventPublisher, applicationSettings.getDmaapStreamIds());
}
}
diff --git a/src/main/java/org/onap/dcae/common/EventSender.java b/src/main/java/org/onap/dcae/common/EventSender.java
index c1002af6..63be9106 100644
--- a/src/main/java/org/onap/dcae/common/EventSender.java
+++ b/src/main/java/org/onap/dcae/common/EventSender.java
@@ -1,9 +1,9 @@
/*
* ============LICENSE_START=======================================================
- * PROJECT
+ * VES Collector
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2018 Nokia. All rights reserved.s
+ * Copyright (C) 2020 Nokia. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,56 +24,48 @@ import com.att.nsa.clock.SaClock;
import com.att.nsa.logging.LoggingContext;
import com.att.nsa.logging.log4j.EcompFields;
import io.vavr.collection.Map;
-import org.json.JSONArray;
-import org.json.JSONObject;
-import org.onap.dcae.ApplicationSettings;
+import org.onap.dcae.common.model.VesEvent;
import org.onap.dcae.common.publishing.EventPublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.List;
+
public class EventSender {
private static final Logger metriclog = LoggerFactory.getLogger("com.att.ecomp.metrics");
- private Map<String, String[]> streamidHash;
+ private Map<String, String[]> streamIdToDmaapIds;
private EventPublisher eventPublisher;
- private static final String VES_UNIQUE_ID = "VESuniqueId";
private static final Logger log = LoggerFactory.getLogger(EventSender.class);
- private static final String EVENT_LITERAL = "event";
- private static final String COMMON_EVENT_HEADER = "commonEventHeader";
- public EventSender( EventPublisher eventPublisher, ApplicationSettings properties) {
+ public EventSender(EventPublisher eventPublisher, Map<String, String[]> streamIdToDmaapIds) {
this.eventPublisher = eventPublisher;
- this.streamidHash = properties.dMaaPStreamsMapping();
+ this.streamIdToDmaapIds = streamIdToDmaapIds;
}
- public void send(JSONArray arrayOfEvents) {
- for (int i = 0; i < arrayOfEvents.length(); i++) {
+ public void send(List<VesEvent> vesEvents) {
+ for (VesEvent vesEvent : vesEvents) {
metriclog.info("EVENT_PUBLISH_START");
- JSONObject object = (JSONObject) arrayOfEvents.get(i);
- setLoggingContext(object);
- streamidHash.get(getDomain(object))
- .onEmpty(() -> log.error("No StreamID defined for publish - Message dropped" + object))
- .forEach(streamIds -> sendEventsToStreams(object, streamIds));
- log.debug("Message published" + object);
+ setLoggingContext(vesEvent);
+ streamIdToDmaapIds.get(vesEvent.getStreamId())
+ .onEmpty(() -> log.error("No StreamID defined for publish - Message dropped" + vesEvent.asJsonObject()))
+ .forEach(streamIds -> sendEventsToStreams(vesEvent, streamIds));
+ log.debug("Message published" + vesEvent.asJsonObject());
}
log.debug("CommonStartup.handleEvents:EVENTS has been published successfully!");
metriclog.info("EVENT_PUBLISH_END");
}
- private static String getDomain(JSONObject event) {
- return event.getJSONObject(EVENT_LITERAL).getJSONObject(COMMON_EVENT_HEADER).getString("domain");
- }
-
- private void sendEventsToStreams(JSONObject event, String[] streamIdList) {
- for (String aStreamIdList : streamIdList) {
- log.info("Invoking publisher for streamId:" + aStreamIdList);
- eventPublisher.sendEvent(event, aStreamIdList);
+ private void sendEventsToStreams(VesEvent vesEvent, String[] streamIdList) {
+ for (String streamId : streamIdList) {
+ log.info("Invoking publisher for streamId/domain:" + streamId);
+ eventPublisher.sendEvent(vesEvent.asJsonObject(), streamId);
}
}
- private void setLoggingContext(JSONObject event) {
- LoggingContext localLC = VESLogger.getLoggingContextForThread(event.get(VES_UNIQUE_ID).toString());
+ private void setLoggingContext(VesEvent vesEvent) {
+ LoggingContext localLC = VESLogger.getLoggingContextForThread(vesEvent.getUniqueId().toString());
localLC.put(EcompFields.kBeginTimestampMs, SaClock.now());
- log.debug("event.VESuniqueId" + event.get(VES_UNIQUE_ID) + "event.commonEventHeader.domain:" + getDomain(event));
+ log.debug("event.VESuniqueId" + vesEvent.getUniqueId() + "event.commonEventHeader.domain:" + vesEvent.getDomain());
}
}
diff --git a/src/main/java/org/onap/dcae/common/EventUpdater.java b/src/main/java/org/onap/dcae/common/EventUpdater.java
index 1469d47e..954e4b6e 100644
--- a/src/main/java/org/onap/dcae/common/EventUpdater.java
+++ b/src/main/java/org/onap/dcae/common/EventUpdater.java
@@ -22,12 +22,14 @@
package org.onap.dcae.common;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.dcae.ApplicationSettings;
+import org.onap.dcae.common.model.VesEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -47,33 +49,33 @@ public class EventUpdater {
this.settings = settings;
}
- public JSONArray convert(JSONObject jsonObject, String version, UUID uuid, String type){
+ public List<VesEvent> convert(VesEvent vesEvent, String version, UUID uuid, String type){
if(type.equalsIgnoreCase(EVENT_LIST)){
- return convertEvents(jsonObject, uuid.toString(), version);
+ return convertEvents(vesEvent, uuid.toString(), version);
}
else {
- return convertEvent(jsonObject, uuid.toString(), version);
+ return convertEvent(vesEvent, uuid.toString(), version);
}
}
- private JSONArray convertEvents(JSONObject jsonObject,
- String uuid, String version) {
- JSONArray asArrayEvents = new JSONArray();
+ private List<VesEvent> convertEvents(VesEvent vesEvent, String uuid, String version) {
+ List<VesEvent> asArrayEvents = new ArrayList<>();
- JSONArray events = jsonObject.getJSONArray(EVENT_LIST);
+ JSONArray events = vesEvent.asJsonObject().getJSONArray(EVENT_LIST);
for (int i = 0; i < events.length(); i++) {
JSONObject event = new JSONObject().put(EVENT, events.getJSONObject(i));
event.put(VES_UNIQUE_ID, uuid + "-" + i);
event.put(VES_VERSION, version);
- asArrayEvents.put(overrideEvent(event));
+ asArrayEvents.add(new VesEvent(overrideEvent(event)));
}
return asArrayEvents;
}
- private JSONArray convertEvent(JSONObject jsonObject, String uuid, String version) {
+ private List<VesEvent> convertEvent(VesEvent vesEvent, String uuid, String version) {
+ JSONObject jsonObject = vesEvent.asJsonObject();
jsonObject.put(VES_UNIQUE_ID, uuid);
jsonObject.put(VES_VERSION, version);
- return new JSONArray().put(overrideEvent(jsonObject));
+ return List.of(new VesEvent(overrideEvent(jsonObject)));
}
private JSONObject overrideEvent(JSONObject event) {
diff --git a/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterHasEmptyValueException.java b/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterHasEmptyValueException.java
new file mode 100644
index 00000000..22ec23a3
--- /dev/null
+++ b/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterHasEmptyValueException.java
@@ -0,0 +1,23 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.common.model;
+
+public class StndDefinedNamespaceParameterHasEmptyValueException extends RuntimeException{
+}
diff --git a/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterNotDefinedException.java b/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterNotDefinedException.java
new file mode 100644
index 00000000..69ee68fa
--- /dev/null
+++ b/src/main/java/org/onap/dcae/common/model/StndDefinedNamespaceParameterNotDefinedException.java
@@ -0,0 +1,24 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.s
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.common.model;
+
+
+public class StndDefinedNamespaceParameterNotDefinedException extends RuntimeException {
+}
diff --git a/src/main/java/org/onap/dcae/common/model/VesEvent.java b/src/main/java/org/onap/dcae/common/model/VesEvent.java
new file mode 100644
index 00000000..ce709d1c
--- /dev/null
+++ b/src/main/java/org/onap/dcae/common/model/VesEvent.java
@@ -0,0 +1,120 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.s
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.common.model;
+
+import org.json.JSONObject;
+
+/**
+ * This class is a wrapper for JSONObject, that represents VES event.
+ * It contains Strings that represents key, that can be found in VES event.
+ *
+ * @author Zebek
+ */
+public class VesEvent {
+
+ private static final String EVENT_LITERAL = "event";
+ private static final String COMMON_EVENT_HEADER = "commonEventHeader";
+ private static final String VES_UNIQUE_ID = "VESuniqueId";
+ private static final String DOMAIN = "domain";
+ private static final String STND_DEFINED_NAMESPACE = "stndDefinedNamespace";
+ private static final String STND_DEFINED_DOMAIN = "stndDefined";
+
+ private final JSONObject event;
+
+ public VesEvent(JSONObject event) {
+ this.event = event;
+ }
+
+ /**
+ * Returns stream ID from VES event.
+ *
+ * @return stream ID
+ */
+ public String getStreamId() {
+ String retVal = getDomain();
+
+ if (isStdDefinedDomain(retVal)) {
+ retVal = resolveDomainForStndDefinedEvent();
+ }
+
+ return retVal;
+ }
+
+ /**
+ * Returns Domain name from VES event.
+ *
+ * @return domain
+ */
+ public String getDomain() {
+ return getEventHeader().getString(DOMAIN);
+ }
+
+ private String resolveDomainForStndDefinedEvent() {
+ final JSONObject eventHeader = getEventHeader();
+ if(eventHeader.has(STND_DEFINED_NAMESPACE)) {
+ final String domain = eventHeader
+ .getString(STND_DEFINED_NAMESPACE);
+ if(domain.isEmpty()) {
+ throw new StndDefinedNamespaceParameterHasEmptyValueException();
+ }
+ return domain;
+ } else {
+ throw new StndDefinedNamespaceParameterNotDefinedException();
+ }
+ }
+
+ private JSONObject getEventHeader() {
+ return event
+ .getJSONObject(EVENT_LITERAL)
+ .getJSONObject(COMMON_EVENT_HEADER);
+ }
+
+ private boolean isStdDefinedDomain(String domain) {
+ return domain.equals(STND_DEFINED_DOMAIN);
+ }
+
+ /**
+ * Returns unique ID of VES event.
+ *
+ * @return unique ID
+ */
+ public Object getUniqueId() {
+ return event.get(VES_UNIQUE_ID);
+ }
+
+ /**
+ * Returns VES event in form of JSON object.
+ *
+ * @return event in form of json Object
+ */
+ public JSONObject asJsonObject() {
+ return new JSONObject(event.toString());
+ }
+
+ /**
+ * Checks if type of event is same as given in paramaters.
+ *
+ * @param type name that will be compared with event type
+ * @return true or false depending if type given in parameter is same as VES event type
+ */
+ public boolean hasType(String type) {
+ return this.event.has(type);
+ }
+}
diff --git a/src/main/java/org/onap/dcae/restapi/ApiException.java b/src/main/java/org/onap/dcae/restapi/ApiException.java
index 5867e52b..255999a6 100644
--- a/src/main/java/org/onap/dcae/restapi/ApiException.java
+++ b/src/main/java/org/onap/dcae/restapi/ApiException.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* org.onap.dcaegen2.collectors.ves
* ================================================================================
- * Copyright (C) 2018 Nokia. All rights reserved.
+ * Copyright (C) 2020 Nokia. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@ public enum ApiException {
INVALID_CONTENT_TYPE(ExceptionType.SERVICE_EXCEPTION, "SVC0002", "Bad Parameter (Incorrect request Content-Type)", 400),
UNAUTHORIZED_USER(ExceptionType.POLICY_EXCEPTION, "POL2000", "Unauthorized user", 401),
INVALID_CUSTOM_HEADER(ExceptionType.SERVICE_EXCEPTION, "SVC0002", "Bad Parameter (Incorrect request api version)", 400),
+ MISSING_NAMESPACE_PARAMETER(ExceptionType.SERVICE_EXCEPTION, "SVC2006", "Mandatory input attribute event.commonEventHeader.stndDefinedNamespace is missing from request", 400),
+ EMPTY_NAMESPACE_PARAMETER(ExceptionType.SERVICE_EXCEPTION, "SVC2006", "Mandatory input attribute event.commonEventHeader.stndDefinedNamespace is empty in request", 400),
NO_SERVER_RESOURCES(ExceptionType.SERVICE_EXCEPTION, "SVC1000", "No server resources (internal processing queue full)", 503);
public final int httpStatusCode;
diff --git a/src/main/java/org/onap/dcae/restapi/EventValidator.java b/src/main/java/org/onap/dcae/restapi/EventValidator.java
index 3261c3b3..0eb0967a 100644
--- a/src/main/java/org/onap/dcae/restapi/EventValidator.java
+++ b/src/main/java/org/onap/dcae/restapi/EventValidator.java
@@ -20,34 +20,54 @@
*/
package org.onap.dcae.restapi;
-import java.util.Optional;
-import org.json.JSONObject;
+import com.networknt.schema.JsonSchema;
import org.onap.dcae.ApplicationSettings;
-import org.springframework.http.ResponseEntity;
+import org.onap.dcae.common.model.VesEvent;
+
+/**
+ * This class is using ApplicationSetting and SchemaValidator to validate VES event.
+ *
+ * @author Zebek
+ */
public class EventValidator {
- private final SchemaValidator schemaValidator = new SchemaValidator();
- private ApplicationSettings applicationSettings;
+ private final SchemaValidator schemaValidator;
+ private final ApplicationSettings applicationSettings;
public EventValidator(ApplicationSettings applicationSettings) {
+ this(applicationSettings, new SchemaValidator());
+ }
+
+ EventValidator(ApplicationSettings applicationSettings, SchemaValidator schemaValidator) {
this.applicationSettings = applicationSettings;
+ this.schemaValidator = schemaValidator;
}
- public Optional<ResponseEntity<String>> validate(JSONObject jsonObject, String type, String version){
+ /**
+ * This method is validating given event using schema adn throws exception if event is not valid
+ *
+ * @param vesEvent event that will be validate
+ * @param type expected type of event
+ * @param version json schema version that will be used
+ * @throws EventValidatorException when event is not valid or have wrong type
+ */
+ public void validate(VesEvent vesEvent, String type, String version) throws EventValidatorException {
if (applicationSettings.eventSchemaValidationEnabled()) {
- if (jsonObject.has(type)) {
- if (!schemaValidator.conformsToSchema(jsonObject, applicationSettings.jsonSchema(version))) {
- return errorResponse(ApiException.SCHEMA_VALIDATION_FAILED);
- }
- } else {
- return errorResponse(ApiException.INVALID_JSON_INPUT);
+ doValidation(vesEvent, type, version);
+ }
+ }
+
+ private void doValidation(VesEvent vesEvent, String type, String version) throws EventValidatorException {
+ if (vesEvent.hasType(type)) {
+ if (!isEventMatchToSchema(vesEvent, applicationSettings.jsonSchema(version))) {
+ throw new EventValidatorException(ApiException.SCHEMA_VALIDATION_FAILED);
}
+ } else {
+ throw new EventValidatorException(ApiException.INVALID_JSON_INPUT);
}
- return Optional.empty();
}
- private Optional<ResponseEntity<String>> errorResponse(ApiException noServerResources) {
- return Optional.of(ResponseEntity.status(noServerResources.httpStatusCode)
- .body(noServerResources.toJSON().toString()));
+ private boolean isEventMatchToSchema(VesEvent vesEvent, JsonSchema schema) {
+ return schemaValidator.conformsToSchema(vesEvent.asJsonObject(), schema);
}
}
diff --git a/src/main/java/org/onap/dcae/restapi/EventValidatorException.java b/src/main/java/org/onap/dcae/restapi/EventValidatorException.java
new file mode 100644
index 00000000..65ad457f
--- /dev/null
+++ b/src/main/java/org/onap/dcae/restapi/EventValidatorException.java
@@ -0,0 +1,32 @@
+/*
+ * ============LICENSE_START=======================================================
+ * VES Collector
+ * ================================================================================
+ * Copyright (C) 2020 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcae.restapi;
+
+public class EventValidatorException extends Exception {
+ private final ApiException apiException;
+
+ public EventValidatorException(ApiException apiException) {
+ this.apiException = apiException;
+ }
+
+ public ApiException getApiException() {
+ return apiException;
+ }
+}
diff --git a/src/main/java/org/onap/dcae/restapi/VesRestController.java b/src/main/java/org/onap/dcae/restapi/VesRestController.java
index b07b58df..f6dde6d2 100644
--- a/src/main/java/org/onap/dcae/restapi/VesRestController.java
+++ b/src/main/java/org/onap/dcae/restapi/VesRestController.java
@@ -1,9 +1,9 @@
/*
* ============LICENSE_START=======================================================
- * PROJECT
+ * VES Collector
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * Copyright (C) 2018 Nokia. All rights reserved.s
+ * Copyright (C) 2020 Nokia. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,22 +21,18 @@
package org.onap.dcae.restapi;
-import static org.springframework.http.ResponseEntity.accepted;
-import static org.springframework.http.ResponseEntity.badRequest;
-
import com.att.nsa.clock.SaClock;
import com.att.nsa.logging.LoggingContext;
import com.att.nsa.logging.log4j.EcompFields;
-import java.util.Optional;
-import java.util.UUID;
-import javax.servlet.http.HttpServletRequest;
-import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.dcae.ApplicationSettings;
import org.onap.dcae.common.EventSender;
-import org.onap.dcae.common.VESLogger;
import org.onap.dcae.common.EventUpdater;
import org.onap.dcae.common.HeaderUtils;
+import org.onap.dcae.common.VESLogger;
+import org.onap.dcae.common.model.StndDefinedNamespaceParameterHasEmptyValueException;
+import org.onap.dcae.common.model.StndDefinedNamespaceParameterNotDefinedException;
+import org.onap.dcae.common.model.VesEvent;
import org.onap.dcaegen2.services.sdk.standardization.header.CustomHeaderUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@@ -48,6 +44,13 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
+import javax.servlet.http.HttpServletRequest;
+import java.util.List;
+import java.util.UUID;
+
+import static org.springframework.http.ResponseEntity.accepted;
+import static org.springframework.http.ResponseEntity.badRequest;
+
@RestController
public class VesRestController {
@@ -58,15 +61,19 @@ public class VesRestController {
private final Logger requestLogger;
private EventSender eventSender;
private final HeaderUtils headerUtils;
+ private final EventValidator eventValidator;
+ private final EventUpdater eventUpdater;
- @Autowired
- VesRestController(ApplicationSettings settings,
- @Qualifier("incomingRequestsLogger") Logger incomingRequestsLogger,
- @Qualifier("eventSender") EventSender eventSender, HeaderUtils headerUtils) {
+ @Autowired
+ VesRestController(ApplicationSettings settings,
+ @Qualifier("incomingRequestsLogger") Logger incomingRequestsLogger,
+ @Qualifier("eventSender") EventSender eventSender, HeaderUtils headerUtils) {
this.settings = settings;
this.requestLogger = incomingRequestsLogger;
this.eventSender = eventSender;
this.headerUtils = headerUtils;
+ this.eventValidator = new EventValidator(settings);
+ this.eventUpdater = new EventUpdater(settings);
}
@PostMapping(value = {"/eventListener/{version}"}, consumes = "application/json")
@@ -86,38 +93,54 @@ public class VesRestController {
return badRequest().contentType(MediaType.APPLICATION_JSON).body(String.format("API version %s is not supported", version));
}
- private ResponseEntity<String> process(String events, String version, HttpServletRequest request, String type) {
+ private ResponseEntity<String> process(String payload, String version, HttpServletRequest request, String type) {
CustomHeaderUtils headerUtils = createHeaderUtils(version, request);
- if(headerUtils.isOkCustomHeaders()){
- JSONObject jsonObject = new JSONObject(events);
-
- EventValidator eventValidator = new EventValidator(settings);
- Optional<ResponseEntity<String>> validationResult = eventValidator.validate(jsonObject, type, version);
-
- if (validationResult.isPresent()){
- return validationResult.get();
- }
- JSONArray arrayOfEvents = new EventUpdater(settings).convert(jsonObject,version, generateUUID(version, request.getRequestURI(), jsonObject), type);
- eventSender.send(arrayOfEvents);
- // TODO call service and return status, replace CambriaClient, split event to single object and list of them
- return accepted().headers(this.headerUtils.fillHeaders(headerUtils.getRspCustomHeader()))
- .contentType(MediaType.APPLICATION_JSON).body("Accepted");
+ if (headerUtils.isOkCustomHeaders()) {
+ final VesEvent vesEvent = new VesEvent(new JSONObject(payload));
+ final String requestURI = request.getRequestURI();
+ return handleEvent(vesEvent, version, type, headerUtils, requestURI);
}
return badRequest().body(String.format(ApiException.INVALID_CUSTOM_HEADER.toString()));
}
- private CustomHeaderUtils createHeaderUtils(String version, HttpServletRequest request){
- return new CustomHeaderUtils(version.toLowerCase().replace("v", ""),
- headerUtils.extractHeaders(request),
- headerUtils.getApiVerFilePath("api_version_config.json"),
- headerUtils.getRestApiIdentify(request.getRequestURI()));
+ private ResponseEntity<String> handleEvent(VesEvent vesEvent, String version, String type, CustomHeaderUtils headerUtils, String requestURI) {
+ try {
+ eventValidator.validate(vesEvent, type, version);
+ List<VesEvent> vesEvents = transformEvent(vesEvent, type, version, requestURI);
+ eventSender.send(vesEvents);
+ } catch (EventValidatorException e) {
+ return ResponseEntity.status(e.getApiException().httpStatusCode)
+ .body(e.getApiException().toJSON().toString());
+ } catch (StndDefinedNamespaceParameterNotDefinedException e) {
+ return ResponseEntity.status(ApiException.MISSING_NAMESPACE_PARAMETER.httpStatusCode)
+ .body(ApiException.MISSING_NAMESPACE_PARAMETER.toJSON().toString());
+ } catch (StndDefinedNamespaceParameterHasEmptyValueException e) {
+ return ResponseEntity.status(ApiException.MISSING_NAMESPACE_PARAMETER.httpStatusCode)
+ .body(ApiException.EMPTY_NAMESPACE_PARAMETER.toJSON().toString());
+ }
+
+ // TODO call service and return status, replace CambriaClient, split event to single object and list of them
+ return accepted().headers(this.headerUtils.fillHeaders(headerUtils.getRspCustomHeader()))
+ .contentType(MediaType.APPLICATION_JSON).body("Accepted");
+ }
+
+ private CustomHeaderUtils createHeaderUtils(String version, HttpServletRequest request) {
+ return new CustomHeaderUtils(version.toLowerCase().replace("v", ""),
+ headerUtils.extractHeaders(request),
+ headerUtils.getApiVerFilePath("api_version_config.json"),
+ headerUtils.getRestApiIdentify(request.getRequestURI()));
+
+ }
+ private List<VesEvent> transformEvent(VesEvent vesEvent, String type, String version, String requestURI) {
+ return this.eventUpdater.convert(
+ vesEvent, version, generateUUID(vesEvent, version, requestURI), type);
}
- private UUID generateUUID(String version, String uri, JSONObject jsonObject) {
+ private UUID generateUUID(VesEvent vesEvent, String version, String uri) {
UUID uuid = UUID.randomUUID();
setUpECOMPLoggingForRequest(uuid);
- requestLogger.info(String.format(VES_EVENT_MESSAGE, jsonObject, uuid, version, uri));
+ requestLogger.info(String.format(VES_EVENT_MESSAGE, vesEvent.asJsonObject(), uuid, version, uri));
return uuid;
}
@@ -125,4 +148,4 @@ public class VesRestController {
LoggingContext localLC = VESLogger.getLoggingContextForThread(uuid);
localLC.put(EcompFields.kBeginTimestampMs, SaClock.now());
}
-} \ No newline at end of file
+}