2 * Copyright 2016-2017, Nokia Corporation
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.vfc.nfvo.driver.vnfm.svnfm.cbam.impl;
19 import java.io.BufferedReader;
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;
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;
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;
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;
50 import com.google.gson.Gson;
53 * This utility class provides an abstraction layer for sending multipart HTTP
54 * POST requests to a web server.
55 * @author www.codejava.net
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();
69 * This constructor initializes a new HTTP POST request with content type
70 * is set to multipart/form-data
75 public MultipartUtility(String requestURL, String charset)
77 this.charset = charset;
79 // creates a unique boundary based on time stamp
80 boundary = "---" + System.currentTimeMillis() + "---";
82 HostnameVerifier hv = new HostnameVerifier() {
83 public boolean verify(String urlHostName, SSLSession session) {
87 TrustManager[] trustAllCerts = new TrustManager[1];
88 TrustManager tm = new TrustManager() {
90 public X509Certificate[] getAcceptedIssuers() {
94 public boolean isServerTrusted(X509Certificate[] certs) {
98 public boolean isClientTrusted(X509Certificate[] certs) {
102 public void checkServerTrusted(X509Certificate[] certs, String authType)
103 throws CertificateException {
107 public void checkClientTrusted(X509Certificate[] certs, String authType)
108 throws CertificateException {
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);
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),
137 private static class TrustAnyTrustManager implements X509TrustManager {
140 public X509Certificate[] getAcceptedIssuers() {
141 return new X509Certificate[] {};
145 public void checkServerTrusted(X509Certificate[] certs, String authType) {
150 public void checkClientTrusted(X509Certificate[] certs, String authType) {
155 private KeyManager[] createKeyManager(SslConfInfo sslConf) {
156 KeyManager[] kms = null;
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();
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());
173 String alg = KeyManagerFactory.getDefaultAlgorithm();
174 KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
175 kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray());
177 kms = kmFact.getKeyManagers();
178 } catch(Exception e) {
179 logger.error("create KeyManager fail!", e);
184 private TrustManager[] createTrustManager(SslConfInfo sslConf) {
185 TrustManager[] tms = null;
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();
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();
203 String alg = TrustManagerFactory.getDefaultAlgorithm();
204 TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
206 tms = tmFact.getTrustManagers();
208 } catch(Exception e) {
209 logger.error("create TrustManager fail!", e);
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
221 public void addFilePart(String fieldName, File uploadFile)
223 String fileName = uploadFile.getName();
224 writer.append("--" + boundary).append(LINE_FEED);
226 "Content-Disposition: form-data; name=\"" + fieldName
227 + "\"; filename=\"" + fileName + "\"")
231 + URLConnection.guessContentTypeFromName(fileName))
233 writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
234 writer.append(LINE_FEED);
237 FileInputStream inputStream = new FileInputStream(uploadFile);
238 byte[] buffer = new byte[4096];
240 while ((bytesRead = inputStream.read(buffer)) != -1) {
241 outputStream.write(buffer, 0, bytesRead);
243 outputStream.flush();
246 writer.append(LINE_FEED);
251 * Adds a header field to the request.
252 * @param name - name of the header field
253 * @param value - value of the header field
255 public void addHeaderField(String name, String value) {
256 writer.append(name + ": " + value).append(LINE_FEED);
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
266 public List<String> finish() throws IOException {
267 List<String> response = new ArrayList<String>();
269 writer.append(LINE_FEED).flush();
270 writer.append("--" + boundary + "--").append(LINE_FEED);
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()));
280 while ((line = reader.readLine()) != null) {
284 httpConn.disconnect();
286 throw new IOException("Server returned non-OK status: " + status);