naming micro-service updates.
[ccsdk/apps.git] / ms / neng / src / main / java / org / onap / ccsdk / apps / ms / neng / service / extinf / impl / AaiServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : CCSDK.apps
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.ccsdk.apps.ms.neng.service.extinf.impl;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.InputStream;
27 import java.net.URI;
28 import java.security.KeyStore;
29 import java.util.logging.Logger;
30 import javax.net.ssl.SSLContext;
31 import org.apache.http.client.HttpClient;
32 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
33 import org.apache.http.impl.client.HttpClients;
34 import org.apache.http.ssl.SSLContextBuilder;
35 import org.onap.ccsdk.apps.ms.neng.core.exceptions.NengException;
36 import org.onap.ccsdk.apps.ms.neng.core.resource.model.AaiResponse;
37 import org.onap.ccsdk.apps.ms.neng.core.rs.interceptors.AaiAuthorizationInterceptor;
38 import org.onap.ccsdk.apps.ms.neng.extinf.props.AaiProps;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.beans.factory.annotation.Qualifier;
41 import org.springframework.boot.web.client.RestTemplateBuilder;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.http.RequestEntity;
44 import org.springframework.http.ResponseEntity;
45 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
46 import org.springframework.stereotype.Service;
47 import org.springframework.util.ResourceUtils;
48 import org.springframework.web.client.HttpClientErrorException;
49 import org.springframework.web.client.RestTemplate;
50
51 /**
52  * Implements interface with A&AI.
53  */
54 @Service
55 public class AaiServiceImpl {
56     private static final Logger log = Logger.getLogger(AaiServiceImpl.class.getName());
57
58     @Autowired AaiProps aaiProps;
59     RestTemplate restTemplate;
60     @Autowired AaiAuthorizationInterceptor authInt;
61
62     @Autowired
63     @Qualifier("aaiRestTempBuilder")
64     RestTemplateBuilder aaiRestTempBuilder;
65
66     /**
67      * Validates the given network element name against A&AI, using the given URL.
68      * @param url   the URL for A&AI
69      * @param name  a generated network element name
70      * @return      true if the element name is valid
71      */
72     public boolean validate(String url, String name) throws Exception {
73         AaiResponse resp = makeOutboundCall(url, name);
74         return !resp.isRecFound();
75     }
76
77     
78     public void setAaiRestTempBuilder(RestTemplateBuilder aaiRestTempBuilder) {
79         this.aaiRestTempBuilder = aaiRestTempBuilder;
80     }
81
82     public void setRestTemplate(RestTemplate restTemplate) {
83         this.restTemplate = restTemplate;
84     }    
85     
86     AaiResponse makeOutboundCall(String url, String name) throws Exception {
87         String uri = aaiProps.getUriBase() + url + name;
88         log.info("AAI URI - " + uri);
89         ResponseEntity<Object> resp = null;
90         try {
91             RequestEntity<Void> re = RequestEntity.get(new URI(uri)).build();
92             resp = getRestTemplate().exchange(re, Object.class);
93             if (HttpStatus.OK.equals(resp.getStatusCode())) {
94                 ObjectMapper objectmapper = new ObjectMapper();
95                 log.info(objectmapper.writeValueAsString(resp.getBody()));
96                 return buildResponse(true);
97             } else if (HttpStatus.NOT_FOUND.equals(resp.getStatusCode())) {
98                 log.warning(resp.toString());
99                 return buildResponse(false);
100             } else {
101                 log.warning(resp.toString());
102                 throw new NengException("Error while validating name with A&AI");
103             }
104         } catch (HttpClientErrorException e) {
105             log.warning(e.getStatusCode().name() + " -- " + e.getResponseBodyAsString());
106             if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
107                 return buildResponse(false);
108             }
109             throw new NengException("Error while validating name with AAI");
110         }
111     }
112     
113     AaiResponse buildResponse(boolean found) {
114         AaiResponse aaiResp = new AaiResponse();
115         aaiResp.setRecFound(found);
116         return aaiResp;
117     }
118
119     RestTemplate getRestTemplate() throws Exception {
120         if (this.restTemplate == null) {
121             char[] password = aaiProps.getCertPassword().toCharArray();
122             KeyStore ks = keyStore(aaiProps.getCert(), password);
123             SSLContextBuilder builder = SSLContextBuilder.create().loadKeyMaterial(ks, password); 
124             SSLContext sslContext = builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
125             HttpClient client = HttpClients.custom().setSSLContext(sslContext).build();
126             RestTemplateBuilder restBld = aaiRestTempBuilder.additionalInterceptors(authInt); 
127             this.restTemplate = restBld.requestFactory(new HttpComponentsClientHttpRequestFactory(client)).build();
128         }
129         return this.restTemplate;
130     }
131
132     KeyStore keyStore(String file, char[] password) throws Exception {
133         KeyStore keyStore = KeyStore.getInstance("PKCS12");
134         File key = ResourceUtils.getFile(file);
135         try (InputStream in = new FileInputStream(key)) {
136             keyStore.load(in, password);
137         }
138         return keyStore;
139     }
140     
141 }