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