Updated jersey from com.sun.jersey to org.glassfish.jersey
[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
44
45 import javax.ws.rs.client.Client;
46 import javax.ws.rs.client.ClientBuilder;
47 import javax.ws.rs.client.Entity;
48 import javax.ws.rs.client.WebTarget;
49 import javax.ws.rs.core.Response;
50 import javax.ws.rs.core.Feature;
51 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
52
53 public class Dme2Client {
54
55     private static final EELFLogger log = EELFManager.getInstance().getLogger(Dme2Client.class);
56     private static final String SDNC_CONFIG_DIR_VAR = "SDNC_CONFIG_DIR";
57     private Properties properties = new Properties();
58     private String operationName;
59     private String appendContext;
60     private String mask;
61     private String ipAddress;
62
63     public Dme2Client(String optName, String subCtxt, Map<String, String> data) throws IOException {
64         log.info("Setting Properties for DME2 Client for INSTAR connection");
65         this.operationName = optName;
66         this.appendContext = data.get(subCtxt);
67         if ("getVnfbyIpadress".equals(optName)) {
68             this.ipAddress = data.get("ipAddress");
69             this.mask = data.get("mask");
70         }
71         String propDir = InstarClientConstant.getEnvironmentVariable(SDNC_CONFIG_DIR_VAR);
72         if (propDir == null) {
73             throw new IOException("Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
74         }
75         String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES;
76         InputStream propStream = InstarClientConstant.getInputStream(propFile);
77         try {
78             properties.load(propStream);
79         } catch (Exception e) {
80             throw new IOException("Could not load properties file " + propFile, e);
81         } finally {
82             try {
83                 propStream.close();
84             } catch (Exception e) {
85                 log.warn("Could not close FileInputStream", e);
86             }
87         }
88     }
89
90     private Response sendToInstar() throws SvcLogicException {
91
92         log.info("Called Send with operation Name=" + this.operationName + "and = " +
93             properties.getProperty(operationName + InstarClientConstant.BASE_URL));
94
95         String resourceUri = buildResourceUri();
96
97         log.info("DME Endpoint URI:" + resourceUri);
98
99         Client client = null;
100         WebTarget webResource;
101         Response clientResponse = null;
102         String authorization = properties.getProperty("authorization");
103         String requestDataType = "application/json";
104         String responseDataType = MediaType.APPLICATION_JSON;
105         String methodType = properties.getProperty("getIpAddressByVnf_method");
106         String request = "";
107         String userId = properties.getProperty("MechID");
108         String password = properties.getProperty("MechPass");
109
110         log.info("authorization = " + authorization + "methodType= " + methodType);
111
112         try {
113             System.setProperty("jsse.enableSNIExtension", "false");
114             SSLContext sslContext;
115             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
116             sslContext = SSLContext.getInstance("SSL");
117             sslContext.init(null, new javax.net.ssl.TrustManager[]{secureRestClientTrustManager}, null);
118
119
120             client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(getHostnameVerifier()).build();
121
122             client.register(HttpAuthenticationFeature.basic(userId, password));
123             webResource = client.target(new URI(resourceUri));
124             webResource.property("Content-Type", "application/json;charset=UTF-8");
125
126             if (HttpMethod.GET.equalsIgnoreCase(methodType)) {
127                 clientResponse = webResource.request(responseDataType).get(Response.class);
128             } else if (HttpMethod.POST.equalsIgnoreCase(methodType)) {
129                 clientResponse = webResource.request(requestDataType).post( Entity.json(request),Response.class);
130             } else if (HttpMethod.PUT.equalsIgnoreCase(methodType)) {
131                 clientResponse = webResource.request(requestDataType).put( Entity.json(request),Response.class);
132             } else if (HttpMethod.DELETE.equalsIgnoreCase(methodType)) {
133                 clientResponse = webResource.request().delete(Response.class);
134             }
135             return clientResponse;
136
137         } catch (Exception e) {
138             log.info(
139                 "failed in RESTCONT Action (" + methodType + ") for the resource " + resourceUri + ", falut message :"
140                     + e.getMessage());
141             throw new SvcLogicException("Error While gettting Data from INSTAR", e);
142
143         } finally {
144             // clean up.
145             if (client != null) {
146                 client.close();
147             }
148         }
149     }
150
151     private String buildResourceUri() {
152         String resourceUri = properties.getProperty(operationName + InstarClientConstant.BASE_URL) +
153             properties.getProperty(operationName + InstarClientConstant.URL_SUFFIX);
154
155         if (ipAddress != null && mask == null) {
156             resourceUri = resourceUri
157                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS) + ipAddress;
158         } else if (mask != null) {
159             resourceUri = resourceUri
160                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYIPADDRESS)
161                 + ipAddress + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT_BYMASK) + mask;
162         } else {
163             resourceUri = resourceUri
164                 + properties.getProperty(operationName + InstarClientConstant.SUB_CONTEXT) + appendContext;
165         }
166         return resourceUri;
167     }
168
169     public String send() {
170         String response = null;
171         try {
172             if (validateProperties()) {
173                 return IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"),
174                     Charset.defaultCharset());
175             }
176             Response clientResponse = sendToInstar();
177             if (clientResponse != null) {
178                 response = clientResponse.readEntity(String.class);
179                 log.info(clientResponse.getStatus() + " Status, Response :" + response);
180             }
181         } catch (Exception e) {
182             log.error("Failed to send response", e);
183         }
184         return response;
185     }
186
187     private boolean validateProperties() {
188         return properties != null
189             && properties.getProperty(InstarClientConstant.MOCK_INSTAR) != null
190             && "true".equalsIgnoreCase(properties.getProperty(InstarClientConstant.MOCK_INSTAR));
191     }
192
193     private HostnameVerifier getHostnameVerifier() {
194         return (hostname, sslSession) -> true;
195     }
196 }