--- /dev/null
+**/.settings\r
+*.classpath\r
+*.project\r
+**/target
\ No newline at end of file
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.onap.dcaegen2.services</groupId>
<mockito.version>2.23.4</mockito.version>
<mockito-ju5-ext.version>2.23.4</mockito-ju5-ext.version>
<powermock.version>2.0.0</powermock.version>
+ <mockserver.version>3.10.8</mockserver.version>
<junit4.version>4.12</junit4.version>
<!-- Plugin Versions -->
<shade.plugin.version>3.2.0</shade.plugin.version>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mock-server</groupId>
+ <artifactId>mockserver-netty</artifactId>
+ <version>${mockserver.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mock-server</groupId>
+ <artifactId>mockserver-client-java</artifactId>
+ <version>${mockserver.version}</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
- <configuration combine.self="override"/>
+ <configuration combine.self="override">
+ <useSystemClassLoader>false</useSystemClassLoader>
+ </configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>jar-with-dependencies</shadedClassifierName>
<transformers>
- <transformer implementation="${shade.transformer}">
+ <transformer
+ implementation="${shade.transformer}">
<mainClass>${shade.main}</mainClass>
</transformer>
</transformers>
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.util.StatusCodes;
-import org.onap.dcaegen2.services.pmmapper.config.BusControllerConfig;
+
+import org.onap.dcaegen2.services.pmmapper.config.ConfigHandler;
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 java.net.MalformedURLException;
import java.net.URL;
public class App {
- public static void main(String[] args) throws MalformedURLException, InterruptedException, TooManyTriesException {
+ public static void main(String[] args) throws MalformedURLException, InterruptedException, TooManyTriesException, CBSConfigException, ConsulServerError, EnvironmentConfigException, CBSServerError, MapperConfigException {
DataRouterSubscriber dataRouterSubscriber = new DataRouterSubscriber(event -> {
event.getHttpServerExchange().unDispatch();
event.getHttpServerExchange().getResponseSender().send(StatusCodes.OK_STRING);
System.out.println(event.getMetadata().getProductName());
});
- BusControllerConfig config = new BusControllerConfig();
- config.setDataRouterSubscribeEndpoint(new URL("http://" + System.getenv("DMAAP_BC_SERVICE_HOST") + ":" + System.getenv("DMAAP_BC_SERVICE_PORT") + "/webapi/dr_subs"));
- dataRouterSubscriber.start(config);
+ 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);
Undertow.builder()
.addHttpListener(8081, "0.0.0.0")
--- /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.config;\r
+\r
+import java.util.Arrays;\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
+import org.onap.dcaegen2.services.pmmapper.utils.RequiredFieldDeserializer;\r
+import com.google.gson.GsonBuilder;\r
+import lombok.extern.slf4j.Slf4j;\r
+\r
+/**\r
+ * Handles the retrieval of the component spec-based PM-Mapper Configuration\r
+ * from DCAE.\r
+ */\r
+@Slf4j\r
+public class ConfigHandler {\r
+ private RequestSender sender;\r
+\r
+ /**\r
+ * Creates a ConfigHandler.\r
+ */\r
+ public ConfigHandler() {\r
+ this(new RequestSender());\r
+ }\r
+\r
+ /**\r
+ * @see ConfigHandler#ConfigHandler()\r
+ * @param sender A RequestSender\r
+ */\r
+ public ConfigHandler(RequestSender sender) {\r
+ this.sender = sender;\r
+ }\r
+\r
+ /**\r
+ * Retrieves PM-Mapper Configuration from DCAE's ConfigBinding Service.\r
+ *
+ * @throws EnvironmentConfigException\r
+ * @throws ConsulServerError\r
+ * @throws CBSConfigException\r
+ * @throws CBSServerError\r
+ * @throws MapperConfigException\r
+ */
+ public MapperConfig getMapperConfig() throws CBSConfigException, ConsulServerError, EnvironmentConfigException,\r
+ CBSServerError, MapperConfigException {\r
+ CBSConfig cbsConfig = convertCBSConfigToObject(getCBSConfigFromConsul());\r
+ String cbsSocketAddress = cbsConfig.getServiceAddress() + ":" + cbsConfig.getServicePort();\r
+ String requestURL = "http://" + cbsSocketAddress + "/service_component/" + cbsConfig.getServiceName();\r
+ String mapperConfigJson = "";\r
+ log.debug("Fetching mapper configuration from CBS: " + requestURL);\r
+ try {\r
+ mapperConfigJson = sender.send(requestURL);\r
+ } catch (Exception exception) {\r
+ throw new CBSServerError("Error connecting to Configbinding Service: ", exception);\r
+ }\r
+\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
+ log.debug(consulURL);\r
+ try {\r
+ cbsParams = sender.send(consulURL);\r
+ } catch (Exception exception) {\r
+ throw new ConsulServerError("Error connecting to Consul: ", exception);\r
+ }\r
+\r
+ log.debug("cbsConfig: " + cbsParams);\r
+ return cbsParams;\r
+ }\r
+\r
+ private MapperConfig convertMapperConfigToObject(String mapperConfigJson) throws MapperConfigException {\r
+ log.debug("mapperConfigJson:" + mapperConfigJson);\r
+ MapperConfig mapperConfig;\r
+ try {\r
+ mapperConfig = new GsonBuilder()\r
+ .registerTypeAdapter(MapperConfig.class, new RequiredFieldDeserializer<MapperConfig>())\r
+ .create()\r
+ .fromJson(mapperConfigJson, MapperConfig.class);\r
+ } catch (Exception exception) {\r
+ throw new MapperConfigException("Error parsing mapper configuration: " + mapperConfigJson, exception);\r
+ }\r
+\r
+ log.debug("\n" + mapperConfig.toString());\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
+ log.debug("\n\nReceived 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 io.undertow.util.HeaderValues;
import lombok.Data;
import lombok.NonNull;
-import org.onap.dcaegen2.services.pmmapper.config.BusControllerConfig;
+
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.Event;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
--- /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 CBSConfigException extends Exception {\r
+ public CBSConfigException(String message, Throwable cause) {\r
+ super(message, cause);\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.services.pmmapper.exceptions;\r
+\r
+public class CBSServerError extends Exception {\r
+ public CBSServerError(String message, Throwable cause) {\r
+ super(message, cause);\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.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
+/*-\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 EnvironmentConfigException extends Exception {\r
+ public EnvironmentConfigException(String message) {\r
+ super(message);\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.services.pmmapper.exceptions;\r
+\r
+public class MapperConfigException extends Exception {\r
+ public MapperConfigException(String message, Throwable cause) {\r
+ super(message, cause);\r
+ }\r
+}\r
* SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-package org.onap.dcaegen2.services.pmmapper.config;
+package org.onap.dcaegen2.services.pmmapper.model;
import lombok.Data;
--- /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
--- /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 java.util.Optional;\r
+\r
+import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;\r
+\r
+public class EnvironmentConfig {\r
+\r
+ private static Integer consulPort = 8500;\r
+\r
+ public static String getConsulHost() throws EnvironmentConfigException {\r
+ return Optional.ofNullable(System.getProperty("CONSUL_HOST"))\r
+ .orElseThrow(() -> new EnvironmentConfigException(\r
+ "$CONSUL_HOST environment variable must be defined prior to pm-mapper initialization"));\r
+ }\r
+\r
+ public static Integer getConsultPort() throws EnvironmentConfigException {\r
+ Integer port = consulPort;\r
+ try {\r
+ port = Optional.ofNullable(System.getProperty("CONSUL_PORT"))\r
+ .map(Integer::valueOf)\r
+ .orElse(consulPort);\r
+ } catch (NumberFormatException e) {\r
+ throw new EnvironmentConfigException("CONSUL_PORT 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
--- /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
+import com.google.gson.annotations.SerializedName;\r
+import lombok.Data;\r
+import lombok.NoArgsConstructor;\r
+\r
+@Data\r
+@NoArgsConstructor\r
+public class MapperConfig {\r
+\r
+ @GSONRequired\r
+ @SerializedName("streams_subscribes.pm_mapper_handle_out.message_router_topic")\r
+ private String messageRouterTopicName;\r
+
+ BusControllerConfig busControllerConfig;\r
+\r
+}
\ No newline at end of file
--- /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.utils;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.InputStream;\r
+import java.io.InputStreamReader;\r
+import java.net.HttpURLConnection;\r
+import java.net.URL;\r
+import java.util.stream.Collectors;\r
+import lombok.extern.slf4j.Slf4j;\r
+\r
+@Slf4j\r
+public class RequestSender {\r
+ private static final int MAX_RETRIES = 5;\r
+ private static final int RETRY_INTERVAL = 1000;\r
+ public static final String SERVER_ERROR_MESSAGE = "Error on Server";\r
+ public static final int ERROR_START_RANGE = 300;\r
+\r
+ /**\r
+ * Sends an Http GET request to a given endpoint.\r
+ *\r
+ * @return http response body\r
+ * @throws Exception\r
+ * @throws InterruptedException\r
+ */\r
+ public String send(final String url) throws Exception {\r
+ log.debug("RequestSender::send: " + url);\r
+ String result = "";\r
+ for (int i = 1; i <= MAX_RETRIES; i++) {\r
+ URL obj = new URL(url);\r
+ HttpURLConnection connection = (HttpURLConnection) obj.openConnection();\r
+ try (InputStream is = connection.getInputStream();\r
+ BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {\r
+ result = reader.lines()\r
+ .collect(Collectors.joining("\n"));\r
+ int responseCode = connection.getResponseCode();\r
+ if (!(isWithinErrorRange(responseCode))) {\r
+ break;\r
+ }\r
+\r
+ } catch (Exception e) {
+ if (retryLimitReached(i)) {\r
+ throw new Exception(SERVER_ERROR_MESSAGE + ": " + connection.getResponseMessage(), e);\r
+ }\r
+ }\r
+\r
+ Thread.sleep(RETRY_INTERVAL);\r
+ }\r
+ return result;\r
+ }\r
+\r
+ private boolean retryLimitReached(final int retryCount) {\r
+ return retryCount >= MAX_RETRIES;\r
+ }\r
+\r
+ private boolean isWithinErrorRange(final int responseCode) {\r
+ return responseCode >= ERROR_START_RANGE;\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
+\r
+import static org.junit.jupiter.api.Assertions.assertThrows;\r
+import static org.junit.jupiter.api.Assertions.*;\r
+import static org.mockito.Mockito.when;\r
+\r
+import java.io.BufferedReader;\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+import java.net.UnknownHostException;\r
+\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
+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.MapperConfig;\r
+import org.onap.dcaegen2.services.pmmapper.utils.RequestSender;\r
+\r
+import com.google.gson.Gson;\r
+\r
+@ExtendWith(MockitoExtension.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 Gson gson = new Gson();\r
+ @Mock\r
+ private RequestSender sender;\r
+\r
+ @BeforeAll()\r
+ public static void beforeAll() throws IOException {\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
+ }\r
+\r
+ @Test\r
+ public void getMapperConfig_success() throws Exception {\r
+ when(sender.send(anyString())).then(invocation -> {\r
+ String url = (String) invocation.getArguments()[0];\r
+ return url.equals(consulURL) ? cbsConfig : validMapperConfig;\r
+ });\r
+\r
+ MapperConfig actualConfig = getMapperConfig();\r
+ MapperConfig expectedConfig = gson.fromJson(validMapperConfig, MapperConfig.class);\r
+\r
+ assertEquals(expectedConfig, actualConfig);\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
+ assertThrows(CBSServerError.class, this::getMapperConfig);\r
+ }\r
+\r
+ @Test\r
+ public void consul_port_invalid() throws Exception {\r
+ System.setProperty("CONSUL_PORT", "19d93hjuji");\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
+ 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
+ assertThrows(MapperConfigException.class, this::getMapperConfig);\r
+ }\r
+\r
+ private MapperConfig getMapperConfig()\r
+ throws UnknownHostException, EnvironmentConfigException, CBSConfigException, Exception {\r
+ return new ConfigHandler(sender).getMapperConfig();\r
+ }\r
+\r
+ private static String getFileContents(String fileName) throws IOException {\r
+ ClassLoader classLoader = ConfigHandlerTests.class.getClassLoader();\r
+ String fileAsString = "";\r
+ try (BufferedReader reader = new BufferedReader(\r
+ new InputStreamReader(classLoader.getResourceAsStream(fileName)))) {\r
+ String line;\r
+ while ((line = reader.readLine()) != null) {\r
+ fileAsString += line;\r
+ }\r
+ }\r
+ return fileAsString;\r
+ }\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.util;\r
+\r
+import static org.junit.jupiter.api.Assertions.assertThrows;\r
+import static org.mockserver.integration.ClientAndServer.startClientAndServer;\r
+import static org.mockserver.model.HttpRequest.request;\r
+import static org.mockserver.model.HttpResponse.response;\r
+\r
+import java.io.IOException;\r
+import java.net.HttpURLConnection;\r
+import java.net.URL;\r
+import java.net.UnknownHostException;\r
+\r
+import org.junit.AfterClass;\r
+import org.junit.BeforeClass;\r
+import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.mockito.Matchers;\r
+import org.mockserver.client.server.MockServerClient;\r
+import org.mockserver.integration.ClientAndServer;\r
+import org.mockserver.model.HttpStatusCode;\r
+import org.mockserver.verify.VerificationTimes;\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
+@RunWith(PowerMockRunner.class)\r
+@PrepareForTest(RequestSender.class)\r
+\r
+public class RequestSenderTests {\r
+ private static ClientAndServer mockServer;\r
+ private MockServerClient client = mockClient();\r
+\r
+ @BeforeClass\r
+ public static void setup() {\r
+ mockServer = startClientAndServer(1080);\r
+ }\r
+\r
+ @AfterClass\r
+ public static void teardown() {\r
+ mockServer.stop();\r
+ }\r
+\r
+ @BeforeClass\r
+ public static void setEnvironmentVariable() {\r
+ System.setProperty("CONSUL_HOST", "my_consult_host");\r
+ System.setProperty("CONFIG_BINDING_SERVICE", "config-binding-service");\r
+ System.setProperty("HOSTNAME", "hostname");\r
+ }\r
+\r
+ @Test\r
+ public void send_success() throws Exception {\r
+\r
+ client.when(request())\r
+ .respond(response().withStatusCode(HttpStatusCode.OK_200.code()));\r
+\r
+ new RequestSender().send("http://127.0.0.1:1080/once");\r
+\r
+ client.verify(request(), VerificationTimes.exactly(1));\r
+ client.clear(request());\r
+ }\r
+\r
+ @Test\r
+ public void host_unavailable_retry_mechanism() throws Exception {\r
+ PowerMockito.mockStatic(Thread.class);\r
+\r
+ client.when(request())\r
+ .respond(response().withStatusCode(HttpStatusCode.SERVICE_UNAVAILABLE_503.code()));\r
+\r
+ assertThrows(Exception.class, () -> {\r
+ new RequestSender().send("http://127.0.0.1:1080/anypath");\r
+ });\r
+\r
+ client.verify(request(), VerificationTimes.exactly(5));\r
+ client.clear(request());\r
+ }\r
+\r
+ @Test\r
+ public void host_unknown() throws IOException {\r
+ PowerMockito.mockStatic(Thread.class);\r
+ URL url = PowerMockito.mock(URL.class);\r
+ PowerMockito.when(url.openConnection())\r
+ .thenThrow(UnknownHostException.class);\r
+\r
+ assertThrows(Exception.class, () -> {\r
+ new RequestSender().send("http://127.0.0.1:1080/host-is-unknown");\r
+ });\r
+\r
+ client.verify(request(), VerificationTimes.exactly(5));\r
+ client.clear(request());\r
+ }\r
+\r
+ private MockServerClient mockClient() {\r
+ return new MockServerClient("127.0.0.1", 1080);\r
+ }\r
+\r
+}\r
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
-import org.onap.dcaegen2.services.pmmapper.config.BusControllerConfig;
import org.onap.dcaegen2.services.pmmapper.exceptions.TooManyTriesException;
+import org.onap.dcaegen2.services.pmmapper.model.BusControllerConfig;
import org.onap.dcaegen2.services.pmmapper.model.Event;
import org.onap.dcaegen2.services.pmmapper.model.EventMetadata;
import org.powermock.api.mockito.PowerMockito;
--- /dev/null
+{\r
+ "_comment": "This mapper config is missing the messagerouter feed name",\r
+ "pm-mapper-filter": {\r
+ "filters": "{[]}"\r
+ },\r
+ "3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",\r
+ "streams_subscribes": {},\r
+ "streams_publishes": {\r
+ "pm_mapper_handle_out": {\r
+ "type": "message_router",\r
+ "aaf_password": null,\r
+ "dmaap_info": {\r
+ "topic_url": "https://we-are-message-router.us:3905/events/some-topic",\r
+ "client_role": null,\r
+ "location": null,\r
+ "client_id": null\r
+ },\r
+ "aaf_username": null\r
+ }\r
+ },\r
+ "some parameter": "unauthenticated.PM_VES_OUTPUT",\r
+ "some field": "1",\r
+ "services_calls": {}\r
+}
\ No newline at end of file
--- /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
--- /dev/null
+{\r
+ "pm-mapper-filter": "{ \"filters\":[]}",\r
+ "3GPP.schema.file": "{\"3GPP_Schema\":\"./etc/3GPP_relaxed_schema.xsd\"}",\r
+ "streams_subscribes": {},\r
+ "streams_publishes": {\r
+ "pm_mapper_handle_out": {\r
+ "type": "message_router",\r
+ "aaf_password": null,\r
+ "dmaap_info": {\r
+ "topic_url": "https://we-are-message-router.us:3905/events/some-topic",\r
+ "client_role": null,\r
+ "location": null,\r
+ "client_id": null\r
+ },\r
+ "aaf_username": null\r
+ }\r
+ },\r
+ "streams_subscribes.pm_mapper_handle_out.message_router_topic": "unauthenticated.PM_VES_OUTPUT",\r
+ "services_calls": {}\r
+}
\ No newline at end of file