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.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;
51 import com.google.gson.Gson;
54 * This utility class provides an abstraction layer for sending multipart HTTP
55 * POST requests to a web server.
56 * @author www.codejava.net
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();
70 * This constructor initializes a new HTTP POST request with content type
71 * is set to multipart/form-data
76 public MultipartUtility(String requestURL, String charset)
78 this.charset = charset;
80 // creates a unique boundary based on time stamp
81 boundary = "---" + System.currentTimeMillis() + "---";
83 HostnameVerifier hv = new HostnameVerifier() {
84 public boolean verify(String urlHostName, SSLSession session) {
88 TrustManager[] trustAllCerts = new TrustManager[1];
89 TrustManager tm = new TrustManager() {
91 public X509Certificate[] getAcceptedIssuers() {
95 public boolean isServerTrusted(X509Certificate[] certs) {
99 public boolean isClientTrusted(X509Certificate[] certs) {
103 public void checkServerTrusted(X509Certificate[] certs, String authType)
104 throws CertificateException {
108 public void checkClientTrusted(X509Certificate[] certs, String authType)
109 throws CertificateException {
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);
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),
138 private static class TrustAnyTrustManager implements X509TrustManager {
141 public X509Certificate[] getAcceptedIssuers() {
142 return new X509Certificate[] {};
146 public void checkServerTrusted(X509Certificate[] certs, String authType) {
151 public void checkClientTrusted(X509Certificate[] certs, String authType) {
156 private KeyManager[] createKeyManager(SslConfInfo sslConf) {
157 KeyManager[] kms = null;
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();
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());
174 String alg = KeyManagerFactory.getDefaultAlgorithm();
175 KeyManagerFactory kmFact = KeyManagerFactory.getInstance(alg);
176 kmFact.init(ks, CERT_STORE_PASSWORD.toCharArray());
178 kms = kmFact.getKeyManagers();
179 } catch(Exception e) {
180 logger.error("create KeyManager fail!", e);
185 private TrustManager[] createTrustManager(SslConfInfo sslConf) {
186 TrustManager[] tms = null;
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();
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();
204 String alg = TrustManagerFactory.getDefaultAlgorithm();
205 TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
207 tms = tmFact.getTrustManagers();
209 } catch(Exception e) {
210 logger.error("create TrustManager fail!", e);
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
222 public void addFilePart(String fieldName, File uploadFile)
224 String fileName = uploadFile.getName();
225 writer.append("--" + boundary).append(LINE_FEED);
227 "Content-Disposition: form-data; name=\"" + fieldName
228 + "\"; filename=\"" + fileName + "\"")
232 + URLConnection.guessContentTypeFromName(fileName))
234 writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
235 writer.append(LINE_FEED);
238 FileInputStream inputStream = new FileInputStream(uploadFile);
239 byte[] buffer = new byte[4096];
241 while ((bytesRead = inputStream.read(buffer)) != -1) {
242 outputStream.write(buffer, 0, bytesRead);
244 outputStream.flush();
247 writer.append(LINE_FEED);
252 * Adds a header field to the request.
253 * @param name - name of the header field
254 * @param value - value of the header field
256 public void addHeaderField(String name, String value) {
257 writer.append(name + ": " + value).append(LINE_FEED);
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
267 public List<String> finish() throws IOException {
268 List<String> response = new ArrayList<String>();
270 writer.append(LINE_FEED).flush();
271 writer.append("--" + boundary + "--").append(LINE_FEED);
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()));
281 while ((line = reader.readLine()) != null) {
285 httpConn.disconnect();
287 throw new IOException("Server returned non-OK status: " + status);