Improve unit-test coverage
[vfc/nfvo/driver/vnfm/svnfm.git] / nokia / vnfmdriver / vfcadaptorservice / vfcadaptor / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / cbam / impl / MultipartUtility.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.impl;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.io.OutputStream;
25 import java.io.OutputStreamWriter;
26 import java.io.PrintWriter;
27 import java.net.URL;
28 import java.net.URLConnection;
29 import java.security.KeyStore;
30 import java.security.SecureRandom;
31 import java.security.cert.CertificateException;
32 import java.security.cert.X509Certificate;
33 import java.util.ArrayList;
34 import java.util.List;
35
36 import javax.net.ssl.HostnameVerifier;
37 import javax.net.ssl.HttpsURLConnection;
38 import javax.net.ssl.KeyManager;
39 import javax.net.ssl.KeyManagerFactory;
40 import javax.net.ssl.SSLContext;
41 import javax.net.ssl.SSLSession;
42 import javax.net.ssl.TrustManager;
43 import javax.net.ssl.TrustManagerFactory;
44 import javax.net.ssl.X509TrustManager;
45
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.bo.SslConfInfo;
49 import org.onap.vfc.nfvo.driver.vnfm.svnfm.common.util.CommonUtil;
50
51 import com.google.gson.Gson;
52  
53 /**
54  * This utility class provides an abstraction layer for sending multipart HTTP
55  * POST requests to a web server.
56  * @author www.codejava.net
57  *
58  */
59 public class MultipartUtility {
60         private static final Logger logger = LoggerFactory.getLogger(MultipartUtility.class);
61     private final String boundary;
62     private static final String LINE_FEED = "\r\n";
63     private HttpsURLConnection httpConn;
64     private String charset;
65     private OutputStream outputStream;
66     private PrintWriter writer;
67     private Gson gson = new Gson();
68  
69     /**
70      * This constructor initializes a new HTTP POST request with content type
71      * is set to multipart/form-data
72      * @param requestURL
73      * @param charset
74      * @throws IOException
75      */
76     public MultipartUtility(String requestURL, String charset)
77             throws Exception {
78         this.charset = charset;
79          
80         // creates a unique boundary based on time stamp
81         boundary = "---" + System.currentTimeMillis() + "---";
82         
83         HostnameVerifier hv = new HostnameVerifier() {  
84             public boolean verify(String urlHostName, SSLSession session) {  
85                 return true;  
86             }  
87         };  
88         TrustManager[] trustAllCerts = new TrustManager[1];  
89         TrustManager tm = new TrustManager() {
90                 
91                     public X509Certificate[] getAcceptedIssuers() {  
92                         return null;  
93                     }  
94                   
95                     public boolean isServerTrusted(X509Certificate[] certs) {  
96                         return true;  
97                     }  
98                   
99                     public boolean isClientTrusted(X509Certificate[] certs) {  
100                         return true;  
101                     }  
102                   
103                     public void checkServerTrusted(X509Certificate[] certs, String authType)  
104                             throws CertificateException {  
105                         return;  
106                     }  
107                   
108                     public void checkClientTrusted(X509Certificate[] certs, String authType)  
109                             throws CertificateException {  
110                         return;  
111                     }  
112         };  
113         trustAllCerts[0] = tm;  
114         SSLContext sslContext = SSLContext.getInstance("SSL");  
115         String filePath = "/etc/conf/sslconf.json";
116         String fileContent = CommonUtil.getJsonStrFromFile(filePath);
117         sslContext.init(createKeyManager(gson.fromJson(fileContent, SslConfInfo.class)), createTrustManager(gson.fromJson(fileContent, SslConfInfo.class)), new SecureRandom());
118         sslContext.init(null, trustAllCerts, null);
119         sslContext.init(null, new TrustManager[] {new TrustAnyTrustManager()}, new SecureRandom());
120         HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); 
121         HttpsURLConnection.setDefaultHostnameVerifier(hv);
122          
123         URL url = new URL(requestURL);
124         httpConn = (HttpsURLConnection) url.openConnection();
125         httpConn.setRequestMethod("POST");
126         httpConn.setUseCaches(false);
127         httpConn.setDoOutput(true); // indicates POST method
128         httpConn.setDoInput(true);
129         httpConn.setRequestProperty("Content-Type",
130                 "multipart/form-data; boundary=" + boundary);
131         httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
132         httpConn.setRequestProperty("Test", "Bonjour");
133         outputStream = httpConn.getOutputStream();
134         writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
135                 true);
136     }
137     
138     private static class TrustAnyTrustManager implements X509TrustManager {
139
140         @Override
141         public X509Certificate[] getAcceptedIssuers() {
142             return new X509Certificate[] {};
143         }
144
145         @Override
146         public void checkServerTrusted(X509Certificate[] certs, String authType) {
147             // NOSONAR
148         }
149
150         @Override
151         public void checkClientTrusted(X509Certificate[] certs, String authType) {
152             // NOSONAR
153         }
154     }
155     
156     private KeyManager[] createKeyManager(SslConfInfo sslConf) {
157         KeyManager[] kms = null;
158         try {
159             String CERT_STORE = "/etc/conf/server.p12";
160             String CERT_STORE_PASSWORD = "Changeme_123";
161             String KEY_STORE_TYPE = "PKCS12";
162             if(sslConf != null) {
163                 CERT_STORE = sslConf.getKeyStore();
164                 CERT_STORE_PASSWORD = sslConf.getKeyStorePass();
165                 KEY_STORE_TYPE = sslConf.getKeyStoreType();
166             }
167             // load jks file
168             FileInputStream f_certStore = new FileInputStream(CommonUtil.getAppRoot() + CERT_STORE);
169             KeyStore ks = KeyStore.getInstance(KEY_STORE_TYPE);
170             ks.load(f_certStore, CERT_STORE_PASSWORD.toCharArray());
171             f_certStore.close();
172
173             // init and create
174             String alg = KeyManagerFactory.getDefaultAlgorithm();
175             KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
176             kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray());
177
178             kms = kmFact.getKeyManagers();
179         } catch(Exception e) {
180             logger.error("create KeyManager fail!", e);
181         }
182         return kms;
183     }
184     
185     private TrustManager[] createTrustManager(SslConfInfo sslConf) {
186         TrustManager[] tms = null;
187         try {
188
189             String TRUST_STORE = "/etc/conf/trust.jks";
190             String TRUST_STORE_PASSWORD = "Changeme_123";
191             String TRUST_STORE_TYPE = "jks";
192             if(sslConf != null) {
193                 TRUST_STORE = sslConf.getTrustStore();
194                 TRUST_STORE_PASSWORD = sslConf.getTrustStorePass();
195                 TRUST_STORE_TYPE = sslConf.getTrustStoreType();
196             }
197             String jksFilePath1 =CommonUtil.getAppRoot() + TRUST_STORE;
198             logger.info("jks path is " + jksFilePath1);
199             FileInputStream f_trustStore = new FileInputStream(jksFilePath1);
200             KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE);
201             ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray());
202             f_trustStore.close();
203
204             String alg = TrustManagerFactory.getDefaultAlgorithm();
205             TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
206             tmFact.init(ks);
207             tms = tmFact.getTrustManagers();
208
209         } catch(Exception e) {
210             logger.error("create TrustManager fail!", e);
211         }
212         return tms;
213     }
214  
215  
216     /**
217      * Adds a upload file section to the request
218      * @param fieldName name attribute in <input type="file" name="..." />
219      * @param uploadFile a File to be uploaded
220      * @throws IOException
221      */
222     public void addFilePart(String fieldName, File uploadFile)
223             throws IOException {
224         String fileName = uploadFile.getName();
225         writer.append("--" + boundary).append(LINE_FEED);
226         writer.append(
227                 "Content-Disposition: form-data; name=\"" + fieldName
228                         + "\"; filename=\"" + fileName + "\"")
229                 .append(LINE_FEED);
230         writer.append(
231                 "Content-Type: "
232                         + URLConnection.guessContentTypeFromName(fileName))
233                 .append(LINE_FEED);
234         writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
235         writer.append(LINE_FEED);
236         writer.flush();
237  
238         FileInputStream inputStream = new FileInputStream(uploadFile);
239         byte[] buffer = new byte[4096];
240         int bytesRead = -1;
241         while ((bytesRead = inputStream.read(buffer)) != -1) {
242             outputStream.write(buffer, 0, bytesRead);
243         }
244         outputStream.flush();
245         inputStream.close();
246          
247         writer.append(LINE_FEED);
248         writer.flush();    
249     }
250  
251     /**
252      * Adds a header field to the request.
253      * @param name - name of the header field
254      * @param value - value of the header field
255      */
256     public void addHeaderField(String name, String value) {
257         writer.append(name + ": " + value).append(LINE_FEED);
258         writer.flush();
259     }
260      
261     /**
262      * Completes the request and receives response from the server.
263      * @return a list of Strings as response in case the server returned
264      * status OK, otherwise an exception is thrown.
265      * @throws IOException
266      */
267     public List<String> finish() throws IOException {
268         List<String> response = new ArrayList<String>();
269  
270         writer.append(LINE_FEED).flush();
271         writer.append("--" + boundary + "--").append(LINE_FEED);
272         writer.close();
273  
274         // checks server's status code first
275         int status = httpConn.getResponseCode();
276         logger.info("MultipartUtility --> finish " + httpConn.getResponseMessage());
277         if (status == HttpsURLConnection.HTTP_OK) {
278             BufferedReader reader = new BufferedReader(new InputStreamReader(
279                     httpConn.getInputStream()));
280             String line = null;
281             while ((line = reader.readLine()) != null) {
282                 response.add(line);
283             }
284             reader.close();
285             httpConn.disconnect();
286         } else {
287             throw new IOException("Server returned non-OK status: " + status);
288         }
289  
290         return response;
291     }
292 }