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;
35 import java.security.NoSuchAlgorithmException;
36 import java.security.KeyManagementException;
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;
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;
53 import com.google.gson.Gson;
56 * This utility class provides an abstraction layer for sending multipart HTTP
57 * POST requests to a web server.
58 * @author www.codejava.net
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();
72 * This constructor initializes a new HTTP POST request with content type
73 * is set to multipart/form-data
78 public MultipartUtility(String requestURL, String charset)
79 throws CertificateException, IOException, NoSuchAlgorithmException, KeyManagementException{
80 this.charset = charset;
82 // creates a unique boundary based on time stamp
83 boundary = "---" + System.currentTimeMillis() + "---";
85 HostnameVerifier hv = new HostnameVerifier() {
86 public boolean verify(String urlHostName, SSLSession session) {
90 TrustManager[] trustAllCerts = new TrustManager[1];
91 TrustManager tm = new TrustManager() {
93 public X509Certificate[] getAcceptedIssuers() {
97 public boolean isServerTrusted(X509Certificate[] certs) {
101 public boolean isClientTrusted(X509Certificate[] certs) {
105 public void checkServerTrusted(X509Certificate[] certs, String authType)
106 throws CertificateException {
110 public void checkClientTrusted(X509Certificate[] certs, String authType)
111 throws CertificateException {
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);
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),
140 private static class TrustAnyTrustManager implements X509TrustManager {
143 public X509Certificate[] getAcceptedIssuers() {
144 return new X509Certificate[] {};
148 public void checkServerTrusted(X509Certificate[] certs, String authType) {
153 public void checkClientTrusted(X509Certificate[] certs, String authType) {
158 private KeyManager[] createKeyManager(SslConfInfo sslConf) {
159 KeyManager[] kms = null;
161 String CERT_STORE = "/etc/conf/server.p12";
162 String CERT_STORE_PASSWORD = "Changeme_123";
163 String KEY_STORE_TYPE = "PKCS12";
164 if(sslConf != null) {
165 CERT_STORE = sslConf.getKeyStore();
166 CERT_STORE_PASSWORD = sslConf.getKeyStorePass();
167 KEY_STORE_TYPE = sslConf.getKeyStoreType();
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_PASSWORD.toCharArray());
176 String alg = KeyManagerFactory.getDefaultAlgorithm();
177 KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
178 kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray());
180 kms = kmFact.getKeyManagers();
182 } catch(Exception e) {
183 logger.error("create KeyManager fail!", e);
188 private TrustManager[] createTrustManager(SslConfInfo sslConf) {
189 TrustManager[] tms = null;
192 String TRUST_STORE = "/etc/conf/trust.jks";
193 String TRUST_STORE_PASSWORD = "Changeme_123";
194 String TRUST_STORE_TYPE = "jks";
195 if(sslConf != null) {
196 TRUST_STORE = sslConf.getTrustStore();
197 TRUST_STORE_PASSWORD = sslConf.getTrustStorePass();
198 TRUST_STORE_TYPE = sslConf.getTrustStoreType();
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_PASSWORD.toCharArray());
207 String alg = TrustManagerFactory.getDefaultAlgorithm();
208 TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
210 tms = tmFact.getTrustManagers();
213 } catch(Exception e) {
214 logger.error("create TrustManager fail!", e);
221 * Adds a upload file section to the request
222 * @param fieldName name attribute in <input type="file" name="..." />
223 * @param uploadFile a File to be uploaded
224 * @throws IOException
226 public void addFilePart(String fieldName, File uploadFile)
228 String fileName = uploadFile.getName();
229 writer.append("--" + boundary).append(LINE_FEED);
231 "Content-Disposition: form-data; name=\"" + fieldName
232 + "\"; filename=\"" + fileName + "\"")
236 + URLConnection.guessContentTypeFromName(fileName))
238 writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
239 writer.append(LINE_FEED);
242 try(FileInputStream inputStream = new FileInputStream(uploadFile)){
243 byte[] buffer = new byte[4096];
245 while ((bytesRead = inputStream.read(buffer)) != -1) {
246 outputStream.write(buffer, 0, bytesRead);
248 outputStream.flush();
251 writer.append(LINE_FEED);
256 * Adds a header field to the request.
257 * @param name - name of the header field
258 * @param value - value of the header field
260 public void addHeaderField(String name, String value) {
261 writer.append(name + ": " + value).append(LINE_FEED);
266 * Completes the request and receives response from the server.
267 * @return a list of Strings as response in case the server returned
268 * status OK, otherwise an exception is thrown.
269 * @throws IOException
271 public List<String> finish() throws IOException {
272 List<String> response = new ArrayList<String>();
274 writer.append(LINE_FEED).flush();
275 writer.append("--" + boundary + "--").append(LINE_FEED);
278 // checks server's status code first
279 int status = httpConn.getResponseCode();
280 logger.info("MultipartUtility --> finish " + httpConn.getResponseMessage());
281 if (status == HttpsURLConnection.HTTP_OK) {
282 BufferedReader reader = new BufferedReader(new InputStreamReader(
283 httpConn.getInputStream()));
285 while ((line = reader.readLine()) != null) {
289 httpConn.disconnect();
291 throw new IOException("Server returned non-OK status: " + status);