7bcab6648998bb7a3f88bd21b1041123cf79b548
[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 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.instar.dme2client;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.sun.jersey.api.client.Client;
30 import com.sun.jersey.api.client.ClientResponse;
31 import com.sun.jersey.api.client.WebResource;
32 import com.sun.jersey.api.client.config.DefaultClientConfig;
33 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
34 import com.sun.jersey.client.urlconnection.HTTPSProperties;
35 import java.io.FileInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.net.URI;
39 import java.nio.charset.Charset;
40 import java.util.Map;
41 import java.util.Properties;
42 import javax.net.ssl.HostnameVerifier;
43 import javax.net.ssl.SSLContext;
44 import javax.ws.rs.HttpMethod;
45 import javax.ws.rs.core.MediaType;
46 import org.apache.commons.io.IOUtils;
47 import org.onap.appc.instar.utils.InstarClientConstant;
48 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
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 = System.getenv(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 = new FileInputStream(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
122             webResource = client.resource(new URI(resourceUri));
123             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
124
125             if (HttpMethod.GET.equalsIgnoreCase(methodType)) {
126                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
127             } else if (HttpMethod.POST.equalsIgnoreCase(methodType)) {
128                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, request);
129             } else if (HttpMethod.PUT.equalsIgnoreCase(methodType)) {
130                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class, request);
131             } else if (HttpMethod.DELETE.equalsIgnoreCase(methodType)) {
132                 clientResponse = webResource.delete(ClientResponse.class);
133             }
134             return clientResponse;
135
136         } catch (Exception e) {
137             log.info(
138                 "failed in RESTCONT Action (" + methodType + ") for the resource " + resourceUri + ", falut message :"
139                     + e.getMessage());
140             throw new SvcLogicException("Error While gettting Data from INSTAR", e);
141
142         } finally {
143             // clean up.
144             if (client != null) {
145                 client.destroy();
146             }
147         }
148     }
149
150     private String buildResourceUri() {
151         String resourceUri = properties.getProperty(operationName + InstarClientConstant.BASE_URL) +
152             properties.getProperty(operationName + InstarClientConstant.URL_SUFFIX);
153
154         if (ipAddress != null && mask == null) {
155             resourceUri = resourceUri
156                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS) + ipAddress;
157         } else if (mask != null) {
158             resourceUri = resourceUri
159                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS)
160                 + ipAddress + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYMASK) + mask;
161         } else {
162             resourceUri = resourceUri
163                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT) + appendContext;
164         }
165         return resourceUri;
166     }
167
168     public String send() {
169         String response = null;
170         try {
171             if (validateProperties()) {
172                 return IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"),
173                     Charset.defaultCharset());
174             }
175             ClientResponse clientResponse = sendToInstar();
176             if (clientResponse != null) {
177                 response = clientResponse.getEntity(String.class);
178                 log.info(clientResponse.getStatus() + " Status, Response :" + response);
179             }
180         } catch (Exception e) {
181             log.error("Failed to send response", e);
182         }
183         return response;
184     }
185
186     private boolean validateProperties() {
187         return properties != null
188             && properties.getProperty(InstarClientConstant.MOCK_INSTAR) != null
189             && "true".equalsIgnoreCase(properties.getProperty(InstarClientConstant.MOCK_INSTAR));
190     }
191
192     private HostnameVerifier getHostnameVerifier() {
193         return (hostname, sslSession) -> true;
194     }
195 }