Merge "Fix artifact name for sonar reporting"
diff --git a/pom.xml b/pom.xml
index f004161..9f9426b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -70,6 +70,7 @@
<compiler.source.version>1.8</compiler.source.version>
<shade.main>org.onap.dcaegen2.services.pmmapper.App</shade.main>
<shade.transformer>org.apache.maven.plugins.shade.resource.ManifestResourceTransformer</shade.transformer>
+ <onap.logging.version>1.2.2</onap.logging.version>
</properties>
<dependencies>
@@ -100,6 +101,17 @@
<version>${logback.version}</version>
</dependency>
<dependency>
+ <groupId>org.onap.logging-analytics</groupId>
+ <artifactId>logging-slf4j</artifactId>
+ <version>${onap.logging.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.5</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/App.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/App.java
index 784e0f1..3c075ba 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/App.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/App.java
@@ -28,11 +28,9 @@
import org.onap.dcaegen2.services.pmmapper.datarouter.DataRouterSubscriber;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;
-import org.onap.dcaegen2.services.pmmapper.exceptions.ConsulServerError;
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.TooManyTriesException;
-import org.onap.dcaegen2.services.pmmapper.model.BusControllerConfig;
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
import org.onap.dcaegen2.services.pmmapper.healthcheck.HealthCheckHandler;
@@ -41,17 +39,14 @@
public class App {
- public static void main(String[] args) throws MalformedURLException, InterruptedException, TooManyTriesException, CBSConfigException, ConsulServerError, EnvironmentConfigException, CBSServerError, MapperConfigException {
+ public static void main(String[] args) throws MalformedURLException, InterruptedException, TooManyTriesException, CBSConfigException, EnvironmentConfigException, CBSServerError, MapperConfigException {
HealthCheckHandler healthCheckHandler = new HealthCheckHandler();
DataRouterSubscriber dataRouterSubscriber = new DataRouterSubscriber(event -> {
event.getHttpServerExchange().unDispatch();
event.getHttpServerExchange().getResponseSender().send(StatusCodes.OK_STRING);
- System.out.println(event.getMetadata().getProductName());
});
MapperConfig mapperConfig = new ConfigHandler().getMapperConfig();
- BusControllerConfig busConfig = mapperConfig.getBusControllerConfig();
- busConfig.setDataRouterSubscribeEndpoint(new URL("http://" + System.getenv("DMAAP_BC_SERVICE_HOST") + ":" + System.getenv("DMAAP_BC_SERVICE_PORT") + "/webapi/dr_subs"));
- dataRouterSubscriber.start(busConfig);
+ dataRouterSubscriber.start(mapperConfig);
Undertow.builder()
.addHttpListener(8081, "0.0.0.0")
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/config/ConfigHandler.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/config/ConfigHandler.java
index 847fff2..fe2f247 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/config/ConfigHandler.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/config/ConfigHandler.java
@@ -19,26 +19,27 @@
*/
package org.onap.dcaegen2.services.pmmapper.config;
-import java.util.Arrays;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;
-import org.onap.dcaegen2.services.pmmapper.exceptions.ConsulServerError;
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;
-import org.onap.dcaegen2.services.pmmapper.model.CBSConfig;
import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;
import org.onap.dcaegen2.services.pmmapper.utils.RequiredFieldDeserializer;
+
+import org.onap.logging.ref.slf4j.ONAPLogAdapter;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.LoggerFactory;
import com.google.gson.GsonBuilder;
-import lombok.extern.slf4j.Slf4j;
/**
* Handles the retrieval of the component spec-based PM-Mapper Configuration
* from DCAE.
*/
-@Slf4j
+
public class ConfigHandler {
+ private static final ONAPLogAdapter logger = new ONAPLogAdapter(LoggerFactory.getLogger(ConfigHandler.class));
private RequestSender sender;
/**
@@ -65,39 +66,24 @@
* @throws CBSServerError
* @throws MapperConfigException
*/
- public MapperConfig getMapperConfig() throws CBSConfigException, ConsulServerError, EnvironmentConfigException,
+ public MapperConfig getMapperConfig() throws CBSConfigException, EnvironmentConfigException,
CBSServerError, MapperConfigException {
- CBSConfig cbsConfig = convertCBSConfigToObject(getCBSConfigFromConsul());
- String cbsSocketAddress = cbsConfig.getServiceAddress() + ":" + cbsConfig.getServicePort();
- String requestURL = "http://" + cbsSocketAddress + "/service_component/" + cbsConfig.getServiceName();
String mapperConfigJson = "";
- log.debug("Fetching mapper configuration from CBS: " + requestURL);
+ String cbsSocketAddress = EnvironmentConfig.getCBSHostName() + ":" + EnvironmentConfig.getCBSPort();
+ String requestURL = "http://" + cbsSocketAddress + "/service_component/" + EnvironmentConfig.getServiceName();
try {
+ logger.unwrap().info(ONAPLogConstants.Markers.ENTRY, "Fetching pm-mapper configuration from Configbinding Service");
mapperConfigJson = sender.send(requestURL);
} catch (Exception exception) {
throw new CBSServerError("Error connecting to Configbinding Service: ", exception);
+ } finally {
+ logger.unwrap().info(ONAPLogConstants.Markers.EXIT, "Received pm-mapper configuration from ConfigBinding Service:\n{}", mapperConfigJson);
}
return convertMapperConfigToObject(mapperConfigJson);
}
- private String getCBSConfigFromConsul() throws ConsulServerError, EnvironmentConfigException {
- String cbsParams;
- String consulURL = "http://" + EnvironmentConfig.getConsulHost() + ":" + EnvironmentConfig.getConsultPort()
- + "/v1/catalog/service/" + EnvironmentConfig.getCbsName();
- log.debug(consulURL);
- try {
- cbsParams = sender.send(consulURL);
- } catch (Exception exception) {
- throw new ConsulServerError("Error connecting to Consul: ", exception);
- }
-
- log.debug("cbsConfig: " + cbsParams);
- return cbsParams;
- }
-
private MapperConfig convertMapperConfigToObject(String mapperConfigJson) throws MapperConfigException {
- log.debug("mapperConfigJson:" + mapperConfigJson);
MapperConfig mapperConfig;
try {
mapperConfig = new GsonBuilder()
@@ -105,29 +91,10 @@
.create()
.fromJson(mapperConfigJson, MapperConfig.class);
} catch (Exception exception) {
- throw new MapperConfigException("Error parsing mapper configuration: " + mapperConfigJson, exception);
+ throw new MapperConfigException("Error parsing mapper configuration:\n{}" + mapperConfigJson, exception);
}
- log.debug("\n" + mapperConfig.toString());
+ logger.unwrap().debug("Mapper configuration:\n{}", mapperConfig);
return mapperConfig;
}
-
- private CBSConfig convertCBSConfigToObject(String cbsParameters) throws CBSConfigException {
- CBSConfig cbsConfig;
- try {
- cbsConfig = Arrays
- .asList(new GsonBuilder()
- .registerTypeAdapter(CBSConfig.class, new RequiredFieldDeserializer<CBSConfig>())
- .create()
- .fromJson(cbsParameters, CBSConfig[].class))
- .get(0);
- log.debug("\n\nReceived ConfigBinding Service Configurations: " + cbsConfig);
- } catch (Exception exception) {
- throw new CBSConfigException(
- "Error mapping the received ConfigBinding service configuration parameters: " + cbsParameters,
- exception);
- }
- return cbsConfig;
- }
-
}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriber.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriber.java
index f063a23..e262d42 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriber.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriber.java
@@ -31,31 +31,35 @@
import org.onap.dcaegen2.services.pmmapper.exceptions.NoMetadataException;
import org.onap.dcaegen2.services.pmmapper.exceptions.TooManyTriesException;
import org.onap.dcaegen2.services.pmmapper.model.EventMetadata;
-import org.onap.dcaegen2.services.pmmapper.model.BusControllerConfig;
+import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
import org.onap.dcaegen2.services.pmmapper.model.Event;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.StatusCodes;
-import lombok.extern.slf4j.Slf4j;
+import org.onap.dcaegen2.services.pmmapper.utils.HttpServerExchangeAdapter;
import org.onap.dcaegen2.services.pmmapper.utils.RequiredFieldDeserializer;
+import org.onap.logging.ref.slf4j.ONAPLogAdapter;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.Optional;
import java.util.Random;
+import java.util.UUID;
/**
* Subscriber for events sent from data router
* Provides an undertow HttpHandler to be used as an endpoint for data router to send events to.
*/
-@Slf4j
@Data
public class DataRouterSubscriber implements HttpHandler {
-
+ private static final ONAPLogAdapter logger = new ONAPLogAdapter(LoggerFactory.getLogger(DataRouterSubscriber.class));
private static final int NUMBER_OF_ATTEMPTS = 5;
private static final int DEFAULT_TIMEOUT = 2000;
private static final int MAX_JITTER = 50;
@@ -87,33 +91,45 @@
* all non constant configuration for subscription through this endpoint.
* @throws TooManyTriesException in the event that timeout has occurred several times.
*/
- public void start(BusControllerConfig config) throws TooManyTriesException, InterruptedException {
- subscribe(NUMBER_OF_ATTEMPTS, DEFAULT_TIMEOUT, config);
+ public void start(MapperConfig config) throws TooManyTriesException, InterruptedException {
+ try {
+ logger.unwrap().info(ONAPLogConstants.Markers.ENTRY, "Starting subscription to DataRouter");
+ subscribe(NUMBER_OF_ATTEMPTS, DEFAULT_TIMEOUT, config);
+ } finally {
+ logger.unwrap().info(ONAPLogConstants.Markers.EXIT, "");
+ }
}
- private HttpURLConnection getBusControllerConnection(BusControllerConfig config, int timeout) throws IOException {
- HttpURLConnection connection = (HttpURLConnection) config.getDataRouterSubscribeEndpoint()
+ private HttpURLConnection getBusControllerConnection(MapperConfig config, int timeout) throws IOException {
+ HttpURLConnection connection = (HttpURLConnection) config.getBusControllerSubscriptionUrl()
.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
+
+ final UUID invocationID = logger.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS);
+ final UUID requestID = UUID.randomUUID();
+ connection.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, requestID.toString());
+ connection.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, invocationID.toString());
+ connection.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, MapperConfig.CLIENT_NAME);
+
return connection;
}
- private JsonObject getBusControllerSubscribeBody(BusControllerConfig config) {
+ private JsonObject getBusControllerSubscribeBody(MapperConfig config) {
JsonObject subscriberObj = new JsonObject();
subscriberObj.addProperty("dcaeLocationName", config.getDcaeLocation());
- subscriberObj.addProperty("deliveryURL", config.getDeliveryURL());
- subscriberObj.addProperty("feedId", config.getFeedId());
- subscriberObj.addProperty("lastMod", config.getLastMod());
- subscriberObj.addProperty("username", config.getUsername());
- subscriberObj.addProperty("userpwd", config.getPassword());
+ subscriberObj.addProperty("deliveryURL", config.getBusControllerDeliveryUrl());
+ subscriberObj.addProperty("feedId", config.getBusControllerFeedId());
+ subscriberObj.addProperty("lastMod", Instant.now().toString());
+ subscriberObj.addProperty("username", config.getBusControllerUserName());
+ subscriberObj.addProperty("userpwd", config.getBusControllerPassword());
return subscriberObj;
}
- private void subscribe(int attempts, int timeout, BusControllerConfig config) throws TooManyTriesException, InterruptedException {
+ private void subscribe(int attempts, int timeout, MapperConfig config) throws TooManyTriesException, InterruptedException {
int subResponse = 504;
String subMessage = "";
try {
@@ -126,9 +142,9 @@
subResponse = connection.getResponseCode();
subMessage = connection.getResponseMessage();
} catch (IOException e) {
- log.info("Timeout Failure:", e);
+ logger.unwrap().error("Timeout Failure:", e);
}
- log.info("Request to bus controller executed with Response Code: '{}' and Response Event: '{}'.", subResponse, subMessage);
+ logger.unwrap().info("Request to bus controller executed with Response Code: '{}' and Response Event: '{}'.", subResponse, subMessage);
if (subResponse >= 300 && attempts > 1) {
Thread.sleep(timeout);
subscribe(--attempts, (timeout * 2) + jitterGenerator.nextInt(MAX_JITTER), config);
@@ -146,33 +162,38 @@
*/
@Override
public void handleRequest(HttpServerExchange httpServerExchange) {
- if (limited) {
- httpServerExchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE)
- .getResponseSender()
- .send(StatusCodes.SERVICE_UNAVAILABLE_STRING);
- } else {
- try {
- String metadataAsString = Optional.of(httpServerExchange.getRequestHeaders()
- .get(METADATA_HEADER))
- .map((HeaderValues headerValues) -> headerValues.get(0))
- .orElseThrow(() -> new NoMetadataException("Metadata Not found"));
+ try{
+ logger.entering(new HttpServerExchangeAdapter(httpServerExchange));
+ if (limited) {
+ httpServerExchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE)
+ .getResponseSender()
+ .send(StatusCodes.SERVICE_UNAVAILABLE_STRING);
+ } else {
+ try {
+ String metadataAsString = Optional.of(httpServerExchange.getRequestHeaders()
+ .get(METADATA_HEADER))
+ .map((HeaderValues headerValues) -> headerValues.get(0))
+ .orElseThrow(() -> new NoMetadataException("Metadata Not found"));
- EventMetadata metadata = metadataBuilder.fromJson(metadataAsString, EventMetadata.class);
- httpServerExchange.getRequestReceiver()
- .receiveFullString((callbackExchange, body) -> {
- httpServerExchange.dispatch(() -> eventReceiver.receive(new Event(callbackExchange, body, metadata)));
- });
- } catch (NoMetadataException exception) {
- log.info("Bad Request: no metadata found under '{}' header.", METADATA_HEADER, exception);
- httpServerExchange.setStatusCode(StatusCodes.BAD_REQUEST)
- .getResponseSender()
- .send(NO_METADATA_MESSAGE);
- } catch (JsonParseException exception) {
- log.info("Bad Request: Failure to parse metadata", exception);
- httpServerExchange.setStatusCode(StatusCodes.BAD_REQUEST)
- .getResponseSender()
- .send(BAD_METADATA_MESSAGE);
+ EventMetadata metadata = metadataBuilder.fromJson(metadataAsString, EventMetadata.class);
+ httpServerExchange.getRequestReceiver()
+ .receiveFullString((callbackExchange, body) -> {
+ httpServerExchange.dispatch(() -> eventReceiver.receive(new Event(callbackExchange, body, metadata)));
+ });
+ } catch (NoMetadataException exception) {
+ logger.unwrap().info("Bad Request: no metadata found under '{}' header.", METADATA_HEADER, exception);
+ httpServerExchange.setStatusCode(StatusCodes.BAD_REQUEST)
+ .getResponseSender()
+ .send(NO_METADATA_MESSAGE);
+ } catch (JsonParseException exception) {
+ logger.unwrap().info("Bad Request: Failure to parse metadata", exception);
+ httpServerExchange.setStatusCode(StatusCodes.BAD_REQUEST)
+ .getResponseSender()
+ .send(BAD_METADATA_MESSAGE);
+ }
}
+ } finally {
+ logger.exiting();
}
}
}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/exceptions/ConsulServerError.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/exceptions/ConsulServerError.java
deleted file mode 100644
index 4c2adab..0000000
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/exceptions/ConsulServerError.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcaegen2.services.pmmapper.exceptions;
-
-public class ConsulServerError extends Exception {
- public ConsulServerError(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/healthcheck/HealthCheckHandler.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/healthcheck/HealthCheckHandler.java
index 2c788b0..756ee7b 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/healthcheck/HealthCheckHandler.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/healthcheck/HealthCheckHandler.java
@@ -22,18 +22,27 @@
package org.onap.dcaegen2.services.pmmapper.healthcheck;
+import org.onap.dcaegen2.services.pmmapper.utils.HttpServerExchangeAdapter;
+import org.onap.logging.ref.slf4j.ONAPLogAdapter;
+import org.slf4j.LoggerFactory;
+
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.StatusCodes;
public class HealthCheckHandler implements HttpHandler {
-
+ private static final ONAPLogAdapter logger = new ONAPLogAdapter(LoggerFactory.getLogger(HealthCheckHandler.class));
@Override
public void handleRequest(HttpServerExchange exchange) {
+ try {
+ logger.entering(new HttpServerExchangeAdapter(exchange));
+ exchange.setStatusCode(StatusCodes.OK)
+ .getResponseSender()
+ .send(StatusCodes.OK_STRING);
- exchange.setStatusCode(StatusCodes.OK)
- .getResponseSender()
- .send(StatusCodes.OK_STRING);
+ } finally {
+ logger.exiting();
+ }
}
}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/BusControllerConfig.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/BusControllerConfig.java
deleted file mode 100644
index 3727099..0000000
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/BusControllerConfig.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcaegen2.services.pmmapper.model;
-
-import lombok.Data;
-
-import java.net.URL;
-
-/**
- * Stub for BusControllerConfiguration object.
- */
-@Data
-public class BusControllerConfig {
-
- private String dcaeLocation = "dcaeLocation";
- private String deliveryURL = "deliveryURL";
- private int feedId = 2;
- private String lastMod = "lastMod";
- private String username = "username";
- private String password = "password";
- private URL dataRouterSubscribeEndpoint;
-
-}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/CBSConfig.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/CBSConfig.java
deleted file mode 100644
index 66fbed4..0000000
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/CBSConfig.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * 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.
- *
- * SPDX-License-Identifier: Apache-2.0
- * ============LICENSE_END=========================================================
- */
-package org.onap.dcaegen2.services.pmmapper.model;
-
-import org.onap.dcaegen2.services.pmmapper.utils.GSONRequired;
-
-import com.google.gson.annotations.SerializedName;
-import lombok.Data;
-
-@Data
-public class CBSConfig {
-
- @GSONRequired
- @SerializedName("ServiceID")
- private String serviceID;
-
- @GSONRequired
- @SerializedName("ServiceName")
- private String serviceName;
-
- @GSONRequired
- @SerializedName("ServiceAddress")
- private String serviceAddress;
-
- @GSONRequired
- @SerializedName("ServicePort")
- private String servicePort;
-
-}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/EnvironmentConfig.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/EnvironmentConfig.java
index f9dd178..fe48bfc 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/EnvironmentConfig.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/EnvironmentConfig.java
@@ -25,30 +25,32 @@
public class EnvironmentConfig {
- private static Integer consulPort = 8500;
+ public static final int DEFAULT_CBS_PORT = 10000;
+ public static final String ENV_CBS_HOST_KEY = "CONFIG_BINDING_SERVICE_SERVICE_HOST";
+ public static final String ENV_CBS_PORT_KEY = "CONFIG_BINDING_SERVICE_SERVICE_PORT";
+ public static final String ENV_SERVICE_NAME_KEY = "HOSTNAME";
- public static String getConsulHost() throws EnvironmentConfigException {
- return Optional.ofNullable(System.getProperty("CONSUL_HOST"))
+ public static String getServiceName() throws EnvironmentConfigException {
+ return Optional.ofNullable(System.getenv("HOSTNAME"))
.orElseThrow(() -> new EnvironmentConfigException(
- "$CONSUL_HOST environment variable must be defined prior to pm-mapper initialization"));
+ ENV_SERVICE_NAME_KEY+ " environment variable must be defined prior to pm-mapper initialization."));
}
- public static Integer getConsultPort() throws EnvironmentConfigException {
- Integer port = consulPort;
+ public static String getCBSHostName() throws EnvironmentConfigException {
+ return Optional.ofNullable(System.getenv("CONFIG_BINDING_SERVICE_SERVICE_HOST"))
+ .orElseThrow(() -> new EnvironmentConfigException(
+ ENV_CBS_HOST_KEY+ " environment variable must be defined prior to pm-mapper initialization."));
+ }
+
+ public static Integer getCBSPort() throws EnvironmentConfigException {
+ Integer port = DEFAULT_CBS_PORT;
try {
- port = Optional.ofNullable(System.getProperty("CONSUL_PORT"))
- .map(Integer::valueOf)
- .orElse(consulPort);
+ port = Optional.ofNullable(System.getenv("CONFIG_BINDING_SERVICE_SERVICE_PORT"))
+ .map(Integer::valueOf).orElse(DEFAULT_CBS_PORT);
} catch (NumberFormatException e) {
- throw new EnvironmentConfigException("CONSUL_PORT must be valid: " + port);
+ throw new EnvironmentConfigException(ENV_CBS_PORT_KEY + " must be valid: " + port);
}
return port;
}
-
- public static String getCbsName() throws EnvironmentConfigException {
- return Optional.ofNullable(System.getProperty("CONFIG_BINDING_SERVICE"))
- .orElseThrow(() -> new EnvironmentConfigException(
- "$CONFIG_BINDING_SERVICE environment variable must be defined prior to pm-mapper initialization."));
- }
}
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/MapperConfig.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/MapperConfig.java
index f8e428f..1753c2c 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/model/MapperConfig.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/model/MapperConfig.java
@@ -19,19 +19,88 @@
*/
package org.onap.dcaegen2.services.pmmapper.model;
+import java.net.MalformedURLException;
+import java.net.URL;
+
import org.onap.dcaegen2.services.pmmapper.utils.GSONRequired;
import com.google.gson.annotations.SerializedName;
-import lombok.Data;
+import lombok.Getter;
+import lombok.AccessLevel;
+import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
-@Data
+@Getter
+@EqualsAndHashCode
@NoArgsConstructor
public class MapperConfig {
- @GSONRequired
- @SerializedName("streams_subscribes.pm_mapper_handle_out.message_router_topic")
- private String messageRouterTopicName;
-
- BusControllerConfig busControllerConfig;
+ public static final String CLIENT_NAME = "pm-mapper";
-}
\ No newline at end of file
+ @GSONRequired
+ @Getter(AccessLevel.PRIVATE)
+ @SerializedName("streams_subscribes")
+ private StreamsSubscribes streamsSubscribes;
+
+ @GSONRequired
+ @SerializedName("buscontroller_feed_subscription_endpoint")
+ private String busControllerSubscriptionEndpoint;
+
+ @GSONRequired
+ @SerializedName("buscontroller_feed_id")
+ private String busControllerFeedId;
+
+ public String getBusControllerDeliveryUrl() {
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getDeliveryUrl();
+ }
+
+ public String getDcaeLocation() {
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getLocation();
+ }
+
+ public String getBusControllerUserName() {
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getUsername();
+ }
+
+ public String getBusControllerPassword() {
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getPassword();
+ }
+
+ public URL getBusControllerSubscriptionUrl() throws MalformedURLException {
+ return new URL(this.getBusControllerSubscriptionEndpoint());
+ }
+
+ @Getter
+ @EqualsAndHashCode
+ private class StreamsSubscribes {
+ @GSONRequired
+ @SerializedName("dmaap_subscriber")
+ DmaapSubscriber dmaapSubscriber;
+ }
+
+ @Getter
+ @EqualsAndHashCode
+ class DmaapSubscriber {
+ @GSONRequired
+ @SerializedName("dmaap_info")
+ DmaapInfo dmaapInfo;
+ }
+
+ @Getter
+ @EqualsAndHashCode
+ class DmaapInfo {
+ @GSONRequired
+ private String location;
+ private String username;
+ private String password;
+
+ @SerializedName("delivery_url")
+ private String deliveryUrl;
+
+ @SerializedName("subscriber_id")
+ private String subscriberId;
+ }
+}
+
+
+
+
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/HttpServerExchangeAdapter.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/HttpServerExchangeAdapter.java
new file mode 100644
index 0000000..ef5512f
--- /dev/null
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/HttpServerExchangeAdapter.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.dcaegen2.services.pmmapper.utils;
+
+import io.undertow.server.HttpServerExchange;
+import org.onap.logging.ref.slf4j.ONAPLogAdapter.RequestAdapter;
+
+/**
+ * Logging Adapter for Undertow's {@link HttpServerExchange}
+ */
+
+public class HttpServerExchangeAdapter implements RequestAdapter<HttpServerExchangeAdapter>{
+
+ private final HttpServerExchange myRequest;
+
+ /**
+ * Construct adapter for the request part of {@link HttpServerExchange}.
+ * @param request to be wrapped;
+ */
+ public HttpServerExchangeAdapter(final HttpServerExchange request) {
+ this.myRequest = request;
+ }
+
+ @Override
+ public String getClientAddress() {
+ return myRequest.getSourceAddress().getAddress().toString();
+ }
+
+ @Override
+ public String getHeader(String headerName) {
+ return myRequest.getRequestHeaders().getFirst(headerName);
+ }
+
+ @Override
+ public String getRequestURI() {
+ return myRequest.getRequestURI();
+ }
+
+ @Override
+ public String getServerAddress() {
+ return myRequest.getHostName();
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/RequestSender.java b/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/RequestSender.java
index 1b9cdc6..25519a0 100644
--- a/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/RequestSender.java
+++ b/src/main/java/org/onap/dcaegen2/services/pmmapper/utils/RequestSender.java
@@ -24,15 +24,22 @@
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.util.UUID;
import java.util.stream.Collectors;
+
+import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
+import org.onap.logging.ref.slf4j.ONAPLogAdapter;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.LoggerFactory;
+
import lombok.extern.slf4j.Slf4j;
-@Slf4j
public class RequestSender {
private static final int MAX_RETRIES = 5;
private static final int RETRY_INTERVAL = 1000;
- public static final String SERVER_ERROR_MESSAGE = "Error on Server";
- public static final int ERROR_START_RANGE = 300;
+ private static final String SERVER_ERROR_MESSAGE = "Error on Server";
+ private static final int ERROR_START_RANGE = 300;
+ private static final ONAPLogAdapter logger = new ONAPLogAdapter(LoggerFactory.getLogger(RequestSender.class));
/**
* Sends an Http GET request to a given endpoint.
@@ -41,23 +48,36 @@
* @throws Exception
* @throws InterruptedException
*/
- public String send(final String url) throws Exception {
- log.debug("RequestSender::send: " + url);
+
+ public String send(final String urlString) throws Exception {
+ final UUID invocationID = logger.invoke(ONAPLogConstants.InvocationMode.SYNCHRONOUS);
+ final UUID requestID = UUID.randomUUID();
String result = "";
+
for (int i = 1; i <= MAX_RETRIES; i++) {
- URL obj = new URL(url);
- HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
+ URL url = new URL(urlString);
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, requestID.toString());
+ connection.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, invocationID.toString());
+ connection.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, MapperConfig.CLIENT_NAME);
+ logger.unwrap()
+ .info("Sending:\n{}", connection.getRequestProperties());
+
try (InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
result = reader.lines()
.collect(Collectors.joining("\n"));
int responseCode = connection.getResponseCode();
if (!(isWithinErrorRange(responseCode))) {
+ logger.unwrap()
+ .info("Received:\n{}", result);
break;
}
- } catch (Exception e) {
+ } catch (Exception e) {
if (retryLimitReached(i)) {
+ logger.unwrap()
+ .error("Execution error: "+connection.getResponseMessage(), e);
throw new Exception(SERVER_ERROR_MESSAGE + ": " + connection.getResponseMessage(), e);
}
}
@@ -74,4 +94,4 @@
private boolean isWithinErrorRange(final int responseCode) {
return responseCode >= ERROR_START_RANGE;
}
-}
+}
\ No newline at end of file
diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml
new file mode 100644
index 0000000..0d5d83c
--- /dev/null
+++ b/src/main/resources/logback.xml
@@ -0,0 +1,46 @@
+<configuration>
+ <property name="outputFilename" value="pm-mapper_output"/>
+ <property name="logPath" value="/var/log/ONAP/dcaegen2/services/pm-mapper"/>
+ <property name="archivePath" value="${logPath}/archive"/>
+ <property name="maxFileSize" value="50MB"/>
+ <property name="maxHistory" value="30"/>
+ <property name="totalSizeCap" value="10GB"/>
+ <property name="p_tim" value="%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX", UTC}"/>
+ <property name="p_lvl" value="%level"/>
+ <property name="p_log" value="%logger"/>
+ <property name="p_mdc" value="%replace(%replace(%mdc){'\t','\\\\t'}){'\n', '\\\\n'}"/>
+ <property name="p_msg" value="%replace(%replace(%msg){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_exc" value="%replace(%replace(%rootException){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_mak" value="%replace(%replace(%marker){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_thr" value="%thread"/>
+ <property name="pattern" value="%nopexception${p_tim}\t${p_thr}\t${p_lvl}\t${p_log}\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t%n"/>
+
+ <variable name="logLevel" value="${LOG_LEVEL:-INFO}"/>
+
+ <logger name="org.mockserver" level="${mockserver.logLevel:-OFF}"/>
+
+ <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${pattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="ROLLING-FILE" class="ch.qos.logback.core.FileAppender">
+ <file>${logPath}/${outputFilename}.log</file>
+ <encoder>
+ <pattern>${pattern}</pattern>
+ </encoder>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <FileNamePattern>${archivePath}/${outputFilename}.%d{yyyy-MM-dd}.%i.log.zip</FileNamePattern>
+ <MaxFileSize>${maxFileSize}</MaxFileSize>
+ <MaxHistory>${maxHistory}</MaxHistory>
+ <TotalSizeCap>${totalSizeCap}</TotalSizeCap>
+ </rollingPolicy>
+ </appender>
+
+ <root level="${logLevel}" additivity="false">
+ <appender-ref ref="CONSOLE" />
+ <appender-ref ref="ROLLING-FILE" />
+ </root>
+
+</configuration>
\ No newline at end of file
diff --git a/src/test/java/org/onap/dcaegen2/pmmapper/config/ConfigHandlerTests.java b/src/test/java/org/onap/dcaegen2/pmmapper/config/ConfigHandlerTests.java
index 0c3fb84..f6aa2a8 100644
--- a/src/test/java/org/onap/dcaegen2/pmmapper/config/ConfigHandlerTests.java
+++ b/src/test/java/org/onap/dcaegen2/pmmapper/config/ConfigHandlerTests.java
@@ -18,9 +18,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.dcaegen2.pmmapper.config;
-
import static org.junit.jupiter.api.Assertions.assertThrows;
-import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
@@ -28,146 +26,95 @@
import java.io.InputStreamReader;
import java.net.UnknownHostException;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.extension.ExtendWith;
+
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.junit.jupiter.MockitoExtension;
import org.onap.dcaegen2.services.pmmapper.config.ConfigHandler;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;
-import org.onap.dcaegen2.services.pmmapper.exceptions.ConsulServerError;
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;
+import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
import com.google.gson.Gson;
-@ExtendWith(MockitoExtension.class)
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import utils.LoggingUtils;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(EnvironmentConfig.class)
public class ConfigHandlerTests {
- private static String cbsConfig;
private static String validMapperConfig;
- private String consulURL = "http://my_consult_host:8500/v1/catalog/service/config-binding-service";
- private String cbsURL = "http://config-binding-service:10000/service_component/pm-mapper-service-name";
+ private static String HOSTNAME = "pm-mapper-service-name";
+ private static String CBS_HOST = "cbs_host";
+ private static int CBS_PORT = 10000;
private Gson gson = new Gson();
@Mock
private RequestSender sender;
- @BeforeAll()
- public static void beforeAll() throws IOException {
+ @BeforeClass()
+ public static void beforeClass() throws Exception {
validMapperConfig = getFileContents("valid_mapper_config.json");
- cbsConfig = getFileContents("valid_cbs_config.json");
}
- @BeforeEach
- public void beforeEach() throws Exception {
- System.setProperty("CONSUL_HOST", "my_consult_host");
- System.setProperty("CONSUL_PORT", "8500");
- System.setProperty("CONFIG_BINDING_SERVICE", "config-binding-service");
- System.setProperty("HOSTNAME", "hotstname");
- }
- @Test
- public void environmentConfig_missing_consulHost() throws EnvironmentConfigException {
- System.clearProperty("CONSUL_HOST");
- System.clearProperty("CONFIG_BINDING_SERVICE");
-
- Exception exception = assertThrows(EnvironmentConfigException.class, () -> {
- ConfigHandler configHandler = new ConfigHandler(sender);
- configHandler.getMapperConfig();
- });
-
- assertTrue(exception.getMessage()
- .contains("$CONSUL_HOST environment variable must be defined"));
+ @Before
+ public void before() throws Exception {
+ PowerMockito.mockStatic(EnvironmentConfig.class);
+ PowerMockito.when(EnvironmentConfig.getCBSHostName()).thenReturn(CBS_HOST);
+ PowerMockito.when(EnvironmentConfig.getCBSPort()).thenReturn(CBS_PORT);
+ PowerMockito.when(EnvironmentConfig.getServiceName()).thenReturn(HOSTNAME);
}
@Test
public void getMapperConfig_success() throws Exception {
- when(sender.send(anyString())).then(invocation -> {
- String url = (String) invocation.getArguments()[0];
- return url.equals(consulURL) ? cbsConfig : validMapperConfig;
- });
+ ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(ConfigHandler.class);
+ String validCbsUrl = "http://" + CBS_HOST + ":" + CBS_PORT +"/service_component/" + HOSTNAME;
+ when(sender.send(validCbsUrl)).thenReturn(validMapperConfig);
MapperConfig actualConfig = getMapperConfig();
MapperConfig expectedConfig = gson.fromJson(validMapperConfig, MapperConfig.class);
assertEquals(expectedConfig, actualConfig);
- }
-
- @Test
- public void configbinding_config_format_error() throws Exception {
- when(sender.send(consulURL)).then((invocationMock) -> {
- return "some string that is not cbs config";
- });
-
- assertThrows(CBSConfigException.class, this::getMapperConfig);
- }
-
- @Test
- public void consul_host_is_unknown() throws Exception {
- when(sender.send(consulURL)).thenThrow(new UnknownHostException());
- assertThrows(ConsulServerError.class, this::getMapperConfig);
- }
-
- @Test
- public void configbinding_host_is_unknown() throws Exception {
- when(sender.send(anyString())).then(invocation -> {
- boolean isCBS = invocation.getArguments()[0].equals(cbsURL);
- if (isCBS) {
- throw new UnknownHostException("unknown cbs");
- }
- return cbsConfig;
- });
-
- assertThrows(CBSServerError.class, this::getMapperConfig);
- }
-
- @Test
- public void consul_port_invalid() throws Exception {
- System.setProperty("CONSUL_PORT", "19d93hjuji");
- assertThrows(EnvironmentConfigException.class, this::getMapperConfig);
- }
-
- @Test
- public void consul_server_error() throws Exception {
- when(sender.send(consulURL)).thenThrow(new ConsulServerError("consul server error", new Throwable()));
- assertThrows(ConsulServerError.class, this::getMapperConfig);
+ assertEquals(logAppender.list.get(0).getMarker().getName(), "ENTRY");
+ assertTrue(logAppender.list.get(1).getMessage().contains("Received pm-mapper configuration from ConfigBinding Service"));
+ assertEquals(logAppender.list.get(1).getMarker().getName(), "EXIT");
+ logAppender.stop();
}
@Test
public void configbinding_server_error() throws Exception {
- when(sender.send(anyString())).then(invocation -> {
- boolean isCBS = invocation.getArguments()[0].equals(cbsURL);
- if (isCBS) {
- throw new CBSServerError("unknown cbs", new Throwable());
- }
- return cbsConfig;
- });
-
+ when(sender.send(anyString())).thenThrow(CBSServerError.class);
assertThrows(CBSServerError.class, this::getMapperConfig);
}
@Test
- public void mapper_parse_invalid_json() throws Exception {
- when(sender.send(anyString())).then(invocation -> {
- String url = (String) invocation.getArguments()[0];
- return url.equals(consulURL) ? cbsConfig : "mapper config with incorrect format";
- });
+ public void configbinding_server_host_missing() throws Exception {
+ PowerMockito.when(EnvironmentConfig.getCBSHostName()).thenThrow(EnvironmentConfigException.class);
+ assertThrows(EnvironmentConfigException.class, this::getMapperConfig);
+ }
+ @Test
+ public void mapper_parse_invalid_json() throws Exception {
+ when(sender.send(anyString())).thenReturn("mapper config with incorrect format");
assertThrows(MapperConfigException.class, this::getMapperConfig);
}
@Test
public void mapper_parse_valid_json_missing_attributes() throws Exception {
- when(sender.send(anyString())).then(invocation -> {
- String incompleteConfig = getFileContents("incomplete_mapper_config.json");
- String url = (String) invocation.getArguments()[0];
- return url.equals(consulURL) ? cbsConfig : incompleteConfig;
- });
-
+ when(sender.send(anyString())).thenReturn(getFileContents("incomplete_mapper_config.json"));
assertThrows(MapperConfigException.class, this::getMapperConfig);
}
diff --git a/src/test/java/org/onap/dcaegen2/pmmapper/config/EnvironmentConfigTest.java b/src/test/java/org/onap/dcaegen2/pmmapper/config/EnvironmentConfigTest.java
new file mode 100644
index 0000000..95a51f7
--- /dev/null
+++ b/src/test/java/org/onap/dcaegen2/pmmapper/config/EnvironmentConfigTest.java
@@ -0,0 +1,71 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.dcaegen2.pmmapper.config;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.Assert.assertEquals;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;
+import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest(EnvironmentConfig.class)
+public class EnvironmentConfigTest {
+
+ @Before
+ public void before() throws Exception {
+ PowerMockito.mockStatic(System.class);
+ }
+
+ @Test
+ public void environmentConfig_is_present_success() throws EnvironmentConfigException {
+ String CBS_HOST = "cbs_host";
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_HOST_KEY)).thenReturn(CBS_HOST);
+ assertEquals(CBS_HOST,EnvironmentConfig.getCBSHostName() );
+ }
+
+ @Test
+ public void environmentConfig_host_not_present() throws EnvironmentConfigException {
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_HOST_KEY)).thenCallRealMethod();
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);
+ }
+
+ @Test
+ public void environmentConfig_hostname_present() throws EnvironmentConfigException {
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_SERVICE_NAME_KEY)).thenCallRealMethod();
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);
+ }
+
+ @Test
+ public void environmentConfig_default_port_is_used() throws EnvironmentConfigException {
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_PORT_KEY)).thenReturn(null);
+ assertEquals(Integer.valueOf(EnvironmentConfig.DEFAULT_CBS_PORT),EnvironmentConfig.getCBSPort());
+ }
+
+ @Test
+ public void environmentConfig_port_invalid() throws EnvironmentConfigException {
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_PORT_KEY)).thenReturn("Invalid_port number");
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);
+ }
+}
diff --git a/src/test/java/org/onap/dcaegen2/pmmapper/config/util/RequestSenderTests.java b/src/test/java/org/onap/dcaegen2/pmmapper/config/util/RequestSenderTests.java
index 470f146..770ae43 100644
--- a/src/test/java/org/onap/dcaegen2/pmmapper/config/util/RequestSenderTests.java
+++ b/src/test/java/org/onap/dcaegen2/pmmapper/config/util/RequestSenderTests.java
@@ -19,13 +19,14 @@
*/
package org.onap.dcaegen2.pmmapper.config.util;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
import java.io.IOException;
-import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
@@ -33,15 +34,19 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Matchers;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.integration.ClientAndServer;
+import org.mockserver.model.HttpRequest;
import org.mockserver.model.HttpStatusCode;
import org.mockserver.verify.VerificationTimes;
import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import utils.LoggingUtils;
@RunWith(PowerMockRunner.class)
@PrepareForTest(RequestSender.class)
@@ -60,23 +65,27 @@
mockServer.stop();
}
- @BeforeClass
- public static void setEnvironmentVariable() {
- System.setProperty("CONSUL_HOST", "my_consult_host");
- System.setProperty("CONFIG_BINDING_SERVICE", "config-binding-service");
- System.setProperty("HOSTNAME", "hostname");
- }
-
@Test
public void send_success() throws Exception {
+ String url = "http://127.0.0.1:1080/once";
+ String uuidRegex = "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$";
+ ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(RequestSender.class);
+ HttpRequest req = HttpRequest.request();
- client.when(request())
- .respond(response().withStatusCode(HttpStatusCode.OK_200.code()));
+ client.when(req
+ .withHeader(ONAPLogConstants.Headers.REQUEST_ID, uuidRegex)
+ .withHeader(ONAPLogConstants.Headers.INVOCATION_ID, uuidRegex))
+ .respond(response()
+ .withStatusCode(HttpStatusCode.OK_200.code())
+ .withBody("ResponseBody"));
+ String result = new RequestSender().send(url);
- new RequestSender().send("http://127.0.0.1:1080/once");
-
- client.verify(request(), VerificationTimes.exactly(1));
- client.clear(request());
+ client.verify(req, VerificationTimes.atLeast(1));
+ assertEquals(result, "ResponseBody");
+ assertTrue(logAppender.list.get(1).getMessage().contains("Sending"));
+ assertTrue(logAppender.list.get(2).getMessage().contains("Received"));
+ logAppender.stop();
+ client.clear(req);
}
@Test
@@ -95,17 +104,17 @@
}
@Test
- public void host_unknown() throws IOException {
+ public void host_unknown() throws Exception {
PowerMockito.mockStatic(Thread.class);
- URL url = PowerMockito.mock(URL.class);
- PowerMockito.when(url.openConnection())
- .thenThrow(UnknownHostException.class);
+ String unknownHostUrl = "http://unknown-host:1080/host-is-unknown";
+ PowerMockito.whenNew(URL.class).withArguments(unknownHostUrl)
+ .thenThrow(UnknownHostException.class);
assertThrows(Exception.class, () -> {
- new RequestSender().send("http://127.0.0.1:1080/host-is-unknown");
+ new RequestSender().send(unknownHostUrl);
});
- client.verify(request(), VerificationTimes.exactly(5));
+ client.verify(request(), VerificationTimes.exactly(0));
client.clear(request());
}
@@ -113,4 +122,4 @@
return new MockServerClient("127.0.0.1", 1080);
}
-}
+}
\ No newline at end of file
diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriberTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriberTest.java
index 645d1be..00dc040 100644
--- a/src/test/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriberTest.java
+++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/datarouter/DataRouterSubscriberTest.java
@@ -29,14 +29,21 @@
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
import io.undertow.io.Receiver;
import io.undertow.io.Sender;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.StatusCodes;
+import utils.LoggingUtils;
+
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
@@ -50,13 +57,14 @@
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.onap.dcaegen2.services.pmmapper.exceptions.TooManyTriesException;
-import org.onap.dcaegen2.services.pmmapper.model.BusControllerConfig;
+import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
import org.onap.dcaegen2.services.pmmapper.model.Event;
import org.onap.dcaegen2.services.pmmapper.model.EventMetadata;
+import org.onap.dcaegen2.services.pmmapper.utils.HttpServerExchangeAdapter;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-
+import org.slf4j.LoggerFactory;
@RunWith(PowerMockRunner.class)
@PrepareForTest(DataRouterSubscriber.class)
@@ -78,8 +86,8 @@
PowerMockito.mockStatic(Thread.class);
URL subEndpoint = mock(URL.class);
- BusControllerConfig config = new BusControllerConfig();
- config.setDataRouterSubscribeEndpoint(subEndpoint);
+ MapperConfig config = mock(MapperConfig.class);
+ when(config.getBusControllerSubscriptionUrl()).thenReturn(subEndpoint);
HttpURLConnection huc = mock(HttpURLConnection.class, RETURNS_DEEP_STUBS);
when(subEndpoint.openConnection()).thenReturn(huc);
when(huc.getResponseCode()).thenReturn(300);
@@ -89,8 +97,8 @@
@Test
public void testStartImmediateSuccess() throws IOException, TooManyTriesException, InterruptedException {
URL subEndpoint = mock(URL.class);
- BusControllerConfig config = new BusControllerConfig();
- config.setDataRouterSubscribeEndpoint(subEndpoint);
+ MapperConfig config = mock(MapperConfig.class);
+ when(config.getBusControllerSubscriptionUrl()).thenReturn(subEndpoint);
HttpURLConnection huc = mock(HttpURLConnection.class, RETURNS_DEEP_STUBS);
when(subEndpoint.openConnection()).thenReturn(huc);
when(huc.getResponseCode()).thenReturn(200);
@@ -103,8 +111,8 @@
PowerMockito.mockStatic(Thread.class);
URL subEndpoint = mock(URL.class);
- BusControllerConfig config = new BusControllerConfig();
- config.setDataRouterSubscribeEndpoint(subEndpoint);
+ MapperConfig config = mock(MapperConfig.class);
+ when(config.getBusControllerSubscriptionUrl()).thenReturn(subEndpoint);
HttpURLConnection huc = mock(HttpURLConnection.class, RETURNS_DEEP_STUBS);
when(subEndpoint.openConnection()).thenReturn(huc);
doAnswer(new Answer() {
@@ -128,8 +136,8 @@
PowerMockito.mockStatic(Thread.class);
URL subEndpoint = mock(URL.class);
- BusControllerConfig config = new BusControllerConfig();
- config.setDataRouterSubscribeEndpoint(subEndpoint);
+ MapperConfig config = mock(MapperConfig.class);
+ when(config.getBusControllerSubscriptionUrl()).thenReturn(subEndpoint);
HttpURLConnection huc = mock(HttpURLConnection.class, RETURNS_DEEP_STUBS);
when(subEndpoint.openConnection()).thenReturn(huc);
doThrow(new IOException()).when(huc).getResponseCode();
@@ -139,6 +147,9 @@
@Test
public void testRequestInboundLimitedStateServiceUnavailable() throws Exception {
HttpServerExchange httpServerExchange = mock(HttpServerExchange.class);
+ HttpServerExchangeAdapter adapterMock = PowerMockito.mock(HttpServerExchangeAdapter.class);
+ PowerMockito.whenNew(HttpServerExchangeAdapter.class).withAnyArguments().thenReturn(adapterMock);
+
Sender responseSender = mock(Sender.class);
when(httpServerExchange.setStatusCode(anyInt())).thenReturn(httpServerExchange);
when(httpServerExchange.getResponseSender()).thenReturn(responseSender);
@@ -150,6 +161,9 @@
@Test
public void testRequestInboundLimitedStateServiceNoEmission() throws Exception {
HttpServerExchange httpServerExchange = mock(HttpServerExchange.class);
+ HttpServerExchangeAdapter adapterMock = PowerMockito.mock(HttpServerExchangeAdapter.class);
+ PowerMockito.whenNew(HttpServerExchangeAdapter.class).withAnyArguments().thenReturn(adapterMock);
+
Sender responseSender = mock(Sender.class);
when(httpServerExchange.setStatusCode(anyInt())).thenReturn(httpServerExchange);
when(httpServerExchange.getResponseSender()).thenReturn(responseSender);
@@ -197,6 +211,7 @@
@Test
public void testRequestInboundSuccess() throws Exception {
+ ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(DataRouterSubscriber.class);
HttpServerExchange httpServerExchange = mock(HttpServerExchange.class, RETURNS_DEEP_STUBS);
Receiver receiver = mock(Receiver.class);
when(httpServerExchange.getRequestReceiver()).thenReturn(receiver);
@@ -222,5 +237,12 @@
.receive(new Event(httpServerExchange, testString,
new GsonBuilder().create()
.fromJson(metadata, EventMetadata.class)));
+
+ assertEquals(logAppender.list.get(0).getMarker().getName(), "ENTRY");
+ assertNotNull(logAppender.list.get(0).getMDCPropertyMap().get("InvocationID"));
+ assertNotNull(logAppender.list.get(0).getMDCPropertyMap().get("RequestID"));
+ assertEquals(logAppender.list.get(1).getMarker().getName(), "EXIT");
+ logAppender.stop();
}
+
}
diff --git a/src/test/java/utils/LoggingUtils.java b/src/test/java/utils/LoggingUtils.java
new file mode 100644
index 0000000..053bd0c
--- /dev/null
+++ b/src/test/java/utils/LoggingUtils.java
@@ -0,0 +1,41 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package utils;
+
+import org.slf4j.LoggerFactory;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+
+public class LoggingUtils {
+
+ /**
+ * Returns a ListAppender that contains all logging events. Call this method at the very beginning of the test
+ * */
+ public static ListAppender<ILoggingEvent> getLogListAppender(Class<?> c) {
+ Logger logger = (Logger) LoggerFactory.getLogger(c);
+ ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
+ listAppender.start();
+ logger.addAppender(listAppender);
+
+ return listAppender;
+ }
+}
diff --git a/src/test/resources/incomplete_mapper_config.json b/src/test/resources/incomplete_mapper_config.json
index aec0aca..ed4ebd7 100644
--- a/src/test/resources/incomplete_mapper_config.json
+++ b/src/test/resources/incomplete_mapper_config.json
@@ -1,10 +1,10 @@
{
- "_comment": "This mapper config is missing the messagerouter feed name",
+ "_comment": "This mapper config is missing streams_subscribes",
"pm-mapper-filter": {
"filters": "{[]}"
},
"3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",
- "streams_subscribes": {},
+ "streams_subscribes": null,
"streams_publishes": {
"pm_mapper_handle_out": {
"type": "message_router",
diff --git a/src/test/resources/valid_cbs_config.json b/src/test/resources/valid_cbs_config.json
deleted file mode 100644
index e2fc650..0000000
--- a/src/test/resources/valid_cbs_config.json
+++ /dev/null
@@ -1,23 +0,0 @@
-[
- {
- "ID": "6e331b82-6563-3bf7-4acc-d02d1e042c9b",
- "Node": "dcae-bootstrap",
- "Address": "10.42.249.191",
- "Datacenter": "dc1",
- "TaggedAddresses": {
- "lan": "10.42.249.191",
- "wan": "10.42.249.191"
- },
- "NodeMeta": {
- "consul-network-segment": ""
- },
- "ServiceID": "dcae-cbs0",
- "ServiceName": "pm-mapper-service-name",
- "ServiceTags": [],
- "ServiceAddress": "config-binding-service",
- "ServicePort": 10000,
- "ServiceEnableTagOverride": false,
- "CreateIndex": 124,
- "ModifyIndex": 124
- }
-]
\ No newline at end of file
diff --git a/src/test/resources/valid_mapper_config.json b/src/test/resources/valid_mapper_config.json
index 7106141..27765ae 100644
--- a/src/test/resources/valid_mapper_config.json
+++ b/src/test/resources/valid_mapper_config.json
@@ -1,7 +1,20 @@
{
"pm-mapper-filter": "{ \"filters\":[]}",
"3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",
- "streams_subscribes": {},
+ "streams_subscribes": {
+ "dmaap_subscriber": {
+ "type": "data_router",
+ "aaf_username": null,
+ "aaf_password": null,
+ "dmaap_info": {
+ "location": "location",
+ "delivery_url": "delivery_url",
+ "username": "username",
+ "password": "password",
+ "subscriber_id": "subsriber_id"
+ }
+ }
+ },
"streams_publishes": {
"pm_mapper_handle_out": {
"type": "message_router",
@@ -15,6 +28,7 @@
"aaf_username": null
}
},
- "streams_subscribes.pm_mapper_handle_out.message_router_topic": "unauthenticated.PM_VES_OUTPUT",
+ "buscontroller_feed_id": "2",
+ "buscontroller_feed_subscription_endpoint": "http://dmaap-bc.onap.svc.cluster.local:8080/webapi/dr_subs",
"services_calls": {}
}
\ No newline at end of file