feat:Add file transfer function
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / util / UploadFileUtil.java
1 /*
2  * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
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 package org.onap.usecaseui.server.util;
17
18 import javax.activation.MimetypesFileTypeMap;
19 import java.io.*;
20 import java.net.HttpURLConnection;
21 import java.net.URL;
22 import java.util.Iterator;
23 import java.util.Map;
24
25 public class UploadFileUtil {
26     /**
27      * upload file
28      * @param urlStr
29      * @param textMap
30      * @param fileMap
31      * @param contentType default application/octet-stream
32      * @return return response data
33      */
34     @SuppressWarnings("rawtypes")
35     public static String formUpload(String urlStr, Map<String, String> textMap,
36                                     Map<String, String> fileMap,String contentType) {
37         String res = "";
38         HttpURLConnection conn = null;
39         String BOUNDARY = "---------------------------123821742118716";
40         try {
41             URL url = new URL(urlStr);
42             conn = (HttpURLConnection) url.openConnection();
43             conn.setConnectTimeout(5000);
44             conn.setReadTimeout(30000);
45             conn.setDoOutput(true);
46             conn.setDoInput(true);
47             conn.setUseCaches(false);
48             conn.setRequestMethod("POST");
49             conn.setRequestProperty("Connection", "Keep-Alive");
50             conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
51             OutputStream out = new DataOutputStream(conn.getOutputStream());
52             if (textMap != null) {
53                 StringBuffer strBuf = new StringBuffer();
54                 Iterator iter = textMap.entrySet().iterator();
55                 while (iter.hasNext()) {
56                     Map.Entry entry = (Map.Entry) iter.next();
57                     String inputName = (String) entry.getKey();
58                     String inputValue = (String) entry.getValue();
59                     if (inputValue == null) {
60                         continue;
61                     }
62                     strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
63                     strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
64                     strBuf.append(inputValue);
65                 }
66                 out.write(strBuf.toString().getBytes());
67             }
68             if (fileMap != null) {
69                 Iterator iter = fileMap.entrySet().iterator();
70                 while (iter.hasNext()) {
71                     Map.Entry entry = (Map.Entry) iter.next();
72                     String inputName = (String) entry.getKey();
73                     String inputValue = (String) entry.getValue();
74                     if (inputValue == null) {
75                         continue;
76                     }
77                     File file = new File(inputValue);
78                     String filename = file.getName();
79
80                     contentType = new MimetypesFileTypeMap().getContentType(file);
81                     if(!"".equals(contentType)){
82                         if (filename.endsWith(".png")) {
83                             contentType = "image/png";
84                         }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
85                             contentType = "image/jpeg";
86                         }else if (filename.endsWith(".gif")) {
87                             contentType = "image/gif";
88                         }else if (filename.endsWith(".ico")) {
89                             contentType = "image/image/x-icon";
90                         }
91                     }
92                     if (contentType == null || "".equals(contentType)) {
93                         contentType = "application/octet-stream";
94                     }
95                     StringBuffer strBuf = new StringBuffer();
96                     strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
97                     strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
98                     strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
99                     out.write(strBuf.toString().getBytes());
100                     DataInputStream in = new DataInputStream(new FileInputStream(file));
101                     int bytes = 0;
102                     byte[] bufferOut = new byte[1024];
103                     while ((bytes = in.read(bufferOut)) != -1) {
104                         out.write(bufferOut, 0, bytes);
105                     }
106                     in.close();
107                 }
108             }
109             byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
110             out.write(endData);
111             out.flush();
112             out.close();
113             StringBuffer strBuf = new StringBuffer();
114             BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
115             String line = null;
116             while ((line = reader.readLine()) != null) {
117                 strBuf.append(line).append("\n");
118             }
119             res = strBuf.toString();
120             reader.close();
121             reader = null;
122         } catch (Exception e) {
123             System.out.println("Error sending post request:" + urlStr);
124             e.printStackTrace();
125         } finally {
126             if (conn != null) {
127                 conn.disconnect();
128                 conn = null;
129             }
130         }
131         return res;
132     }
133 }