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());
+ Integer.getInteger("discovery.threads", DEFAULT_WORKER_THREADS),
+ new ThreadFactoryBuilder().setNameFormat("discovery-worker-%d").build());
@Autowired
private RestClient enricherClient;
private DocumentBuilder parser;
+ @javax.annotation.Resource
+ private Map<String, String> enricherAttributeNameMapping;
public SpringServiceImpl() throws ParserConfigurationException {
this.parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
@Override
public NetworkDiscoveryResponse findbyResourceIdAndType(String transactionId,
- String requestId,
- String resourceType,
- List<String> resourceIds,
- String notificationURL,
- String notificationAuthorization,
- ONAPLogAdapter adapter) throws ApplicationException {
+ String requestId,
+ String resourceType,
+ List<String> resourceIds,
+ String notificationURL,
+ String notificationAuthorization,
+ ONAPLogAdapter adapter) throws ApplicationException {
NetworkDiscoveryResponse response = new NetworkDiscoveryResponse();
response.setRequestId(requestId);
}
// schedule discovery of specified resources
- Runnable task = new ResourceTask(transactionId, requestId, resourceType, resourceIds,
- notificationURL, notificationAuthorization, enricherURL, adapter);
+ Runnable task = new ResourceTask(transactionId, requestId, resourceType, resourceIds, notificationURL,
+ notificationAuthorization, enricherURL, adapter);
this.executor.submit(task);
response.setCode(Status.ACCEPTED.getStatusCode());
this.executor.shutdown();
}
- private List<Attribute> toAttributeList(String xml) throws SAXException, IOException {
- // TODO don't return raw A&AI attributes but coerce to swagger-defined enums
+ private List<Attribute> toAttributeList(String xml, ONAPLogAdapter adapter) throws SAXException, IOException {
+ Logger log = adapter.unwrap();
Document doc = this.parser.parse(new InputSource(new StringReader(xml)));
NodeList children = doc.getDocumentElement().getChildNodes();
List<Attribute> result = new ArrayList<>();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
- Attribute attr = new Attribute();
- attr.setName(((Element)child).getTagName());
- attr.setValue(((Element)child).getTextContent());
- attr.setDataQuality(DataQuality.ok());
- result.add(attr);
+
+ // remove white space before conversion
+ String attributeName = ((Element) child).getTagName().replaceAll("\\s", "");
+
+ // If the incoming attribute name is not listed in the
+ // attributeNameMapping, then this attribute will be removed.
+ String newName = enricherAttributeNameMapping.get(attributeName);
+ if (newName != null) {
+ Attribute attr = new Attribute();
+ attr.setName(newName);
+ attr.setValue(((Element) child).getTextContent());
+ attr.setDataQuality(DataQuality.ok());
+ result.add(attr);
+ } else {
+ log.debug("[" + ((Element) child).getTagName()
+ + "] was removed due to not listed in enricherAttributeNameMapping.");
+ }
}
}
return result;
private void sendNotification(String url, String authorization, Object notification, ONAPLogAdapter adapter) {
- Invocation.Builder request = this.callbackClient
- .target(url)
- .request()
- .accept(MediaType.TEXT_PLAIN_TYPE);
+ Invocation.Builder request = this.callbackClient.target(url).request().accept(MediaType.TEXT_PLAIN_TYPE);
if (authorization != null) {
request.header(HttpHeaders.AUTHORIZATION, authorization);
StringBuilder debugRequest = new StringBuilder("REQUEST:\n");
debugRequest.append("URL: ").append(url).append("\n");
debugRequest.append("Payload: ").append(notification).append("\n");
-// if (headers != null) {
-// debugRequest.append("Headers: ");
-// for (Entry<String, List<String>> header : headers.entrySet()) {
-// debugRequest.append("\n\t").append(header.getKey()).append(":");
-// for (String headerEntry : header.getValue()) {
-// debugRequest.append("\"").append(headerEntry).append("\" ");
-// }
-// }
-// }
+ // if (headers != null) {
+ // debugRequest.append("Headers: ");
+ // for (Entry<String, List<String>> header : headers.entrySet())
+ // {
+ // debugRequest.append("\n\t").append(header.getKey()).append(":");
+ // for (String headerEntry : header.getValue()) {
+ // debugRequest.append("\"").append(headerEntry).append("\" ");
+ // }
+ // }
+ // }
log.debug(debugRequest.toString());
}
Response result = request.post(Entity.json(notification));
- adapter.unwrap().info("request at url = {} resulted in http response: {}", url, result.getStatusInfo().getStatusCode() + " " + result.getStatusInfo().getReasonPhrase());
+ adapter.unwrap().info("request at url = {} resulted in http response: {}", url,
+ result.getStatusInfo().getStatusCode() + " " + result.getStatusInfo().getReasonPhrase());
if (log.isDebugEnabled()) {
StringBuilder debugResponse = new StringBuilder("RESPONSE:\n");
}
} catch (Exception x) {
- log.error("Error during {} operation to endpoint at url = {} with error = {}",
- "POST", url, x.getLocalizedMessage());
+ log.error("Error during {} operation to endpoint at url = {} with error = {}", "POST", url,
+ x.getLocalizedMessage());
}
}
private final ONAPLogAdapter adapter;
public ResourceTask(String transactionId,
- String requestId,
- String resourceType,
- List<String> resourceIds,
- String notificationURL,
- String notificationAuthorization,
- String resourceURL,
- ONAPLogAdapter adapter) {
+ String requestId,
+ String resourceType,
+ List<String> resourceIds,
+ String notificationURL,
+ String notificationAuthorization,
+ String resourceURL,
+ ONAPLogAdapter adapter) {
this.transactionId = transactionId;
this.requestId = requestId;
this.resourceType = resourceType;
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
headers.add(ENRICHER_HEADER_APPLICATION, RestService.SERVICE_NAME);
headers.add(ENRICHER_HEADER_TRANSACTION, this.transactionId);
+
for (String resourceId : this.resourceIds) {
String url = format.format(new Object[] { resourceId });
- OperationResult result = SpringServiceImpl.this.enricherClient.get(url, headers, MediaType.APPLICATION_XML_TYPE);
+ OperationResult result = SpringServiceImpl.this.enricherClient.get(url, headers,
+ MediaType.APPLICATION_XML_TYPE);
Resource resource = new Resource();
resource.setType(this.resourceType);
if (result.wasSuccessful()) {
resource.setDataQuality(DataQuality.ok());
try {
- resource.setAttributeList(toAttributeList(result.getResult()));
+ List<Attribute> attributeList = toAttributeList(result.getResult(), adapter);
+ resource.setAttributeList(attributeList);
} catch (Exception x) {
resource.setDataQuality(DataQuality.error(x.getMessage()));
}
- }
- else {
+ } else {
resource.setDataQuality(DataQuality.error(result.getFailureCause()));
}
}
private static class RequestBuilderWrapper implements RequestBuilder<RequestBuilderWrapper> {
private Invocation.Builder builder;
+
private RequestBuilderWrapper(Invocation.Builder builder) {
this.builder = builder;
}
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
@WebAppConfiguration
@SpringBootTest
-@TestPropertySource(properties = {
- "enricher.url=http://localhost:9505",
+@TestPropertySource(properties = { "enricher.url=http://localhost:9505",
"basicAuth.username=admin",
- "basicAuth.password=OBF:1u2a1toa1w8v1tok1u30"
-})
-
+ "basicAuth.password=OBF:1u2a1toa1w8v1tok1u30" })
public class NetworkDiscoveryTest {
private static final String V1 = "v1";
private static final String APP = "junit";
// 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, getCallbackUrl());
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
// should get WWW-Authenticate header in response
assertTrue(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE).startsWith("Basic realm"));
String authorization = "Basic " + Base64.getEncoder().encodeToString("aaa:bbb".getBytes());
// 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());
+ Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, authorization, APP,
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
// should not get WWW-Authenticate header in response
assertNull(response.getHeaderString(HttpHeaders.WWW_AUTHENTICATE));
// 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, getCallbackUrl());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
+ assertTrue(((String) response.getEntity()).contains(ONAPLogConstants.Headers.PARTNER_NAME));
}
@Test
// no X-FromAppId header
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, getCallbackUrl());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains("requestId"));
+ assertTrue(((String) response.getEntity()).contains("requestId"));
}
@Test
// no X-FromAppId header
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);
+ this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, null);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains("notificationURL"));
+ assertTrue(((String) response.getEntity()).contains("notificationURL"));
}
@Test
// 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());
+ Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains("resourceIds"));
+ assertTrue(((String) response.getEntity()).contains("resourceIds"));
}
// empty resourceId list
{
List<String> resourceIds = new ArrayList<>();
- Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP, this.transactionId,
- this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
+ Response response = this.service.findbyResourceIdAndType(this.httpRequest, V1, AUTH, APP,
+ this.transactionId, this.requestId, RESOURCE_TYPE_VSERVER, resourceIds, getCallbackUrl());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains("resourceIds"));
+ assertTrue(((String) response.getEntity()).contains("resourceIds"));
}
}
// 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, getCallbackUrl());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertTrue(((String)response.getEntity()).contains("resourceType"));
+ assertTrue(((String) response.getEntity()).contains("resourceType"));
}
@Test
String vserverId = UUID.randomUUID().toString();
String resourcePath = MessageFormat.format(
- this.environment.getProperty("enricher.type.vserver.url"),
- new Object[] { vserverId });
-
- String enricherPayload = String.format(
- "<vserver xmlns=\"http://org.onap.aai.inventory/v11\">\r\n"
- + " <vserver-id>%s</vserver-id>\r\n"
- + " <power-state>1</power-state>\r\n"
- + " <vm-state>active</vm-state>\r\n"
- + " <status>ACTIVE</status>\r\n"
- + " <host-status>UNKNOWN</host-status>\r\n"
- + " <updated>2017-11-20T04:26:13Z</updated>\r\n"
- + " <disk-allocation-gb>.010</disk-allocation-gb>\r\n"
- + " <memory-usage-mb>null</memory-usage-mb>\r\n"
- + " <cpu-util-percent>.043</cpu-util-percent>\r\n"
- + " <retrieval-timestamp>2018-06-27 19:41:49 +0000</retrieval-timestamp>\r\n"
- + "</vserver>", vserverId);
+ this.environment.getProperty("enricher.type.vserver.url"),
+ new Object[] { vserverId });
+
+ String enricherPayload = String.format("<vserver xmlns=\"http://org.onap.aai.inventory/v11\">\r\n"
+ + " <vserver-id>%s</vserver-id>\r\n"
+ + " <power-state>1</power-state>\r\n"
+ + " <locked>true</locked>\r\n"
+ + " <hostname>10.147.112.48</hostname>\r\n"
+ + " <vm-state>active</vm-state>\r\n"
+ + " <status>ACTIVE</status>\r\n"
+ + " <host-status>UNKNOWN</host-status>\r\n"
+ + " <updated>2017-11-20T04:26:13Z</updated>\r\n"
+ + " <disk-allocation-gb>.010</disk-allocation-gb>\r\n"
+ + " <memory-usage-mb>null</memory-usage-mb>\r\n"
+ + " <cpu-util-percent>.043</cpu-util-percent>\r\n"
+ + " <retrieval-timestamp>2018-06-27 19:41:49 +0000</retrieval-timestamp>\r\n"
+ + "</vserver>",
+ vserverId);
this.enricherRule.stubFor(get(resourcePath).willReturn(okTextXml(enricherPayload)));
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), getCallbackUrl());
assertEquals(Status.OK.getStatusCode(), response.getStatus());
NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.setAnnotationIntrospector(introspector);
- NetworkDiscoveryNotification notification =
- mapper.readValue(notificationJson, NetworkDiscoveryNotification.class);
+ NetworkDiscoveryNotification notification = mapper.readValue(notificationJson,
+ NetworkDiscoveryNotification.class);
assertEquals(requestId, notification.getRequestId());
assertEquals(Status.OK.getStatusCode(), notification.getCode().intValue());
assertEquals("vserver", vserver.getType());
assertEquals(DataQuality.Status.ok, vserver.getDataQuality().getStatus());
- verifyAttribute(vserver.getAttributeList(), "power-state", "1");
- verifyAttribute(vserver.getAttributeList(), "vm-state", "active");
verifyAttribute(vserver.getAttributeList(), "status", "ACTIVE");
- verifyAttribute(vserver.getAttributeList(), "host-status", "UNKNOWN");
- verifyAttribute(vserver.getAttributeList(), "updated", "2017-11-20T04:26:13Z");
- verifyAttribute(vserver.getAttributeList(), "disk-allocation-gb", ".010");
- verifyAttribute(vserver.getAttributeList(), "memory-usage-mb", "null");
- verifyAttribute(vserver.getAttributeList(), "cpu-util-percent", ".043");
- verifyAttribute(vserver.getAttributeList(), "retrieval-timestamp", "2018-06-27 19:41:49 +0000");
+ verifyAttribute(vserver.getAttributeList(), "inMaintenance", "true");
+ verifyAttribute(vserver.getAttributeList(), "hostname", "10.147.112.48");
+ verifyAttribute(vserver.getAttributeList(), "vmState", "active");
}
/**
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());
+ this.requestId, resourceType, resourceIds, getCallbackUrl());
assertEquals(Status.OK.getStatusCode(), response.getStatus());
NetworkDiscoveryResponse entity = (NetworkDiscoveryResponse) response.getEntity();
}
private List<ServeEvent> waitForRequests(WireMockRule service, int minRequests, long timeoutSeconds)
- throws InterruptedException {
+ throws InterruptedException {
long remaining = timeoutSeconds * 1000L;
long retryInterval = Math.min(remaining / 5, 1000);