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