summaryrefslogtreecommitdiffstats
path: root/pomba
diff options
context:
space:
mode:
Diffstat (limited to 'pomba')
-rw-r--r--pomba/network-discovery/pom.xml59
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/CallbackConfiguration.java74
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/JerseyConfiguration.java49
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/OpenstackConfiguration.java11
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/WebConfiguration.java44
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/OSAuthentication.java91
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringService.java2
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringServiceImpl.java245
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestService.java15
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestServiceImpl.java63
-rw-r--r--pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/util/TransformationUtil.java2
-rw-r--r--pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/NetworkDiscoveryTest.java148
-rw-r--r--pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/util/TransformationUtilTest.java1
13 files changed, 219 insertions, 585 deletions
diff --git a/pomba/network-discovery/pom.xml b/pomba/network-discovery/pom.xml
index dea7353..a428a59 100644
--- a/pomba/network-discovery/pom.xml
+++ b/pomba/network-discovery/pom.xml
@@ -66,30 +66,23 @@ limitations under the License.
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
-
- <!-- Springframework dependencies -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
+
+ <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- <exclusions>
- <exclusion>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jersey</artifactId>
+
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-jersey</artifactId>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-tomcat</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
+
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
@@ -111,32 +104,20 @@ limitations under the License.
</exclusion>
</exclusions>
</dependency>
+
<!-- swagger dependencies -->
- <dependency>
- <groupId>io.swagger</groupId>
- <artifactId>swagger-annotations</artifactId>
- <version>1.5.9</version>
- </dependency>
+ <dependency>
+ <groupId>io.swagger</groupId>
+ <artifactId>swagger-jersey2-jaxrs</artifactId>
+ <version>1.5.21</version>
+ </dependency>
+
<!-- application dependencies -->
<dependency>
<groupId>org.onap.sdnc.apps.pomba</groupId>
<artifactId>network-discovery-api</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
-
- </dependency>
- <dependency>
- <groupId>org.glassfish.jersey.core</groupId>
- <artifactId>jersey-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.onap.aai</groupId>
- <artifactId>rest-client</artifactId>
- <version>1.2.1</version>
- </dependency>
<!-- Test dependencies -->
<dependency>
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/CallbackConfiguration.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/CallbackConfiguration.java
deleted file mode 100644
index 1d2bdab..0000000
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/CallbackConfiguration.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * ============LICENSE_START===================================================
- * Copyright (c) 2018 Amdocs
- * ============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=====================================================
- */
-package org.onap.sdnc.apps.pomba.networkdiscovery;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import org.glassfish.jersey.client.ClientConfig;
-import org.glassfish.jersey.client.ClientProperties;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Bean;
-import org.springframework.stereotype.Component;
-
-@Component
-public class CallbackConfiguration {
- /** Use same object mapper as embedded tomcat server */
- @Autowired
- private ObjectMapper objectMapper;
-
- @Value("${callback.keyStorePath:}")
- private String keyStorePath;
-
- @Value("${callback.keyStorePassword:}")
- private String keyStorePassword;
-
- @Value("${callback.connectionTimeout:5000}")
- private int connectionTimeout;
-
- @Value("${callback.readTimeout:60000}")
- private int readTimeout;
-
- @Value("${callback.username:}")
- private String basicAuthUsername;
-
- @Value("${callback.password:}")
- private String basicAuthPassword;
-
- @Bean(name="callbackClient")
- public Client getClient() {
- ClientConfig configuration = new ClientConfig()
- .property(ClientProperties.CONNECT_TIMEOUT, this.connectionTimeout)
- .property(ClientProperties.READ_TIMEOUT, this.readTimeout)
- .register(new JacksonJaxbJsonProvider(objectMapper, null));
-
- // TODO set up SSL if configured
-// if (useSsl) {
-// setupSecureSocketLayerClientConfig(clientConfig);
-// }
- // Finally, create and initialize our client...
- Client client = ClientBuilder.newClient(configuration);
-
- // ...and return it to the caller.
- return client;
- }
-
-
-}
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/JerseyConfiguration.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/JerseyConfiguration.java
index b4488db..e073e34 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/JerseyConfiguration.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/JerseyConfiguration.java
@@ -19,6 +19,7 @@ package org.onap.sdnc.apps.pomba.networkdiscovery;
import java.util.logging.Logger;
+import javax.annotation.PostConstruct;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
@@ -27,34 +28,24 @@ import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.logging.LoggingFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
+import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.MapperFeature;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
+import io.swagger.jaxrs.config.BeanConfig;
+import io.swagger.jaxrs.listing.ApiListingResource;
+import io.swagger.jaxrs.listing.SwaggerSerializers;
@Component
@ApplicationPath("/")
public class JerseyConfiguration extends ResourceConfig {
- private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName());
-
- @Bean
- @Primary
- public ObjectMapper objectMapper() {
- ObjectMapper objectMapper = new ObjectMapper();
- objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
- objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
- objectMapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
- objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
- return objectMapper;
- }
+
+ public static final String SERVICE_NAME = "network-discovery";
+ private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName());
+
@Autowired
public JerseyConfiguration() {
register(RestServiceImpl.class);
@@ -66,4 +57,26 @@ public class JerseyConfiguration extends ResourceConfig {
public Client jerseyClient() {
return ClientBuilder.newClient(new ClientConfig());
}
+
+ @PostConstruct
+ public void init() {
+ // Register components where DI is needed
+ this.configureSwagger();
+ }
+
+ private void configureSwagger() {
+ // Available at localhost:port/swagger.json
+ this.register(ApiListingResource.class);
+ this.register(SwaggerSerializers.class);
+
+ BeanConfig config = new BeanConfig();
+ config.setTitle("Network Discovery Swagger");
+ config.setVersion("v1");
+ config.setSchemes(new String[] { "https", "http" });
+ config.setBasePath("/" + SERVICE_NAME);
+ config.setResourcePackage(RestService.class.getPackage().getName());
+ config.setPrettyPrint(true);
+ config.setScan(true);
+ }
+
}
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/OpenstackConfiguration.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/OpenstackConfiguration.java
index ee18397..230a3f2 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/OpenstackConfiguration.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/OpenstackConfiguration.java
@@ -21,8 +21,10 @@ import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+
import org.eclipse.jetty.util.security.Password;
-import org.onap.aai.restclient.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
@@ -59,11 +61,8 @@ public class OpenstackConfiguration {
private int readTimeout;
@Bean(name = "openstackClient")
- public RestClient restClient() {
- return new RestClient().validateServerHostname(false)
- .validateServerCertChain(false)
- .connectTimeoutMs(this.connectionTimeout)
- .readTimeoutMs(this.readTimeout);
+ public Client restClient() {
+ return ClientBuilder.newClient();
}
@Bean(name = "openstackIdentityUrl")
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/WebConfiguration.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/WebConfiguration.java
deleted file mode 100644
index 7a7bbd9..0000000
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/WebConfiguration.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * ============LICENSE_START===================================================
- * Copyright (c) 2018 Amdocs
- * ============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=====================================================
- */
-package org.onap.sdnc.apps.pomba.networkdiscovery;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
-@Configuration
-public class WebConfiguration {
-
- @Bean
- public WebMvcConfigurerAdapter forwardToIndex() {
- return new WebMvcConfigurerAdapter() {
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/swagger").setViewName(
- "redirect:/swagger/index.html");
- registry.addViewController("/swagger/").setViewName(
- "redirect:/swagger/index.html");
- registry.addViewController("/docs").setViewName(
- "redirect:/docs/html/index.html");
- registry.addViewController("/docs/").setViewName(
- "redirect:/docs/html/index.html");
- }
- };
- }
-} \ No newline at end of file
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/OSAuthentication.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/OSAuthentication.java
index c00bf24..e0a158f 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/OSAuthentication.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/OSAuthentication.java
@@ -17,72 +17,69 @@
*/
package org.onap.sdnc.apps.pomba.networkdiscovery.service;
-import static org.onap.sdnc.apps.pomba.networkdiscovery.ApplicationException.Error.UNAUTHORIZED;
-
import java.io.File;
import java.io.FileInputStream;
-import java.io.IOException;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.Response.Status.Family;
import org.apache.commons.io.IOUtils;
-import org.onap.aai.restclient.client.OperationResult;
-import org.onap.aai.restclient.client.RestClient;
import org.onap.logging.ref.slf4j.ONAPLogAdapter;
import org.onap.sdnc.apps.pomba.networkdiscovery.ApplicationException;
-import org.slf4j.Logger;
-
public class OSAuthentication {
private static final String CONFIG_AUTH_DIR = "config/auth";
private static final String X_SUBJECT_TOKEN = "X-Subject-Token";
- private static final String USER_PATTERN = "%USER%";
- private static final String PASSWORD_PATTERN = "%PASSWORD%";
+ private static final String USER_PATTERN = "%USER%";
+ private static final String PW_PATTERN = "%PASSWORD%";
private OSAuthentication() {
throw new IllegalStateException("Utility class");
}
- public static String getToken(String openstackIdentityUrl, String userId, String password, RestClient openstackClient, ONAPLogAdapter adapter)
- throws IOException, ApplicationException {
-
- MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
-
- String mappingConfigPath = CONFIG_AUTH_DIR + File.separator + "osauth.json";
-
- File file = new File(mappingConfigPath);
- String payload = IOUtils.toString(new FileInputStream(file), "UTF-8");
- payload = payload.replaceAll(USER_PATTERN, userId);
- payload = payload.replaceAll(PASSWORD_PATTERN, password);
-
- OperationResult result = openstackClient.post(openstackIdentityUrl, payload, headers,
- MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE);
-
- Logger log = adapter.unwrap();
-
- if (result.wasSuccessful()) {
- log.info("request at url = {} resulted in http response code: {}",
- openstackIdentityUrl, result.getResultCode());
- } else {
- log.error("request at url = {} resulted in http response code: {}. Failure cause: {}",
- openstackIdentityUrl, result.getResultCode(), result.getFailureCause());
- }
-
-
- String token = result.getHeaders().getFirst(X_SUBJECT_TOKEN);
-
- if (token == null) {
- throw new ApplicationException(UNAUTHORIZED, Status.UNAUTHORIZED);
- }
-
- log.debug("Got token: {}", token);
-
- return token;
- }
+ public static String getToken(String openstackIdentityUrl, String userId, String password, Client openstackClient,
+ ONAPLogAdapter adapter) throws ApplicationException {
+
+ String mappingConfigPath = CONFIG_AUTH_DIR + File.separator + "osauth.json";
+ File file = new File(mappingConfigPath);
+
+ Response result;
+ try {
+ String payload = IOUtils.toString(new FileInputStream(file), "UTF-8");
+ payload = payload.replaceAll(USER_PATTERN, userId);
+ payload = payload.replaceAll(PW_PATTERN, password);
+
+ result = openstackClient.target(openstackIdentityUrl).request()
+ .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
+ .post(Entity.entity(payload, MediaType.APPLICATION_JSON));
+ } catch (Exception e) {
+ // catch the case when the connection times out (e.g., host not available).
+ throw new ApplicationException(ApplicationException.Error.GENERAL_FAILURE, Status.NOT_FOUND,
+ "Openstack API login failed - " + e.getMessage());
+ }
+
+ String jsonResult = result.readEntity(String.class);
+
+ if (result.getStatusInfo().getFamily() != Family.SUCCESSFUL) {
+ throw new ApplicationException(ApplicationException.Error.GENERAL_FAILURE, Status.NOT_FOUND, jsonResult);
+ }
+
+ String token = result.getHeaderString(X_SUBJECT_TOKEN);
+ if (token == null) {
+ throw new ApplicationException(ApplicationException.Error.GENERAL_FAILURE, Status.NOT_FOUND,
+ "Failed to get token from Openstack API response");
+ }
+
+ adapter.unwrap().debug("Got token: {}", token);
+
+ return token;
+ }
}
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringService.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringService.java
index e0f50f6..b4a9ce1 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringService.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringService.java
@@ -28,8 +28,6 @@ public interface SpringService {
String requestId,
String resourceType,
List<String> resourceIds,
- String notificationURL,
- String notificationAuthorization,
ONAPLogAdapter adapter)
throws ApplicationException;
}
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringServiceImpl.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringServiceImpl.java
index f9de2be..5577398 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringServiceImpl.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/SpringServiceImpl.java
@@ -17,37 +17,19 @@
*/
package org.onap.sdnc.apps.pomba.networkdiscovery.service;
-import com.bazaarvoice.jolt.JsonUtils;
-import com.google.common.util.concurrent.ThreadFactoryBuilder;
-
-import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import javax.annotation.PreDestroy;
import javax.ws.rs.client.Client;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.StatusType;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.Response.Status.Family;
-import javax.xml.parsers.ParserConfigurationException;
-import org.onap.aai.restclient.client.OperationResult;
-import org.onap.aai.restclient.client.RestClient;
import org.onap.logging.ref.slf4j.ONAPLogAdapter;
-import org.onap.logging.ref.slf4j.ONAPLogAdapter.RequestBuilder;
-import org.onap.logging.ref.slf4j.ONAPLogConstants;
-import org.onap.logging.ref.slf4j.ONAPLogConstants.InvocationMode;
import org.onap.pomba.common.datatypes.DataQuality;
import org.onap.sdnc.apps.pomba.networkdiscovery.ApplicationException;
import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
@@ -63,14 +45,9 @@ import org.springframework.stereotype.Service;
public class SpringServiceImpl implements SpringService {
private static final String OPENSTACK_HEADER_TOKEN = "X-Auth-Token";
private static final String OPENSTACK_HEADER_API_VERSION = "X-OpenStack-Nova-API-Version";
- private static final int DEFAULT_WORKER_THREADS = 3;
-
- private ExecutorService executor = Executors.newFixedThreadPool(
- Integer.getInteger("discovery.threads", DEFAULT_WORKER_THREADS),
- new ThreadFactoryBuilder().setNameFormat("discovery-worker-%d").build());
@Autowired
- private RestClient openstackClient;
+ private Client openstackClient;
@Autowired
private String openstackIdentityUrl;
@@ -85,194 +62,72 @@ public class SpringServiceImpl implements SpringService {
private String openstackApiMicroversion;
@javax.annotation.Resource
- private Client callbackClient;
-
- @javax.annotation.Resource
private Map<String, String> openstackTypeURLs;
- public SpringServiceImpl() throws ParserConfigurationException {
- }
-
@Override
public NetworkDiscoveryResponse findbyResourceIdAndType(String transactionId, String requestId, String resourceType,
- List<String> resourceIds, String notificationURL, String notificationAuthorization, ONAPLogAdapter adapter)
- throws ApplicationException {
+ List<String> resourceIds, ONAPLogAdapter adapter) throws ApplicationException {
NetworkDiscoveryResponse response = new NetworkDiscoveryResponse();
response.setRequestId(requestId);
- String openstackURL = this.openstackTypeURLs.get(resourceType);
// check if resourceType is supported
+ String openstackURL = this.openstackTypeURLs.get(resourceType);
if (openstackURL == null) {
- // don't know what to do with this - return empty response
- response.setCode(Status.NO_CONTENT.getStatusCode());
- response.setMessage("Unsupported resourceType " + resourceType);
- response.setAckFinalIndicator(true);
- return response;
+ throw new ApplicationException(ApplicationException.Error.GENERAL_FAILURE, Status.BAD_REQUEST,
+ "Unsupported resourceType " + resourceType);
}
-
- // schedule discovery of specified resources
- Runnable task = new ResourceTask(transactionId, requestId, resourceType, resourceIds, notificationURL,
- notificationAuthorization, openstackURL, adapter);
- this.executor.submit(task);
-
- response.setCode(Status.ACCEPTED.getStatusCode());
- response.setMessage(Status.ACCEPTED.getReasonPhrase());
- response.setAckFinalIndicator(false);
- return response;
- }
-
- @PreDestroy
- public void shutdown() {
- this.executor.shutdown();
- }
-
- private void sendNotification(String url, String transactionId, String authorization, Object notification,
- ONAPLogAdapter adapter) {
-
- Invocation.Builder request = this.callbackClient.target(url).request().accept(MediaType.TEXT_PLAIN_TYPE);
-
- if (authorization != null) {
- request.header(HttpHeaders.AUTHORIZATION, authorization);
- request.header(ONAPLogConstants.Headers.REQUEST_ID, transactionId);
- }
- Logger log = adapter.unwrap();
- adapter.invoke(new RequestBuilderWrapper(request), InvocationMode.SYNCHRONOUS);
- try {
- log.info("Posting notfication to url = {} , payload: {}", url,
- JsonUtils.toJsonString(Entity.json(notification).getEntity()));
-
- Response result = request.post(Entity.json(notification));
-
- StatusType status = result.getStatusInfo();
-
- if (status.getFamily().equals(Family.SUCCESSFUL)) {
- log.info("request at url = {} resulted in http status code {}",
- url, status.getStatusCode());
- } else {
- log.error("request at url = {} resulted in http status code {}, reason: {}",
- url, status.getStatusCode(), status.getReasonPhrase());
- }
-
-
- } catch (Exception x) {
- log.error("Error during {} operation to endpoint at url = {} with error = {}", "POST", url,
- x.getLocalizedMessage());
- }
- }
-
- private class ResourceTask implements Runnable {
- private final String transactionId;
- private final String requestId;
- private final String resourceType;
- private final List<String> resourceIds;
- private final String notificationURL;
- private final String notificationAuthorization;
- private final String resourceURL;
- private final ONAPLogAdapter adapter;
-
- public ResourceTask(String transactionId, String requestId, String resourceType, List<String> resourceIds,
- String notificationURL, String notificationAuthorization, String resourceURL, ONAPLogAdapter adapter) {
- this.transactionId = transactionId;
- this.requestId = requestId;
- this.resourceType = resourceType;
- this.resourceIds = resourceIds;
- this.notificationURL = notificationURL;
- this.notificationAuthorization = notificationAuthorization;
- this.resourceURL = resourceURL;
- this.adapter = adapter;
- }
-
- @Override
- public void run() {
+ String token = OSAuthentication.getToken(openstackIdentityUrl, openstackIdentityUser, openstackIdentityPassword,
+ openstackClient, adapter);
+
+ NetworkDiscoveryNotification discoveryResponse = new NetworkDiscoveryNotification();
+ discoveryResponse.setRequestId(requestId);
+
+ List<Resource> resources = new ArrayList<>();
+ MessageFormat format = new MessageFormat(openstackURL);
+
+ for (String resourceId : resourceIds) {
+ String url = format.format(new Object[] { resourceId });
+ Resource resource = new Resource();
+ resource.setType(resourceType);
+ resource.setId(resourceId);
+ resources.add(resource);
+
+ Response result;
try {
- runResourceDiscoveryTask();
+ result = openstackClient.target(url).request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
+ .header(OPENSTACK_HEADER_TOKEN, token)
+ .header(OPENSTACK_HEADER_API_VERSION, openstackApiMicroversion).get();
} catch (Exception e) {
- Logger log = adapter.unwrap();
- log.error("Failure in resource task", e);
-
- // Try to send out a notification of the failure:
- NetworkDiscoveryNotification notification = new NetworkDiscoveryNotification();
- notification.setRequestId(this.requestId);
- notification.setCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
- notification.setMessage(e.getMessage());
- notification.setAckFinalIndicator(true);
-
- // call client back with resource details
- sendNotification(this.notificationURL, this.transactionId, this.notificationAuthorization, notification,
- adapter);
+ // in case of time-out, exit the loop and return a failure.
+ throw new ApplicationException(ApplicationException.Error.GENERAL_FAILURE, Status.NOT_FOUND,
+ "Openstack API GET failed - " + e.getMessage());
}
- }
-
- private void runResourceDiscoveryTask() throws IOException, ApplicationException {
-
- String token = OSAuthentication.getToken(openstackIdentityUrl, openstackIdentityUser,
- openstackIdentityPassword, openstackClient, adapter);
-
- NetworkDiscoveryNotification notification = new NetworkDiscoveryNotification();
- notification.setRequestId(this.requestId);
-
- List<Resource> resources = null;
- MessageFormat format = new MessageFormat(this.resourceURL);
- MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
- headers.add(OPENSTACK_HEADER_TOKEN, token);
- headers.add(OPENSTACK_HEADER_API_VERSION, openstackApiMicroversion);
-
- for (String resourceId : this.resourceIds) {
- String url = format.format(new Object[] { resourceId });
- OperationResult result = SpringServiceImpl.this.openstackClient.get(url, headers,
- MediaType.APPLICATION_JSON_TYPE);
-
- Resource resource = new Resource();
- resource.setType(this.resourceType);
- resource.setId(resourceId);
- if (resources == null) {
- resources = new ArrayList<>();
- notification.setResources(resources);
- }
- resources.add(resource);
-
- Logger log = adapter.unwrap();
-
- if (result.wasSuccessful()) {
- log.info("Openstack GET result code: {}", result.getResultCode());
-
- String transformedOutput = TransformationUtil.transform(result.getResult(), this.resourceType);
-
- log.debug("Jolt transformed output: {}", transformedOutput);
-
- resource.setDataQuality(DataQuality.ok());
- List<Attribute> attributeList = TransformationUtil.toAttributeList(transformedOutput);
- resource.setAttributeList(attributeList);
- } else {
- log.error("Openstack GET result code: {}. Failure cause: {}",
- result.getResultCode(), result.getFailureCause());
- resource.setDataQuality(DataQuality.error(result.getFailureCause()));
- }
+
+ String jsonResult = result.readEntity(String.class);
+ Logger log = adapter.unwrap();
+
+ log.info("Openstack GET result for resourceID {}: {}", resourceId, jsonResult);
+
+ if (result.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
+ String transformedOutput = TransformationUtil.transform(jsonResult, resourceType);
+
+ log.debug("Jolt transformed output: {}", transformedOutput);
+
+ resource.setDataQuality(DataQuality.ok());
+ List<Attribute> attributeList = TransformationUtil.toAttributeList(transformedOutput);
+ resource.setAttributeList(attributeList);
+ } else {
+ resource.setDataQuality(DataQuality.error(jsonResult));
}
- notification.setCode(Status.OK.getStatusCode());
- notification.setMessage(Status.OK.getReasonPhrase());
- notification.setAckFinalIndicator(true);
-
- // call client back with resource details
- sendNotification(this.notificationURL, this.transactionId, this.notificationAuthorization, notification,
- adapter);
}
- }
-
- private static class RequestBuilderWrapper implements RequestBuilder<RequestBuilderWrapper> {
- private Invocation.Builder builder;
-
- private RequestBuilderWrapper(Invocation.Builder builder) {
- this.builder = builder;
- }
-
- @Override
- public RequestBuilderWrapper setHeader(String name, String value) {
- this.builder.header(name, value);
- return this;
- }
+ discoveryResponse.setResources(resources);
+ discoveryResponse.setCode(Status.OK.getStatusCode());
+ discoveryResponse.setMessage(Status.OK.getReasonPhrase());
+ discoveryResponse.setAckFinalIndicator(true);
+ return discoveryResponse;
}
+
} \ No newline at end of file
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestService.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestService.java
index 57fbb53..226f325 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestService.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestService.java
@@ -38,7 +38,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.sdnc.apps.pomba.networkdiscovery.ApplicationException;
-import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryResponse;
+import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
@Api(protocols="http", tags= {"resource"})
@@ -46,8 +46,6 @@ import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryRespo
@Produces(MediaType.APPLICATION_JSON)
public interface RestService {
- public static final String SERVICE_NAME = "network-discovery";
-
@GET
@Path("/resource")
@Produces(MediaType.APPLICATION_JSON)
@@ -55,14 +53,13 @@ public interface RestService {
@ApiOperation(
value = "Get Network Information",
notes = "Retrieve information from primary data sources",
- response = NetworkDiscoveryResponse.class,
authorizations = @Authorization("basicAuth")
)
@ApiResponses(
value = {
- @ApiResponse(code = 200, message = "Request has completed and no more information is forthcoming."),
- @ApiResponse(code = 202, message = "Request has been accepted and more information will be posted to notificationURL."),
+ @ApiResponse(code = 200, message = "Request has completed.", response = NetworkDiscoveryNotification.class),
@ApiResponse(code = 400, message = "Missing mandatory field in the request or HTTP header."),
+ @ApiResponse(code = 401, message = "Missing basicAuth header."),
@ApiResponse(code = 404, message = "Requested resource was not found."),
@ApiResponse(code = 500, message = "Request failed due to internal error")
})
@@ -94,10 +91,6 @@ public interface RestService {
@QueryParam("resourceId")
@ApiParam(required=true)
- List<String> resourceIds,
-
- @QueryParam("notificationURL")
- @ApiParam(required=true)
- String notificationURL) throws ApplicationException;
+ List<String> resourceIds) throws ApplicationException;
} \ No newline at end of file
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestServiceImpl.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestServiceImpl.java
index 0677dcd..adb5df0 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestServiceImpl.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/rs/RestServiceImpl.java
@@ -34,6 +34,7 @@ import org.onap.logging.ref.slf4j.ONAPLogAdapter;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
import org.onap.sdnc.apps.pomba.networkdiscovery.ApplicationException;
+import org.onap.sdnc.apps.pomba.networkdiscovery.JerseyConfiguration;
import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryResponse;
import org.onap.sdnc.apps.pomba.networkdiscovery.service.SpringService;
import org.slf4j.Logger;
@@ -60,54 +61,34 @@ public class RestServiceImpl implements RestService {
String transactionId,
String requestId,
String resourceType,
- List<String> resourceIds,
- String notificationURL) throws ApplicationException {
+ List<String> resourceIds) throws ApplicationException {
ONAPLogAdapter adapter = new ONAPLogAdapter(log);
try {
- adapter.getServiceDescriptor().setServiceName(SERVICE_NAME);
+ adapter.getServiceDescriptor().setServiceName(JerseyConfiguration.SERVICE_NAME);
adapter.entering(request);
- if (version == null) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "version");
- }
-
- if (authorization == null || !this.basicAuthHeader.equals(authorization)) {
- throw new ApplicationException(UNAUTHORIZED, Status.UNAUTHORIZED);
- }
- if ((fromAppId == null) || fromAppId.trim().isEmpty()) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, ONAPLogConstants.Headers.PARTNER_NAME);
- }
- if (requestId == null || requestId.isEmpty()) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "requestId");
- }
- if (notificationURL == null) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "notificationURL");
- }
- if (resourceType == null || resourceType.isEmpty()) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "resourceType");
- }
- if (resourceIds == null || resourceIds.isEmpty()) {
- throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "resourceIds");
- }
+ validateInput(version, authorization, fromAppId, requestId, resourceType, resourceIds);
if (transactionId == null || transactionId.isEmpty()) {
transactionId = UUID.randomUUID().toString();
log.debug("transactionId is missing; using newly generated value: {}", transactionId);
}
- // just reuse received Authorization header in callback
NetworkDiscoveryResponse response = this.service.findbyResourceIdAndType(transactionId,
- requestId, resourceType, resourceIds, notificationURL, authorization, adapter);
+ requestId, resourceType, resourceIds, adapter);
adapter.getResponseDescriptor().setResponseStatus(ResponseStatus.COMPLETED);
- return Response.ok(response).build();
+ Response returnedResponse = Response.ok(response).build();
+ adapter.unwrap().info("request at url = {} resulted in http status {} and response: {}", request.getServletPath(),
+ returnedResponse.getStatus(), returnedResponse.getEntity());
+ return returnedResponse;
} catch (ApplicationException x) {
adapter.getResponseDescriptor()
.setResponseCode(x.getResponseCode())
.setResponseStatus(ResponseStatus.ERROR);
- log.error(x.getMessage(), x);
+ log.error(x.getMessage());
ResponseBuilder builder = Response.status(x.getHttpStatus()).entity(x.getMessage());
if (authorization == null) {
builder.header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"network-discovery\"");
@@ -124,4 +105,28 @@ public class RestServiceImpl implements RestService {
adapter.exiting();
}
}
+
+ private void validateInput(String version, String authorization, String fromAppId, String requestId,
+ String resourceType, List<String> resourceIds) throws ApplicationException {
+ if (version == null) {
+ throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "version");
+ }
+
+ if (authorization == null || !this.basicAuthHeader.equals(authorization)) {
+ throw new ApplicationException(UNAUTHORIZED, Status.UNAUTHORIZED);
+ }
+ if ((fromAppId == null) || fromAppId.trim().isEmpty()) {
+ throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, ONAPLogConstants.Headers.PARTNER_NAME);
+ }
+ if (requestId == null || requestId.isEmpty()) {
+ throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "requestId");
+ }
+
+ if (resourceType == null || resourceType.isEmpty()) {
+ throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "resourceType");
+ }
+ if (resourceIds == null || resourceIds.isEmpty()) {
+ throw new ApplicationException(MISSING_PARAM, Status.BAD_REQUEST, "resourceIds");
+ }
+ }
}
diff --git a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/util/TransformationUtil.java b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/util/TransformationUtil.java
index dc17848..0984f66 100644
--- a/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/util/TransformationUtil.java
+++ b/pomba/network-discovery/src/main/java/org/onap/sdnc/apps/pomba/networkdiscovery/service/util/TransformationUtil.java
@@ -35,7 +35,7 @@ public class TransformationUtil {
private static final String CONFIG_JOLT = "config/jolt";
private static final String EMPTY_STRING = "";
- public TransformationUtil() {
+ private TransformationUtil() {
throw new IllegalStateException("Utility class");
}
diff --git a/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/NetworkDiscoveryTest.java b/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/NetworkDiscoveryTest.java
index 18a0a04..31b1abe 100644
--- a/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/NetworkDiscoveryTest.java
+++ b/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/NetworkDiscoveryTest.java
@@ -19,7 +19,6 @@
package org.onap.sdnc.apps.pomba.networkdiscovery.unittest.service;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
-import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.okJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
@@ -29,14 +28,8 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.bazaarvoice.jolt.JsonUtils;
-import com.fasterxml.jackson.databind.AnnotationIntrospector;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.type.TypeFactory;
-import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
-import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
-import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import java.net.URISyntaxException;
import java.text.MessageFormat;
@@ -62,7 +55,6 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.pomba.common.datatypes.DataQuality;
import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Attribute;
import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryNotification;
-import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.NetworkDiscoveryResponse;
import org.onap.sdnc.apps.pomba.networkdiscovery.datamodel.Resource;
import org.onap.sdnc.apps.pomba.networkdiscovery.service.rs.RestService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -90,7 +82,6 @@ public class NetworkDiscoveryTest {
private static final String APP = "junit";
private static final String RESOURCE_TYPE_VSERVER = "vserver";
- private static final String CALLBACK_PATH = "/callback";
private static final String AUTH = "Basic " + Base64.getEncoder().encodeToString((
"admin:" + Password.deobfuscate("OBF:1u2a1toa1w8v1tok1u30")).getBytes());
@@ -131,7 +122,7 @@ public class NetworkDiscoveryTest {
// no Authorization header
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, null, APP, this.transactionId,
- this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
// should get WWW-Authenticate header in response
assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
@@ -143,7 +134,7 @@ public class NetworkDiscoveryTest {
// bad Authorization header
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP,
- this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
// should not get WWW-Authenticate header in response
assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
@@ -155,7 +146,7 @@ public class NetworkDiscoveryTest {
String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, null, authorization, APP,
- this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
// should get WWW-Authenticate header in response
assertTrue(((String) response.getEntity()).contains("version"));
@@ -166,7 +157,7 @@ public class NetworkDiscoveryTest {
// no X-FromAppId header
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, null, this.transactionId,
- this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertTrue(((String) response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
}
@@ -175,27 +166,18 @@ public class NetworkDiscoveryTest {
public void testVerifyRequestId() throws Exception {
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
- null, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ null, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertTrue(((String) response.getEntity()).contains("requestId"));
}
@Test
- public void testVerifyNotificationUrl() throws Exception {
- List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
- Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
- this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, null);
- assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String) response.getEntity()).contains("notificationURL"));
- }
-
- @Test
public void testVerifyResourceIds() throws Exception {
// no resourceIds list
{
List<String> resourceIds = null;
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
- this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertTrue(((String) response.getEntity()).contains("resourceIds"));
}
@@ -204,7 +186,7 @@ public class NetworkDiscoveryTest {
{
List<String> resourceIds = new ArrayList<>();
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
- this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertTrue(((String) response.getEntity()).contains("resourceIds"));
}
@@ -215,7 +197,7 @@ public class NetworkDiscoveryTest {
// no resource type
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
- this.requestId, null, resourceIds, getCallbackUrl());
+ this.requestId, null, resourceIds);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertTrue(((String) response.getEntity()).contains("resourceType"));
}
@@ -225,7 +207,7 @@ public class NetworkDiscoveryTest {
// no request
List<String> resourceIds = Arrays.asList(UUID.randomUUID().toString());
Response response = this.service.findbyResourceIdAndType(null, V1, AUTH, APP, this.transactionId,
- this.requestId, null, resourceIds, getCallbackUrl());
+ this.requestId, null, resourceIds);
assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}
@@ -245,28 +227,12 @@ public class NetworkDiscoveryTest {
this.openstackRule.stubFor(get(resourcePath).willReturn(okJson(openstackApiResponse)));
this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
-
- this.callbackRule.stubFor(post(CALLBACK_PATH).willReturn(ok("Acknowledged")));
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
- RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId), getCallbackUrl());
+ RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
- assertEquals(requestId, entity.getRequestId());
- assertEquals(Status.ACCEPTED.getStatusCode(), entity.getCode().intValue());
- assertEquals(Boolean.FALSE, entity.getAckFinalIndicator());
-
- List<ServeEvent> events = waitForRequests(this.callbackRule, 1, 10);
- LoggedRequest notificationRequest = events.get(0).getRequest();
- assertEquals(AUTH, notificationRequest.getHeader(HttpHeaders.AUTHORIZATION));
- String notificationJson = notificationRequest.getBodyAsString();
-
- ObjectMapper mapper = new ObjectMapper();
- AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
- mapper.setAnnotationIntrospector(introspector);
- NetworkDiscoveryNotification notification = mapper.readValue(notificationJson,
- NetworkDiscoveryNotification.class);
+ NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
assertEquals(requestId, notification.getRequestId());
assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
@@ -285,7 +251,7 @@ public class NetworkDiscoveryTest {
}
@Test
- public void testDiscoverVserverFailure() throws Exception {
+ public void testDiscoverVserverFailureNotFound() throws Exception {
String vserverId = UUID.randomUUID().toString();
String resourcePath = MessageFormat.format("/v2.1/servers/{0}",
@@ -296,29 +262,12 @@ public class NetworkDiscoveryTest {
this.openstackRule.stubFor(get(resourcePath).willReturn(WireMock.notFound()));
this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}").withHeader("X-Subject-Token", "tokenId")));
-
- this.callbackRule.stubFor(post(CALLBACK_PATH).willReturn(ok("Acknowledged")));
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
- RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId), getCallbackUrl());
+ RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
- assertEquals(requestId, entity.getRequestId());
- assertEquals(Status.ACCEPTED.getStatusCode(), entity.getCode().intValue());
- assertEquals(Boolean.FALSE, entity.getAckFinalIndicator());
-
- List<ServeEvent> events = waitForRequests(this.callbackRule, 1, 10);
- LoggedRequest notificationRequest = events.get(0).getRequest();
- assertEquals(AUTH, notificationRequest.getHeader(HttpHeaders.AUTHORIZATION));
- String notificationJson = notificationRequest.getBodyAsString();
-
- ObjectMapper mapper = new ObjectMapper();
- AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
- mapper.setAnnotationIntrospector(introspector);
- NetworkDiscoveryNotification notification = mapper.readValue(notificationJson,
- NetworkDiscoveryNotification.class);
-
+ NetworkDiscoveryNotification notification = (NetworkDiscoveryNotification) response.getEntity();
assertEquals(requestId, notification.getRequestId());
assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
@@ -331,7 +280,6 @@ public class NetworkDiscoveryTest {
assertNull(vserver.getAttributeList());
}
-
/**
* Verify API returns a final response indicating no discovery possible.
*/
@@ -341,13 +289,8 @@ public class NetworkDiscoveryTest {
String resourceType = "unsupported";
List<String> resourceIds = Arrays.asList("dummyId");
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
- this.requestId, resourceType, resourceIds, getCallbackUrl());
- assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
- NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
- System.err.println("entity:" + entity);
- assertEquals(Boolean.TRUE, entity.getAckFinalIndicator());
- assertEquals(Status.NO_CONTENT.getStatusCode(), entity.getCode().intValue());
+ this.requestId, resourceType, resourceIds);
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
@@ -357,35 +300,25 @@ public class NetworkDiscoveryTest {
String identityPath = "/v3/auth/tokens";
this.identityRule.stubFor(post(identityPath).willReturn(WireMock.unauthorized()));
-
- this.callbackRule.stubFor(post(CALLBACK_PATH).willReturn(ok("Acknowledged")));
Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
- RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId), getCallbackUrl());
-
- assertEquals(Status.OK.getStatusCode(), response.getStatus());
- NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
- assertEquals(requestId, entity.getRequestId());
- assertEquals(Status.ACCEPTED.getStatusCode(), entity.getCode().intValue());
- assertEquals(Boolean.FALSE, entity.getAckFinalIndicator());
-
- List<ServeEvent> events = waitForRequests(this.callbackRule, 1, 10);
- LoggedRequest notificationRequest = events.get(0).getRequest();
- assertEquals(AUTH, notificationRequest.getHeader(HttpHeaders.AUTHORIZATION));
- String notificationJson = notificationRequest.getBodyAsString();
-
- ObjectMapper mapper = new ObjectMapper();
- AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
- mapper.setAnnotationIntrospector(introspector);
- NetworkDiscoveryNotification notification = mapper.readValue(notificationJson,
- NetworkDiscoveryNotification.class);
+ RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
- assertEquals(requestId, notification.getRequestId());
- assertEquals(Status.INTERNAL_SERVER_ERROR.getStatusCode(), notification.getCode().intValue());
- assertEquals(Boolean.TRUE, notification.getAckFinalIndicator());
- assertNull(notification.getResources());
+ assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
+
+ @Test
+ public void testLoginFailureMissingToken() throws Exception {
+ String vserverId = UUID.randomUUID().toString();
+ String identityPath = "/v3/auth/tokens";
+
+ this.identityRule.stubFor(post(identityPath).willReturn(okJson("{}")));
+
+ Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, null, this.requestId,
+ RESOURCE_TYPE_VSERVER, Arrays.asList(vserverId));
+ assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
+ }
private void verifyAttribute(List<Attribute> attributeList, String attrName, String attrValue) {
for (Attribute attr : attributeList) {
@@ -397,25 +330,4 @@ public class NetworkDiscoveryTest {
fail("Attribute " + attrName + " not found");
}
- private List<ServeEvent> waitForRequests(WireMockRule service, int minRequests, long timeoutSeconds)
- throws InterruptedException {
-
- long remaining = timeoutSeconds * 1000L;
- long retryInterval = Math.min(remaining / 5, 1000);
- while (true) {
- List<ServeEvent> events = service.getAllServeEvents();
- if (events.size() >= minRequests) {
- return events;
- }
- if (remaining <= 0) {
- fail("Timeout waiting for " + minRequests + " requests");
- }
- Thread.sleep(retryInterval);
- remaining -= retryInterval;
- }
- }
-
- private String getCallbackUrl() {
- return "http://localhost:" + this.callbackRule.port() + CALLBACK_PATH;
- }
}
diff --git a/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/util/TransformationUtilTest.java b/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/util/TransformationUtilTest.java
index 968c1cf..dc4775f 100644
--- a/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/util/TransformationUtilTest.java
+++ b/pomba/network-discovery/src/test/java/org/onap/sdnc/apps/pomba/networkdiscovery/unittest/service/util/TransformationUtilTest.java
@@ -129,7 +129,6 @@ public class TransformationUtilTest {
for (Attribute attribute : resultAttributeList) {
resultAttributes.put(attribute.getName(), attribute.getValue());
}
- // assertThat(expectedAttributes, resultAttributes);
assertThat(expectedAttributes, CoreMatchers.is(resultAttributes));
}