Merge "[AAI] Fix doc config files"
[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.json.JSONConfiguration;
28 import com.sun.jersey.client.urlconnection.HTTPSProperties;
29
30 import java.io.FileInputStream;
31 import java.io.IOException;
32 import java.security.KeyManagementException;
33 import java.security.KeyStore;
34 import java.security.KeyStoreException;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.UnrecoverableKeyException;
37 import java.security.cert.CertificateException;
38
39 import javax.net.ssl.HostnameVerifier;
40 import javax.net.ssl.HttpsURLConnection;
41 import javax.net.ssl.KeyManagerFactory;
42 import javax.net.ssl.SSLContext;
43 import javax.net.ssl.SSLSession;
44
45 import org.onap.aai.aailog.filter.RestControllerClientLoggingInterceptor;
46 import org.onap.aai.exceptions.AAIException;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public class HttpsAuthClient {
51
52     private static final Logger logger = LoggerFactory.getLogger(HttpsAuthClient.class);
53
54     /**
55      * The main method.
56      *
57      * @param args the arguments
58      */
59     public static void main(String[] args) {
60         try {
61             String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers";
62             System.out.println("Making Jersey https call...");
63             Client client = HttpsAuthClient.getClient();
64
65             ClientResponse res = client.resource(url).accept("application/json").header("X-TransactionId", "PROV001")
66                     .header("X-FromAppId", "AAI").type("application/json").get(ClientResponse.class);
67
68             // System.out.println("Jersey result: ");
69             // System.out.println(res.getEntity(String.class).toString());
70
71         } catch (KeyManagementException e) {
72             logger.debug("HttpsAuthClient KeyManagement error : {}", e.getMessage());
73         } catch (Exception e) {
74             logger.debug("HttpsAuthClient error : {}", e.getMessage());
75         }
76     }
77
78     /**
79      * Gets the client.
80      *
81      * @param truststorePath the truststore path
82      * @param truststorePassword the truststore password
83      * @param keystorePath the keystore path
84      * @param keystorePassword the keystore password
85      * @return the client
86      * @throws KeyManagementException the key management exception
87      */
88     public static Client getClient(String truststorePath, String truststorePassword, String keystorePath,
89             String keystorePassword) throws KeyManagementException, UnrecoverableKeyException, CertificateException,
90             NoSuchAlgorithmException, KeyStoreException, IOException {
91
92         ClientConfig config = new DefaultClientConfig();
93         config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
94         config.getClasses().add(org.onap.aai.restcore.CustomJacksonJaxBJsonProvider.class);
95         SSLContext ctx = null;
96         try {
97             System.setProperty("javax.net.ssl.trustStore", truststorePath);
98             System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
99             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
100                 public boolean verify(String string, SSLSession ssls) {
101                     return true;
102                 }
103             });
104
105             ctx = SSLContext.getInstance("TLSv1.2");
106             KeyManagerFactory kmf = null;
107
108             try (FileInputStream fin = new FileInputStream(keystorePath)) {
109                 kmf = KeyManagerFactory.getInstance("SunX509");
110                 KeyStore ks = KeyStore.getInstance("PKCS12");
111                 char[] pwd = keystorePassword.toCharArray();
112                 ks.load(fin, pwd);
113                 kmf.init(ks, pwd);
114             } catch (Exception e) {
115                 System.out.println("Error setting up kmf: exiting " + e.getMessage());
116                 throw e;
117             }
118
119             ctx.init(kmf.getKeyManagers(), null, null);
120             config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
121                     new HTTPSProperties(new HostnameVerifier() {
122                         @Override
123                         public boolean verify(String s, SSLSession sslSession) {
124                             return true;
125                         }
126                     }, ctx));
127         } catch (Exception e) {
128             System.out.println("Error setting up config: exiting " + e.getMessage());
129             throw e;
130         }
131
132         Client client = Client.create(config);
133         client.addFilter(new RestControllerClientLoggingInterceptor());
134         // uncomment this line to get more logging for the request/response
135         // client.addFilter(new LoggingFilter(System.out));
136
137         return client;
138     }
139
140     /**
141      * Gets the client.
142      *
143      * @return the client
144      * @throws KeyManagementException the key management exception
145      */
146     public static Client getClient() throws KeyManagementException, AAIException, UnrecoverableKeyException,
147             CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
148         String truststorePath = null;
149         String truststorePassword = null;
150         String keystorePath = null;
151         String keystorePassword = null;
152         truststorePath = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME);
153         truststorePassword = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD);
154         keystorePath = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME);
155         keystorePassword = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD);
156         return getClient(truststorePath, truststorePassword, keystorePath, keystorePassword);
157     }
158
159 }