Change parent version to snapshot
[appc.git] / appc-outbound / appc-network-inventory-client / provider / src / main / java / org / onap / appc / instar / dme2client / Dme2Client.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * 
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.instar.dme2client;
27
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.net.URI;
31 import java.nio.charset.Charset;
32 import java.util.Map;
33 import java.util.Properties;
34 import javax.net.ssl.HostnameVerifier;
35 import javax.net.ssl.SSLContext;
36 import javax.ws.rs.HttpMethod;
37 import javax.ws.rs.core.MediaType;
38 import org.apache.commons.io.IOUtils;
39 import org.onap.appc.instar.utils.InstarClientConstant;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
41 import com.att.eelf.configuration.EELFLogger;
42 import com.att.eelf.configuration.EELFManager;
43 import com.sun.jersey.api.client.Client;
44 import com.sun.jersey.api.client.ClientResponse;
45 import com.sun.jersey.api.client.WebResource;
46 import com.sun.jersey.api.client.config.DefaultClientConfig;
47 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
48 import com.sun.jersey.client.urlconnection.HTTPSProperties;
49
50 public class Dme2Client {
51
52     private static final EELFLogger log = EELFManager.getInstance().getLogger(Dme2Client.class);
53     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
54     private Properties properties = new Properties();
55     private String operationName;
56     private String appendContext;
57     private String mask;
58     private String ipAddress;
59
60     public Dme2Client(String optName, String subCtxt, Map<String, String> data) throws IOException {
61         log.info("Setting Properties for DME2 Client for INSTAR connection");
62         this.operationName = optName;
63         this.appendContext = data.get(subCtxt);
64         if ("getVnfbyIpadress".equals(optName)) {
65             this.ipAddress = data.get("ipAddress");
66             this.mask = data.get("mask");
67         }
68         String propDir = InstarClientConstant.getEnvironmentVariable(SDNC_CONFIG_DIR_VAR);
69         if (propDir == null) {
70             throw new IOException("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
71         }
72         String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES;
73         InputStream propStream = InstarClientConstant.getInputStream(propFile);
74         try {
75             properties.load(propStream);
76         } catch (Exception e) {
77             throw new IOException("Could not load properties file " + propFile, e);
78         } finally {
79             try {
80                 propStream.close();
81             } catch (Exception e) {
82                 log.warn("Could not close FileInputStream", e);
83             }
84         }
85     }
86
87     private ClientResponse sendToInstar() throws SvcLogicException {
88
89         log.info("Called Send with operation Name=" + this.operationName + "and = " +
90             properties.getProperty(operationName + InstarClientConstant.BASE_URL));
91
92         String resourceUri = buildResourceUri();
93
94         log.info("DME Endpoint URI:" + resourceUri);
95
96         Client client = null;
97         WebResource webResource;
98         ClientResponse clientResponse = null;
99         String authorization = properties.getProperty("authorization");
100         String requestDataType = "application/json";
101         String responseDataType = MediaType.APPLICATION_JSON;
102         String methodType = properties.getProperty("getIpAddressByVnf_method");
103         String request = "";
104         String userId = properties.getProperty("MechID");
105         String password = properties.getProperty("MechPass");
106
107         log.info("authorization = " + authorization + "methodType= " + methodType);
108
109         try {
110             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
111             System.setProperty("jsse.enableSNIExtension", "false");
112             SSLContext sslContext;
113             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
114             sslContext = SSLContext.getInstance("SSL");
115             sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
116             defaultClientConfig
117                 .getProperties()
118                 .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(getHostnameVerifier(), sslContext));
119             client = Client.create(defaultClientConfig);
120             client.addFilter(new HTTPBasicAuthFilter(userId, password));
121             webResource = client.resource(new URI(resourceUri));
122             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
123
124             if (HttpMethod.GET.equalsIgnoreCase(methodType)) {
125                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
126             } else if (HttpMethod.POST.equalsIgnoreCase(methodType)) {
127                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, request);
128             } else if (HttpMethod.PUT.equalsIgnoreCase(methodType)) {
129                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class, request);
130             } else if (HttpMethod.DELETE.equalsIgnoreCase(methodType)) {
131                 clientResponse = webResource.delete(ClientResponse.class);
132             }
133             return clientResponse;
134
135         } catch (Exception e) {
136             log.info(
137                 "failed in RESTCONT Action (" + methodType + ") for the resource " + resourceUri + ", falut message :"
138                     + e.getMessage());
139             throw new SvcLogicException("Error While gettting Data from INSTAR", e);
140
141         } finally {
142             // clean up.
143             if (client != null) {
144                 client.destroy();
145             }
146         }
147     }
148
149     private String buildResourceUri() {
150         String resourceUri = properties.getProperty(operationName + InstarClientConstant.BASE_URL) +
151             properties.getProperty(operationName + InstarClientConstant.URL_SUFFIX);
152
153         if (ipAddress != null && mask == null) {
154             resourceUri = resourceUri
155                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS) + ipAddress;
156         } else if (mask != null) {
157             resourceUri = resourceUri
158                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS)
159                 + ipAddress + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYMASK) + mask;
160         } else {
161             resourceUri = resourceUri
162                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT) + appendContext;
163         }
164         return resourceUri;
165     }
166
167     public String send() {
168         String response = null;
169         try {
170             if (validateProperties()) {
171                 return IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"),
172                     Charset.defaultCharset());
173             }
174             ClientResponse clientResponse = sendToInstar();
175             if (clientResponse != null) {
176                 response = clientResponse.getEntity(String.class);
177                 log.info(clientResponse.getStatus() + " Status, Response :" + response);
178             }
179         } catch (Exception e) {
180             log.error("Failed to send response", e);
181         }
182         return response;
183     }
184
185     private boolean validateProperties() {
186         return properties != null
187             && properties.getProperty(InstarClientConstant.MOCK_INSTAR) != null
188             && "true".equalsIgnoreCase(properties.getProperty(InstarClientConstant.MOCK_INSTAR));
189     }
190
191     private HostnameVerifier getHostnameVerifier() {
192         return (hostname, sslSession) -> true;
193     }
194 }