2e822d03248c2226a120f13776c7cfdb78df2ee1
[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 import java.io.FileInputStream;
27 import java.io.InputStream;
28 import java.net.URI;
29 import java.nio.charset.Charset;
30 import java.util.HashMap;
31 import java.util.Properties;
32 import javax.net.ssl.HostnameVerifier;
33 import javax.net.ssl.SSLContext;
34 import javax.ws.rs.HttpMethod;
35 import javax.ws.rs.core.MediaType;
36
37 import org.apache.commons.io.IOUtils;
38 import org.onap.appc.instar.utils.InstarClientConstant;
39
40
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
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     //DME2Client client = null;
55     Properties props = new Properties();
56     String operationName ;
57     String appendContext;
58 String mask;
59     String ipAddress;
60     public Dme2Client(String optName, String subCtxt, HashMap<String, String> data) throws Exception{
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 Exception(" Cannot find Property file -" + SDNC_CONFIG_DIR_VAR);
71         String propFile = propDir + InstarClientConstant.OUTBOUND_PROPERTIES;
72         InputStream propStream = new FileInputStream(propFile);
73         try
74         {
75             props.load(propStream);
76         }
77         catch (Exception e)
78         {
79             throw new Exception("Could not load properties file " + propFile, e);
80         }
81         finally
82         {
83             try
84             {
85                 propStream.close();
86             }
87             catch (Exception e)
88             {
89                 log.warn("Could not close FileInputStream", e);
90             }
91         }
92     }
93
94     public  ClientResponse  sendtoInstar() throws Exception {
95
96         log.info("Called Send with operation Name=" + this.operationName + "and = " + props.getProperty(operationName+InstarClientConstant.BASE_URL));
97         String resourceUri = props.getProperty(operationName+InstarClientConstant.BASE_URL)+
98                 props.getProperty(operationName + InstarClientConstant.URL_SUFFIX);
99                 if(this.ipAddress!=null && this.mask == null){
100             //resourceUri = resourceUri.substring(0,resourceUri.length() - 1) + "?";
101             resourceUri = resourceUri + props.getProperty(operationName+InstarClientConstant.SUB_CONTEXT_BYIPADDRESS);
102             resourceUri = resourceUri + ipAddress;
103         }else if(mask!=null){
104             //resourceUri = resourceUri.substring(0,resourceUri.length() - 1) + "?";
105             resourceUri = resourceUri + props.getProperty(operationName+InstarClientConstant.SUB_CONTEXT_BYIPADDRESS) + ipAddress+ props.getProperty(operationName+InstarClientConstant.SUB_CONTEXT_BYMASK);
106             resourceUri = resourceUri + mask ;
107         }else{
108             resourceUri=resourceUri+ props.getProperty(operationName + InstarClientConstant.SUB_CONTEXT)+ appendContext;
109         }
110
111         log.info("DME Endpoint URI:" + resourceUri);
112         Client client = null;
113         WebResource webResource = null;
114         ClientResponse clientResponse = null;
115         String authorization = props.getProperty("authorization");
116         String requestDataType = "application/json";
117         String responseDataType=    MediaType.APPLICATION_JSON;
118         String methodType =  props.getProperty("getIpAddressByVnf_method");
119         String request = "";
120         String userId=props.getProperty("MechID");
121         String password=props.getProperty("MechPass");
122         log.info("authorization = " + authorization + "methodType= " + methodType);
123         try{
124             DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
125             System.setProperty("jsse.enableSNIExtension", "false");
126             SSLContext sslContext = null;
127             SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager();
128             sslContext = SSLContext.getInstance("SSL");
129             sslContext.init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null);
130             defaultClientConfig.getProperties().put(
131                     com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
132                     new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), sslContext));
133             client = Client.create(defaultClientConfig);
134             client.addFilter(new HTTPBasicAuthFilter(userId, password));
135
136             webResource = client.resource(new URI(resourceUri));
137             webResource.setProperty("Content-Type", "application/json;charset=UTF-8");
138
139             if(HttpMethod.GET.equalsIgnoreCase(methodType)){
140                 clientResponse = webResource.accept(responseDataType).get(ClientResponse.class);
141             }else if(HttpMethod.POST.equalsIgnoreCase(methodType)){
142                 clientResponse = webResource.type(requestDataType).post(ClientResponse.class, request);
143             }else if(HttpMethod.PUT.equalsIgnoreCase(methodType)){
144                 clientResponse = webResource.type(requestDataType).put(ClientResponse.class,request);
145             }else if(HttpMethod.DELETE.equalsIgnoreCase(methodType)){
146                 clientResponse = webResource.delete(ClientResponse.class);
147             }
148
149             return clientResponse;
150
151         }catch (Exception e) {
152             log.info("failed in RESTCONT Action ("+methodType+") for the resource " + resourceUri + ", falut message :"+e.getMessage());
153             throw new Exception("Error While gettting Data from INSTAR" + e.getMessage());
154         }
155         finally {
156             // clean up.
157             webResource = null;
158             if(client != null){
159                 client.destroy();
160                 client = null;
161             }
162         }
163
164
165     }
166
167     public String send() {
168         String response = null;
169         try{
170
171             if(props !=null &&
172                     props.getProperty(InstarClientConstant.MOCK_INSTAR) != null &&
173                     props.getProperty(InstarClientConstant.MOCK_INSTAR).equalsIgnoreCase("true"))
174                 return  IOUtils.toString(Dme2Client.class.getClassLoader().getResourceAsStream("/tmp/sampleResponse"), Charset.defaultCharset());
175
176             ClientResponse clientResponse = sendtoInstar();
177             if(clientResponse != null){
178                 response = clientResponse.getEntity(String.class);
179                 log.info(clientResponse.getStatus() + " Status, Response :" + response);
180
181             }
182         } catch (Exception e) {
183             e.printStackTrace();
184         }
185         return response;
186     }
187
188     private HostnameVerifier getHostnameVerifier() {
189         return new HostnameVerifier() {
190             @Override
191             public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
192                 return true;
193             }
194         };
195     }
196
197
198 }