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;
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")
*/\r
package org.onap.dcaegen2.services.pmmapper.config;\r
\r
-import java.util.Arrays;\r
-import java.util.UUID;\r
-\r
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSConfigException;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;\r
-import org.onap.dcaegen2.services.pmmapper.exceptions.ConsulServerError;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;\r
-import org.onap.dcaegen2.services.pmmapper.model.CBSConfig;\r
import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;\r
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;\r
import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;\r
\r
public class ConfigHandler {\r
private static final ONAPLogAdapter logger = new ONAPLogAdapter(LoggerFactory.getLogger(ConfigHandler.class));\r
- private static final String EMPTY_MESSAGE = "";\r
private RequestSender sender;\r
\r
/**\r
* @throws CBSServerError\r
* @throws MapperConfigException\r
*/
- public MapperConfig getMapperConfig() throws CBSConfigException, ConsulServerError, EnvironmentConfigException,\r
+ public MapperConfig getMapperConfig() throws CBSConfigException, EnvironmentConfigException,\r
CBSServerError, MapperConfigException {\r
String mapperConfigJson = "";\r
- CBSConfig cbsConfig = convertCBSConfigToObject(getCBSConfigFromConsul());\r
- String cbsSocketAddress = cbsConfig.getServiceAddress() + ":" + cbsConfig.getServicePort();\r
- String requestURL = "http://" + cbsSocketAddress + "/service_component/" + cbsConfig.getServiceName();\r
+ String cbsSocketAddress = EnvironmentConfig.getCBSHostName() + ":" + EnvironmentConfig.getCBSPort();\r
+ String requestURL = "http://" + cbsSocketAddress + "/service_component/" + EnvironmentConfig.getServiceName();\r
try {\r
logger.unwrap().info(ONAPLogConstants.Markers.ENTRY, "Fetching pm-mapper configuration from Configbinding Service");\r
mapperConfigJson = sender.send(requestURL);\r
} catch (Exception exception) {\r
throw new CBSServerError("Error connecting to Configbinding Service: ", exception);\r
} finally {\r
- logger.unwrap().info(ONAPLogConstants.Markers.EXIT, EMPTY_MESSAGE);\r
+ logger.unwrap().info(ONAPLogConstants.Markers.EXIT, "Received pm-mapper configuration from ConfigBinding Service:\n{}", mapperConfigJson);\r
}\r
\r
- logger.unwrap().info("Received pm-mapper configuration from ConfigBinding Service:\n{}", mapperConfigJson);\r
return convertMapperConfigToObject(mapperConfigJson);\r
}\r
\r
- private String getCBSConfigFromConsul() throws ConsulServerError, EnvironmentConfigException {\r
- String cbsParams="";\r
- String consulURL = "http://" + EnvironmentConfig.getConsulHost() + ":" + EnvironmentConfig.getConsultPort()\r
- + "/v1/catalog/service/" + EnvironmentConfig.getCbsName();\r
- try {\r
- logger.unwrap().info(ONAPLogConstants.Markers.ENTRY,\r
- "Retrieving ConfigBinding Service parameters from this Consul URL: {}", consulURL);\r
- cbsParams = sender.send(consulURL);\r
- } catch (Exception exception) {\r
- throw new ConsulServerError("Error connecting to Consul: ", exception);\r
- } finally {\r
- logger.unwrap().info(ONAPLogConstants.Markers.EXIT, "Received ConfigBinding Service parameters:\n{}", cbsParams);\r
- }\r
-\r
- return cbsParams;\r
- }\r
-\r
private MapperConfig convertMapperConfigToObject(String mapperConfigJson) throws MapperConfigException {\r
MapperConfig mapperConfig;\r
try {\r
logger.unwrap().debug("Mapper configuration:\n{}", mapperConfig);\r
return mapperConfig;\r
}\r
-\r
- private CBSConfig convertCBSConfigToObject(String cbsParameters) throws CBSConfigException {\r
- CBSConfig cbsConfig;\r
- try {\r
- cbsConfig = Arrays\r
- .asList(new GsonBuilder()\r
- .registerTypeAdapter(CBSConfig.class, new RequiredFieldDeserializer<CBSConfig>())\r
- .create()\r
- .fromJson(cbsParameters, CBSConfig[].class))\r
- .get(0);\r
- logger.unwrap().debug("ConfigBinding Service Configurations: " + cbsConfig);\r
- } catch (Exception exception) {\r
- throw new CBSConfigException(\r
- "Error mapping the received ConfigBinding service configuration parameters: " + cbsParameters,\r
- exception);\r
- }\r
- return cbsConfig;\r
- }\r
-\r
}\r
import org.onap.dcaegen2.services.pmmapper.exceptions.TooManyTriesException;
import org.onap.dcaegen2.services.pmmapper.model.EventMetadata;
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;
-import org.onap.dcaegen2.services.pmmapper.model.BusControllerConfig;
import org.onap.dcaegen2.services.pmmapper.model.Event;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
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;
* 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 {
+ 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);
}
}
- 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);
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 {
+++ /dev/null
-/*-\r
- * ============LICENSE_START=======================================================\r
- * Copyright (C) 2019 Nordix Foundation.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- *\r
- * SPDX-License-Identifier: Apache-2.0\r
- * ============LICENSE_END=========================================================\r
- */\r
-package org.onap.dcaegen2.services.pmmapper.exceptions;\r
-\r
-public class ConsulServerError extends Exception {\r
- public ConsulServerError(String message, Throwable cause) {\r
- super(message, cause);\r
- }\r
-}\r
+++ /dev/null
-/*-
- * ============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;
-
-}
+++ /dev/null
-/*-\r
- * ============LICENSE_START=======================================================\r
- * Copyright (C) 2019 Nordix Foundation.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- *\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- *\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- *\r
- * SPDX-License-Identifier: Apache-2.0\r
- * ============LICENSE_END=========================================================\r
- */\r
-package org.onap.dcaegen2.services.pmmapper.model;\r
-\r
-import org.onap.dcaegen2.services.pmmapper.utils.GSONRequired;\r
-\r
-import com.google.gson.annotations.SerializedName;\r
-import lombok.Data;\r
-\r
-@Data\r
-public class CBSConfig {\r
-\r
- @GSONRequired\r
- @SerializedName("ServiceID")\r
- private String serviceID;\r
-\r
- @GSONRequired\r
- @SerializedName("ServiceName")\r
- private String serviceName;\r
-\r
- @GSONRequired\r
- @SerializedName("ServiceAddress")\r
- private String serviceAddress;\r
-\r
- @GSONRequired\r
- @SerializedName("ServicePort")\r
- private String servicePort;\r
-\r
-}\r
\r
public class EnvironmentConfig {\r
\r
- private static Integer consulPort = 8500;\r
+ public static final int DEFAULT_CBS_PORT = 10000;\r
+ public static final String ENV_CBS_HOST_KEY = "CONFIG_BINDING_SERVICE_SERVICE_HOST";\r
+ public static final String ENV_CBS_PORT_KEY = "CONFIG_BINDING_SERVICE_SERVICE_PORT";\r
+ public static final String ENV_SERVICE_NAME_KEY = "HOSTNAME";\r
\r
- public static String getConsulHost() throws EnvironmentConfigException {\r
- return Optional.ofNullable(System.getProperty("CONSUL_HOST"))\r
+ public static String getServiceName() throws EnvironmentConfigException {\r
+ return Optional.ofNullable(System.getenv("HOSTNAME"))\r
.orElseThrow(() -> new EnvironmentConfigException(\r
- "$CONSUL_HOST environment variable must be defined prior to pm-mapper initialization"));\r
+ ENV_SERVICE_NAME_KEY+ " environment variable must be defined prior to pm-mapper initialization."));\r
}\r
\r
- public static Integer getConsultPort() throws EnvironmentConfigException {\r
- Integer port = consulPort;\r
+ public static String getCBSHostName() throws EnvironmentConfigException {\r
+ return Optional.ofNullable(System.getenv("CONFIG_BINDING_SERVICE_SERVICE_HOST"))\r
+ .orElseThrow(() -> new EnvironmentConfigException(\r
+ ENV_CBS_HOST_KEY+ " environment variable must be defined prior to pm-mapper initialization."));\r
+ }\r
+\r
+ public static Integer getCBSPort() throws EnvironmentConfigException {\r
+ Integer port = DEFAULT_CBS_PORT;\r
try {\r
- port = Optional.ofNullable(System.getProperty("CONSUL_PORT"))\r
- .map(Integer::valueOf)\r
- .orElse(consulPort);\r
+ port = Optional.ofNullable(System.getenv("CONFIG_BINDING_SERVICE_SERVICE_PORT"))\r
+ .map(Integer::valueOf).orElse(DEFAULT_CBS_PORT);\r
} catch (NumberFormatException e) {\r
- throw new EnvironmentConfigException("CONSUL_PORT must be valid: " + port);\r
+ throw new EnvironmentConfigException(ENV_CBS_PORT_KEY + " must be valid: " + port);\r
}\r
return port;\r
\r
}\r
-\r
- public static String getCbsName() throws EnvironmentConfigException {\r
- return Optional.ofNullable(System.getProperty("CONFIG_BINDING_SERVICE"))\r
- .orElseThrow(() -> new EnvironmentConfigException(\r
- "$CONFIG_BINDING_SERVICE environment variable must be defined prior to pm-mapper initialization."));\r
- }\r
}\r
*/\r
package org.onap.dcaegen2.services.pmmapper.model;\r
\r
+import java.net.MalformedURLException;\r
+import java.net.URL;\r
+\r
import org.onap.dcaegen2.services.pmmapper.utils.GSONRequired;\r
import com.google.gson.annotations.SerializedName;\r
-import lombok.Data;\r
+import lombok.Getter;\r
+import lombok.AccessLevel;\r
+import lombok.EqualsAndHashCode;\r
import lombok.NoArgsConstructor;\r
\r
-@Data\r
+@Getter\r
+@EqualsAndHashCode\r
@NoArgsConstructor\r
public class MapperConfig {\r
+\r
public static final String CLIENT_NAME = "pm-mapper";\r
\r
@GSONRequired\r
- @SerializedName("streams_subscribes.pm_mapper_handle_out.message_router_topic")\r
- private String messageRouterTopicName;
+ @Getter(AccessLevel.PRIVATE)\r
+ @SerializedName("streams_subscribes")\r
+ private StreamsSubscribes streamsSubscribes;\r
+\r
+ @GSONRequired\r
+ @SerializedName("buscontroller_feed_subscription_endpoint")\r
+ private String busControllerSubscriptionEndpoint;\r
+\r
+ @GSONRequired\r
+ @SerializedName("buscontroller_feed_id")\r
+ private String busControllerFeedId;\r
+\r
+ public String getBusControllerDeliveryUrl() {\r
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getDeliveryUrl();\r
+ }\r
+\r
+ public String getDcaeLocation() {\r
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getLocation();\r
+ }\r
+\r
+ public String getBusControllerUserName() {\r
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getUsername();\r
+ }\r
+\r
+ public String getBusControllerPassword() {\r
+ return this.getStreamsSubscribes().getDmaapSubscriber().getDmaapInfo().getPassword();\r
+ }\r
+\r
+ public URL getBusControllerSubscriptionUrl() throws MalformedURLException {\r
+ return new URL(this.getBusControllerSubscriptionEndpoint());\r
+ }\r
+\r
+ @Getter\r
+ @EqualsAndHashCode\r
+ private class StreamsSubscribes {\r
+ @GSONRequired\r
+ @SerializedName("dmaap_subscriber")\r
+ DmaapSubscriber dmaapSubscriber;\r
+ }\r
+\r
+ @Getter\r
+ @EqualsAndHashCode\r
+ class DmaapSubscriber {\r
+ @GSONRequired\r
+ @SerializedName("dmaap_info")\r
+ DmaapInfo dmaapInfo;\r
+ }\r
+\r
+ @Getter\r
+ @EqualsAndHashCode\r
+ class DmaapInfo {\r
+ @GSONRequired\r
+ private String location;\r
+ private String username;\r
+ private String password;\r
+\r
+ @SerializedName("delivery_url")\r
+ private String deliveryUrl;\r
+\r
+ @SerializedName("subscriber_id")\r
+ private String subscriberId;\r
+ }\r
+}\r
+\r
+\r
\r
- BusControllerConfig busControllerConfig;\r
\r
-}
\ No newline at end of file
\r
} catch (Exception e) {\r
if (retryLimitReached(i)) {\r
+ logger.unwrap()\r
+ .error("Execution error: "+connection.getResponseMessage(), e);\r
throw new Exception(SERVER_ERROR_MESSAGE + ": " + connection.getResponseMessage(), e);\r
}\r
}\r
* ============LICENSE_END=========================================================\r
*/\r
package org.onap.dcaegen2.pmmapper.config;\r
-\r
-import static org.junit.jupiter.api.Assertions.*;\r
+import static org.junit.jupiter.api.Assertions.assertThrows;\r
import static org.mockito.Mockito.when;\r
\r
import java.io.BufferedReader;\r
import java.io.InputStreamReader;\r
import java.net.UnknownHostException;\r
\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertTrue;\r
import static org.mockito.Mockito.*;\r
-import org.junit.jupiter.api.BeforeAll;\r
-import org.junit.jupiter.api.BeforeEach;\r
-import org.junit.jupiter.api.Test;\r
-import org.junit.jupiter.api.extension.ExtendWith;\r
+\r
+import org.junit.Before;\r
+import org.junit.BeforeClass;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
import org.mockito.Mock;\r
-import org.mockito.junit.jupiter.MockitoExtension;\r
import org.onap.dcaegen2.services.pmmapper.config.ConfigHandler;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSConfigException;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;\r
-import org.onap.dcaegen2.services.pmmapper.exceptions.ConsulServerError;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;\r
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;\r
+import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;\r
import org.onap.dcaegen2.services.pmmapper.model.MapperConfig;\r
import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;\r
+import org.powermock.api.mockito.PowerMockito;\r
+import org.powermock.core.classloader.annotations.PrepareForTest;\r
+import org.powermock.modules.junit4.PowerMockRunner;\r
\r
import com.google.gson.Gson;\r
\r
import ch.qos.logback.core.read.ListAppender;\r
import utils.LoggingUtils;\r
\r
-@ExtendWith(MockitoExtension.class)\r
+@RunWith(PowerMockRunner.class)\r
+@PrepareForTest(EnvironmentConfig.class)\r
public class ConfigHandlerTests {\r
- private static String cbsConfig;\r
private static String validMapperConfig;\r
- private String consulURL = "http://my_consult_host:8500/v1/catalog/service/config-binding-service";\r
- private String cbsURL = "http://config-binding-service:10000/service_component/pm-mapper-service-name";\r
+ private static String HOSTNAME = "pm-mapper-service-name";\r
+ private static String CBS_HOST = "cbs_host";\r
+ private static int CBS_PORT = 10000;\r
private Gson gson = new Gson();\r
@Mock\r
private RequestSender sender;\r
\r
- @BeforeAll()\r
- public static void beforeAll() throws IOException {\r
+ @BeforeClass()\r
+ public static void beforeClass() throws Exception {\r
validMapperConfig = getFileContents("valid_mapper_config.json");\r
- cbsConfig = getFileContents("valid_cbs_config.json");\r
}\r
\r
- @BeforeEach\r
- public void beforeEach() throws Exception {\r
- System.setProperty("CONSUL_HOST", "my_consult_host");\r
- System.setProperty("CONSUL_PORT", "8500");\r
- System.setProperty("CONFIG_BINDING_SERVICE", "config-binding-service");\r
- System.setProperty("HOSTNAME", "hotstname");\r
- }\r
\r
- @Test\r
- public void environmentConfig_missing_consulHost() throws EnvironmentConfigException {\r
- System.clearProperty("CONSUL_HOST");\r
- System.clearProperty("CONFIG_BINDING_SERVICE");\r
-\r
- Exception exception = assertThrows(EnvironmentConfigException.class, () -> {\r
- ConfigHandler configHandler = new ConfigHandler(sender);\r
- configHandler.getMapperConfig();\r
- });\r
-\r
- assertTrue(exception.getMessage()\r
- .contains("$CONSUL_HOST environment variable must be defined"));\r
+ @Before\r
+ public void before() throws Exception {\r
+ PowerMockito.mockStatic(EnvironmentConfig.class);\r
+ PowerMockito.when(EnvironmentConfig.getCBSHostName()).thenReturn(CBS_HOST);\r
+ PowerMockito.when(EnvironmentConfig.getCBSPort()).thenReturn(CBS_PORT);\r
+ PowerMockito.when(EnvironmentConfig.getServiceName()).thenReturn(HOSTNAME);\r
}\r
\r
@Test\r
public void getMapperConfig_success() throws Exception {\r
ListAppender<ILoggingEvent> logAppender = LoggingUtils.getLogListAppender(ConfigHandler.class);\r
- when(sender.send(anyString())).then(invocation -> {\r
- String url = (String) invocation.getArguments()[0];\r
- return url.equals(consulURL) ? cbsConfig : validMapperConfig;\r
- });\r
+ String validCbsUrl = "http://" + CBS_HOST + ":" + CBS_PORT +"/service_component/" + HOSTNAME;\r
+ when(sender.send(validCbsUrl)).thenReturn(validMapperConfig);\r
\r
MapperConfig actualConfig = getMapperConfig();\r
MapperConfig expectedConfig = gson.fromJson(validMapperConfig, MapperConfig.class);\r
\r
assertEquals(expectedConfig, actualConfig);\r
assertEquals(logAppender.list.get(0).getMarker().getName(), "ENTRY");\r
- assertTrue(logAppender.list.get(1).getMessage().contains("Received ConfigBinding Service parameters"));\r
+ assertTrue(logAppender.list.get(1).getMessage().contains("Received pm-mapper configuration from ConfigBinding Service"));\r
assertEquals(logAppender.list.get(1).getMarker().getName(), "EXIT");\r
- assertTrue(logAppender.list.get(4).getMessage().contains("Received pm-mapper configuration from ConfigBinding Service"));\r
logAppender.stop();\r
}\r
\r
@Test\r
- public void configbinding_config_format_error() throws Exception {\r
- when(sender.send(consulURL)).then((invocationMock) -> {\r
- return "some string that is not cbs config";\r
- });\r
-\r
- assertThrows(CBSConfigException.class, this::getMapperConfig);\r
- }\r
-\r
- @Test\r
- public void consul_host_is_unknown() throws Exception {\r
- when(sender.send(consulURL)).thenThrow(new UnknownHostException());\r
- assertThrows(ConsulServerError.class, this::getMapperConfig);\r
- }\r
-\r
- @Test\r
- public void configbinding_host_is_unknown() throws Exception {\r
- when(sender.send(anyString())).then(invocation -> {\r
- boolean isCBS = invocation.getArguments()[0].equals(cbsURL);\r
- if (isCBS) {\r
- throw new UnknownHostException("unknown cbs");\r
- }\r
- return cbsConfig;\r
- });\r
-\r
+ public void configbinding_server_error() throws Exception {\r
+ when(sender.send(anyString())).thenThrow(CBSServerError.class);\r
assertThrows(CBSServerError.class, this::getMapperConfig);\r
}\r
\r
@Test\r
- public void consul_port_invalid() throws Exception {\r
- System.setProperty("CONSUL_PORT", "19d93hjuji");\r
+ public void configbinding_server_host_missing() throws Exception {\r
+ PowerMockito.when(EnvironmentConfig.getCBSHostName()).thenThrow(EnvironmentConfigException.class);\r
assertThrows(EnvironmentConfigException.class, this::getMapperConfig);\r
}\r
\r
- @Test\r
- public void consul_server_error() throws Exception {\r
- when(sender.send(consulURL)).thenThrow(new ConsulServerError("consul server error", new Throwable()));\r
- assertThrows(ConsulServerError.class, this::getMapperConfig);\r
- }\r
-\r
- @Test\r
- public void configbinding_server_error() throws Exception {\r
- when(sender.send(anyString())).then(invocation -> {\r
- boolean isCBS = invocation.getArguments()[0].equals(cbsURL);\r
- if (isCBS) {\r
- throw new CBSServerError("unknown cbs", new Throwable());\r
- }\r
- return cbsConfig;\r
- });\r
-\r
- assertThrows(CBSServerError.class, this::getMapperConfig);\r
- }\r
-\r
@Test\r
public void mapper_parse_invalid_json() throws Exception {\r
- when(sender.send(anyString())).then(invocation -> {\r
- String url = (String) invocation.getArguments()[0];\r
- return url.equals(consulURL) ? cbsConfig : "mapper config with incorrect format";\r
- });\r
-\r
+ when(sender.send(anyString())).thenReturn("mapper config with incorrect format");\r
assertThrows(MapperConfigException.class, this::getMapperConfig);\r
}\r
\r
@Test\r
public void mapper_parse_valid_json_missing_attributes() throws Exception {\r
- when(sender.send(anyString())).then(invocation -> {\r
- String incompleteConfig = getFileContents("incomplete_mapper_config.json");\r
- String url = (String) invocation.getArguments()[0];\r
- return url.equals(consulURL) ? cbsConfig : incompleteConfig;\r
- });\r
-\r
+ when(sender.send(anyString())).thenReturn(getFileContents("incomplete_mapper_config.json"));\r
assertThrows(MapperConfigException.class, this::getMapperConfig);\r
}\r
\r
--- /dev/null
+/*-\r
+ * ============LICENSE_START=======================================================\r
+ * Copyright (C) 2019 Nordix Foundation.\r
+ * ================================================================================\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ *\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ *\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ *\r
+ * SPDX-License-Identifier: Apache-2.0\r
+ * ============LICENSE_END=========================================================\r
+ */\r
+package org.onap.dcaegen2.pmmapper.config;\r
+import static org.junit.jupiter.api.Assertions.assertThrows;\r
+import static org.junit.Assert.assertEquals;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;\r
+import org.onap.dcaegen2.services.pmmapper.model.EnvironmentConfig;\r
+import org.powermock.api.mockito.PowerMockito;\r
+import org.powermock.core.classloader.annotations.PrepareForTest;\r
+import org.powermock.modules.junit4.PowerMockRunner;\r
+\r
+@RunWith(PowerMockRunner.class)\r
+@PrepareForTest(EnvironmentConfig.class)\r
+public class EnvironmentConfigTest {\r
+\r
+ @Before\r
+ public void before() throws Exception {\r
+ PowerMockito.mockStatic(System.class);\r
+ }\r
+\r
+ @Test\r
+ public void environmentConfig_is_present_success() throws EnvironmentConfigException {\r
+ String CBS_HOST = "cbs_host";\r
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_HOST_KEY)).thenReturn(CBS_HOST);\r
+ assertEquals(CBS_HOST,EnvironmentConfig.getCBSHostName() );\r
+ }\r
+\r
+ @Test\r
+ public void environmentConfig_host_not_present() throws EnvironmentConfigException {\r
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_HOST_KEY)).thenCallRealMethod();\r
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);\r
+ }\r
+\r
+ @Test\r
+ public void environmentConfig_hostname_present() throws EnvironmentConfigException {\r
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_SERVICE_NAME_KEY)).thenCallRealMethod();\r
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);\r
+ }\r
+\r
+ @Test\r
+ public void environmentConfig_default_port_is_used() throws EnvironmentConfigException {\r
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_PORT_KEY)).thenReturn(null);\r
+ assertEquals(Integer.valueOf(EnvironmentConfig.DEFAULT_CBS_PORT),EnvironmentConfig.getCBSPort());\r
+ }\r
+\r
+ @Test\r
+ public void environmentConfig_port_invalid() throws EnvironmentConfigException {\r
+ PowerMockito.when(System.getenv(EnvironmentConfig.ENV_CBS_PORT_KEY)).thenReturn("Invalid_port number");\r
+ assertThrows(EnvironmentConfigException.class,EnvironmentConfig::getCBSHostName);\r
+ }\r
+}\r
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;
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);
@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);
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() {
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();
{\r
- "_comment": "This mapper config is missing the messagerouter feed name",\r
+ "_comment": "This mapper config is missing streams_subscribes",\r
"pm-mapper-filter": {\r
"filters": "{[]}"\r
},\r
"3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",\r
- "streams_subscribes": {},\r
+ "streams_subscribes": null,\r
"streams_publishes": {\r
"pm_mapper_handle_out": {\r
"type": "message_router",\r
+++ /dev/null
-[\r
- {\r
- "ID": "6e331b82-6563-3bf7-4acc-d02d1e042c9b",\r
- "Node": "dcae-bootstrap",\r
- "Address": "10.42.249.191",\r
- "Datacenter": "dc1",\r
- "TaggedAddresses": {\r
- "lan": "10.42.249.191",\r
- "wan": "10.42.249.191"\r
- },\r
- "NodeMeta": {\r
- "consul-network-segment": ""\r
- },\r
- "ServiceID": "dcae-cbs0",\r
- "ServiceName": "pm-mapper-service-name",\r
- "ServiceTags": [],\r
- "ServiceAddress": "config-binding-service",\r
- "ServicePort": 10000,\r
- "ServiceEnableTagOverride": false,\r
- "CreateIndex": 124,\r
- "ModifyIndex": 124\r
- }\r
-]
\ No newline at end of file
{\r
"pm-mapper-filter": "{ \"filters\":[]}",\r
"3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",\r
- "streams_subscribes": {},\r
+ "streams_subscribes": {\r
+ "dmaap_subscriber": {\r
+ "type": "data_router",\r
+ "aaf_username": null,\r
+ "aaf_password": null,\r
+ "dmaap_info": {\r
+ "location": "location",\r
+ "delivery_url": "delivery_url",\r
+ "username": "username",\r
+ "password": "password",\r
+ "subscriber_id": "subsriber_id"\r
+ }\r
+ }\r
+ },\r
"streams_publishes": {\r
"pm_mapper_handle_out": {\r
"type": "message_router",\r
"aaf_username": null\r
}\r
},\r
- "streams_subscribes.pm_mapper_handle_out.message_router_topic": "unauthenticated.PM_VES_OUTPUT",\r
+ "buscontroller_feed_id": "2",\r
+ "buscontroller_feed_subscription_endpoint": "http://dmaap-bc.onap.svc.cluster.local:8080/webapi/dr_subs",\r
"services_calls": {}\r
}
\ No newline at end of file