Enhancements for the aai-common library
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / HttpsAuthClient.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.util;
22
23 import com.sun.jersey.api.client.Client;
24 import com.sun.jersey.api.client.ClientResponse;
25 import com.sun.jersey.api.client.config.ClientConfig;
26 import com.sun.jersey.api.client.config.DefaultClientConfig;
27 import com.sun.jersey.api.client.filter.LoggingFilter;
28 import com.sun.jersey.api.json.JSONConfiguration;
29 import com.sun.jersey.client.urlconnection.HTTPSProperties;
30 import org.onap.aai.aailog.filter.RestControllerClientLoggingInterceptor;
31 import org.onap.aai.exceptions.AAIException;
32
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.security.*;
36 import java.security.cert.CertificateException;
37
38 import javax.net.ssl.HostnameVerifier;
39 import javax.net.ssl.HttpsURLConnection;
40 import javax.net.ssl.KeyManagerFactory;
41 import javax.net.ssl.SSLContext;
42 import javax.net.ssl.SSLSession;
43
44 public class HttpsAuthClient {
45
46     /**
47      * The main method.
48      *
49      * @param args the arguments
50      */
51     public static void main(String[] args) {
52         try {
53             String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers";
54             System.out.println("Making Jersey https call...");
55             Client client = HttpsAuthClient.getClient();
56
57             ClientResponse res = client.resource(url).accept("application/json").header("X-TransactionId", "PROV001")
58                     .header("X-FromAppId", "AAI").type("application/json").get(ClientResponse.class);
59
60             // System.out.println("Jersey result: ");
61             // System.out.println(res.getEntity(String.class).toString());
62
63         } catch (KeyManagementException e) {
64             e.printStackTrace();
65         } catch (Exception e) {
66             e.printStackTrace();
67         }
68     }
69     /**
70      * Gets the client.
71      *
72      * @param truststorePath the truststore path
73      * @param truststorePassword the truststore password
74      * @param keystorePath the keystore path
75      * @param keystorePassword the keystore password
76      * @return the client
77      * @throws KeyManagementException the key management exception
78      */
79     public static Client getClient(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws KeyManagementException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
80
81         ClientConfig config = new DefaultClientConfig();
82         config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
83         config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
84         SSLContext ctx = null;
85         try {
86             System.setProperty("javax.net.ssl.trustStore", truststorePath);
87             System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
88             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
89                 public boolean verify(String string, SSLSession ssls) {
90                     return true;
91                 }
92             });
93
94             ctx = SSLContext.getInstance("TLSv1.2");
95             KeyManagerFactory kmf = null;
96             try {
97                 kmf = KeyManagerFactory.getInstance("SunX509");
98                 FileInputStream fin = new FileInputStream(keystorePath);
99                 KeyStore ks = KeyStore.getInstance("PKCS12");
100                 char[] pwd = keystorePassword.toCharArray();
101                 ks.load(fin, pwd);
102                 kmf.init(ks, pwd);
103             } catch (Exception e) {
104                 System.out.println("Error setting up kmf: exiting");
105                 e.printStackTrace();
106                 throw e;
107                 //System.exit(1);
108             }
109
110             ctx.init(kmf.getKeyManagers(), null, null);
111             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
112                 new HTTPSProperties(new HostnameVerifier() {
113                     @Override
114                     public boolean verify(String s, SSLSession sslSession) {
115                         return true;
116                     }
117                 }, ctx));
118         } catch (Exception e) {
119             System.out.println("Error setting up config: exiting");
120             e.printStackTrace();
121             throw e;
122             //System.exit(1);
123         }
124
125         Client client = Client.create(config);
126         client.addFilter(new RestControllerClientLoggingInterceptor());
127         // uncomment this line to get more logging for the request/response
128         // client.addFilter(new LoggingFilter(System.out));
129
130         return client;
131     }
132     /**
133      * Gets the client.
134      *
135      * @return the client
136      * @throws KeyManagementException the key management exception
137      */
138     public static Client getClient() throws KeyManagementException, AAIException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
139         String truststore_path = null;
140         String truststore_password = null;
141         String keystore_path = null;
142         String keystore_password = null;
143         try {
144             truststore_path =
145                 AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
146             truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
147             keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
148             keystore_password = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
149         }
150         catch (AAIException e) {
151             throw e;
152         }
153         return(getClient(truststore_path, truststore_password, keystore_path, keystore_password));
154     }
155
156 }