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