b6c35e5050d62b618144d635f801498939b5a92a
[appc.git] /
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  * 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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.instar.dme2client;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.sun.jersey.api.client.Client;
29 import com.sun.jersey.api.client.ClientResponse;
30 import com.sun.jersey.api.client.WebResource;
31 import com.sun.jersey.api.client.config.DefaultClientConfig;
32 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
33 import com.sun.jersey.client.urlconnection.HTTPSProperties;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.net.URI;
38 import java.nio.charset.Charset;
39 import java.util.Map;
40 import java.util.Properties;
41 import javax.net.ssl.HostnameVerifier;
42 import javax.net.ssl.SSLContext;
43 import javax.ws.rs.HttpMethod;
44 import javax.ws.rs.core.MediaType;
45 import org.apache.commons.io.IOUtils;
46 import org.onap.appc.instar.utils.InstarClientConstant;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
48
49 public class Dme2Client {
50
51     private static final EELFLogger log = EELFManager.getInstance().getLogger(Dme2Client.class);
52     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
53     private Properties properties = new Properties();
54     private String operationName;
55     private String appendContext;
56     private String mask;
57     private String ipAddress;
58
59     public Dme2Client(String optName, String subCtxt, Map<String, String> data) throws IOException {
60         log.info("Setting Properties for DME2 Client for INSTAR connection");
61         this.operationName = optName;
62         this.appendContext = data.get(subCtxt);
63         if ("getVnfbyIpadress".equals(optName)) {
64             this.ipAddress = data.get("ipAddress");
65             this.mask = data.get("mask");
66         }
67         String propDir = System.getenv(SDNC_CONFIG_DIR_VAR);
68         if (propDir == null) {
69             throw new IOException("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
70         }
71         String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES;
72         InputStream propStream = new FileInputStream(propFile);
73         try {
74             properties.load(propStream);
75         } catch (Exception e) {
76             throw new IOException("Could not load properties file " + propFile, e);
77         } finally {
78             try {
79                 propStream.close();
80             } catch (Exception e) {
81                 log.warn("Could not close FileInputStream", e);
82             }
83         }
84     }
85
86     private ClientResponse sendToInstar() throws SvcLogicException {
87
88         log.info("Called Send with operation Name=" + this.operationName + "and = " +
89             properties.getProperty(operationName + InstarClientConstant.BASE_URL));
90
91         String resourceUri = buildResourceUri();
92
93         log.info("DME Endpoint URI:" + resourceUri);
94
95         Client client = null;
96         WebResource webResource;
97         ClientResponse clientResponse = null;
98         String authorization = properties.getProperty("authorization");
99         String requestDataType = "application/json";
100         String responseDataType = MediaType.APPLICATION_JSON;
101         String methodType = properties.getProperty("getIpAddressByVnf_method");
102         String request = "";
103         String userId = properties.getProperty("MechID");
104         String password = properties.getProperty("MechPass");
105
106         log.info("authorization = " + authorization + "methodType= " + methodType);
107
108         try {
109             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
110             System.setProperty("jsse.enableSNIExtension", "false");
111             SSLContext sslContext;
112             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
113             sslContext = SSLContext.getInstance("SSL");
114             sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
115             defaultClientConfig
116                 .getProperties()
117                 .put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(getHostnameVerifier(), sslContext));
118             client = Client.create(defaultClientConfig);
119             client.addFilter(new HTTPBasicAuthFilter(userId, password));
120
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 }