Programming/java
[java] WebUtils 및 FileUtils
WebUtils 및 FileUtils
WebUtils.java
package web.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.CookieGenerator;
import org.springframework.web.util.UriComponentsBuilder;
/**
* com.tving.mobile.web.util.TvingWebUtils.java
* <p/>
* <pre>
* 웹용 유틸리티 모듬
* </pre>
*
* @author developer
* @version 1.0
* @date 2012. 11. 13.
*/
public class WebUtils {
protected static final Logger log = LoggerFactory.getLogger(WebUtils.class);
public static final String KEY_HOSTNAME = "hostName";
public static final String KEY_HOSTADDRESS = "hostAddress";
public static final String KEY_IP = "ip";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
private static final String ACCESS_CONTROL_ALLOW_ORIGIN_VALUE = "*";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE = "true";
private static final String ACCESS_CONTROL_ALLOW_METHODS_VALUE = "GET";
private static final String EMPTY = "";
private static final String EMPER = "&";
private static final String QMARK = "?";
private static final String EQUAL = "=";
private static final String UTF8 = "UTF-8";
private static final String COLON = ":";
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
/**
* cookieName 을 받아서 해당 Cookie Object를 반환 한다<br>
*
* @param request
* @param cookieName
* @return
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
Cookie returnCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(cookieName)) {
returnCookie = cookies[i];
break;
}
}
}
return returnCookie;
}
/**
* cookieName 을 받아서 cookie value 를 String 으로 반환 한다.<br>
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieString(HttpServletRequest request, String cookieName) {
Cookie cookie = getCookie(request, cookieName);
if (cookie != null) {
try {
String valueStr = URLDecoder.decode(cookie.getValue(), "UTF-8");
return valueStr;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return null;
}
/**
* QueryString 을 받아서 parameterName=parameterValue 의 데이터에서 parameterName 기준으로 <br>
* value 값을 추출 입력값은 "parameterName=" 까지 이다 <br>
* rerutn <br>
*
* @param queryString
* @param parameterName
* @return
*/
public static String getQueryStringValue(String queryString, String parameterName) {
if (queryString == null || parameterName == null || EMPTY.equals(queryString) || EMPTY.equals(parameterName)) {
return EMPTY;
} else {
int stringIndex = queryString.indexOf(parameterName);
if (stringIndex > -1) {
String tempString = queryString.substring(stringIndex);
int splitCharIndex = tempString.indexOf(EMPER);
if (splitCharIndex > -1) {
return tempString.substring(parameterName.length(),
splitCharIndex);
} else {
return tempString.substring(parameterName.length());
}
} else {
return "";
}
}
}
/**
* URL 디코딩을 한다.
*
* @param url
* @param encoding
* @return
* @throws UnsupportedEncodingException
*/
public static String urlDecoder(String url, String encoding) {
if (url != null) {
try {
url = URLDecoder.decode(url, encoding);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return url;
}
public static String urlDecoder(String url) {
if (url != null) {
try {
url = URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return url;
}
/**
* URL 인코팅을 한다<br>
*
* @param url
* @param encoding
* @return
* @throws UnsupportedEncodingException
*/
public static String urlEncoder(String url, String encoding) throws UnsupportedEncodingException {
if (url != null) {
return URLEncoder.encode(url, encoding);
}
return null;
}
public static String urlEncoder(String url) throws UnsupportedEncodingException {
if (url != null) {
return URLEncoder.encode(url, "UTF-8");
}
return null;
}
/**
* UTF-8 인지 확인 한다.
*
* @param sequence
* @return
*/
public static boolean isUtf8(byte[] sequence) {
int numberBytesInChar;
for (int i = 0; i < sequence.length; i++) {
byte b = sequence[i];
if (((b >> 6) & 0x03) == 2) {
return false;
}
byte test = b;
numberBytesInChar = 0;
while ((test & 0x80) > 0) {
test <<= 1;
numberBytesInChar++;
}
if (numberBytesInChar > 1) {
for (int j = 1; j < numberBytesInChar; j++) {
if (i + j >= sequence.length) {
return false; // not a character encoding - probably
// random bytes
}
if (((sequence[i + j] >> 6) & 0x03) != 2) {
return false;
}
}
i += numberBytesInChar - 1; // increment i to the next utf8
// character start position.
}
}
return true;
}
/**
* HttpServletRequest 을 이용하여 <br>
* 요청 URL 을 추출해 낸다. <br>
*
* @param request
* @return
*/
public static String getRequestUrl(HttpServletRequest request) {
StringBuilder builder = new StringBuilder(request.getRequestURL());
Enumeration<String> parameterNames = request.getParameterNames();
int start = 0;
while (parameterNames.hasMoreElements()) {
String temp = parameterNames.nextElement();
if (0 == start) {
builder.append(QMARK);
} else {
builder.append(EMPER);
}
if (!StringUtils.equals(temp, "password") && !StringUtils.equals(temp, "passwd")) {
builder.append(temp);
builder.append(EQUAL);
builder.append(request.getParameter(temp));
}
start++;
}
return builder.toString();
}
/**
* HttpServletRequest 을 이용하여 <br>
* 요청 URL 중 parameter를 encoding하여 추출해 낸다. <br>
*
* @param request
* @return
*/
public static String getRequestUrlEncoding(HttpServletRequest request) {
StringBuilder builder = new StringBuilder(request.getRequestURL());
Enumeration<String> parameterNames = request.getParameterNames();
int start = 0;
while (parameterNames.hasMoreElements()) {
String temp = parameterNames.nextElement();
if (0 == start) {
builder.append(QMARK);
} else {
builder.append(EMPER);
}
builder.append(EQUAL);
String paramVal = request.getParameter(temp);
try {
paramVal = urlEncoder(paramVal, UTF8);
} catch (UnsupportedEncodingException ignore) {
}
builder.append(paramVal);
start++;
}
return builder.toString();
}
/**
* HttpServletRequest 를 기반으로 요청 도메인을 port 와 더불어 반환 한다.
*
* @param request
* @return
*/
public static String getRequestServer(HttpServletRequest request) {
StringBuilder builder = new StringBuilder("http://");
builder.append(request.getServerName());
if (80 != request.getServerPort()) { // 80 가 아닐 경우
builder.append(COLON);
builder.append(request.getServerPort());
}
return builder.toString();
}
/**
* 쿠키를 생성 한다. <br>
* maxAge(-1) : 시간 무제한에 브라저가 종료 할 때 까지 <br>
*
* @param cookieName
* @param value
* @param serverName
* @param path
* @param response
*/
public static void setCookieByBrowser(String cookieName, String value, String serverName, String path, HttpServletResponse response) {
try {
Cookie cookie = new Cookie(cookieName, URLEncoder.encode(value, "UTF-8"));
cookie.setDomain(serverName);
cookie.setPath(path);
cookie.setMaxAge(-1);
response.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 쿠키를 생성 한다. <br>
* maxAge(second) : 초 설정의 쿠키 생성 <br>
*
* @param cookieName
* @param value
* @param serverName
* @param path
* @param maxAge
* @param response
*/
public static void setCookie(String cookieName, String value, String serverName, String path, int maxAge, HttpServletResponse response) {
try {
Cookie cookie = new Cookie(cookieName, URLEncoder.encode(value, "UTF-8"));
cookie.setDomain(serverName);
cookie.setPath(path);
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static void setCookie(String cookieName, String value, int maxAge, HttpServletResponse response) {
try {
Cookie cookie = new Cookie(cookieName, URLEncoder.encode(value, "UTF-8"));
cookie.setPath("/");
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* 쿠키를 저장한다.
*
* @param cookie
* @param response
*/
public static void setCookie(Cookie cookie, HttpServletResponse response) {
response.addCookie(cookie);
}
/**
* 접속 User 의 아이피 정보를 준다 <br>
*
* @param request
* @return
*/
public static String getRemoteAddr(HttpServletRequest request) {
return StringUtils.isNotEmpty(request.getHeader("X-Real-IP")) ? request.getHeader("X-Real-IP") : request.getRemoteAddr();
}
/**
* cookie 를 삭제 한다 <br>
*
* @param cookieName
* @param request
* @param response
*/
public static void expireCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String serverName, String path) {
Cookie cookie = new Cookie(cookieName, EMPTY);
cookie.setDomain(serverName);
cookie.setPath(path);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
/**
* cookie 를 삭제 한다.
*
* @param cookieName
* @param request
* @param response
*/
public static void removeCookie(String cookieName, HttpServletRequest request, HttpServletResponse response) {
Cookie cookie = getCookie(request, cookieName);
if (cookie != null) {
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
/**
*
* @param request
* @return
*/
public static boolean isAppVisitor(HttpServletRequest request){
String store = request.getHeader("store");
String appId = request.getHeader("appId");
return (StringUtils.isNotBlank(store) && StringUtils.isNotBlank(appId));
}
/**
* key=value 의 문자열 목록을 가지고 Cookie 를 생성한다.
*
* @param response
* @param cookies
*/
public static void setCookies(HttpServletResponse response, List<String> cookies) {
if (cookies == null) return;
CookieGenerator cookieGenerator = new CookieGenerator();
for (String cookie : cookies) {
String[] cookieValue = cookie.split("=");
if (cookieValue.length == 2) {
cookieGenerator.setCookieName(cookieValue[0]);
cookieGenerator.addCookie(response, cookieValue[1]);
} else {
log.warn("Cookie [{}] can not be created", cookie);
}
}
}
/**
* 서버의 기본 URL을 반환한다.
*
* @param request
* @return
*/
public static String getBasePath(HttpServletRequest request) {
String basePath = request.getScheme() + "://" + request.getServerName();
if (request.getServerPort() == 80) {
basePath += request.getContextPath();
} else {
basePath += ":" + request.getServerPort() + request.getContextPath();
}
return basePath;
}
/**
* 인자로 넘어오는 값이 이메일인지 체크한다.
*
* @param email
* @return
*/
public static boolean isEmail(String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
public static boolean passPattern(String str, String ptern) {
Pattern pattern = Pattern.compile(ptern);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
/**
* 인자로 넘어오는 문자열의 끝 3자리만 *로 변경한다.
*
* @param str
* @return
*/
public static String getAsteriskString(String str) {
String tmpStr = str;
String emailDomain = null;
if (WebUtils.isEmail(str)) {
String[] emailInfo = StringUtils.split(str, "@");
tmpStr = emailInfo[0];
emailDomain = emailInfo[1];
}
tmpStr = StringUtils.substring(tmpStr, 0, tmpStr.length() - 3) + "***";
tmpStr = emailDomain == null ? tmpStr : tmpStr + "@" + emailDomain;
return tmpStr;
}
/**
* Map을 QueryString으로 변환한다.
*
* @param params
* @return
*/
public static String mapToQueryString(Map<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (sb.length() > 0) sb.append('&');
try {
sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append('=');
String value = entry.getValue();
if (value != null)
sb.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* URI를 생성한다.
*
* @param url
* @param params
* @return
*/
public static String buildURI(String url, Map<String, String> params) {
StringBuilder sb = new StringBuilder(url);
String queryString = mapToQueryString(params);
if (StringUtils.isNotBlank(queryString)) {
sb.append("?").append(queryString);
}
if (log.isDebugEnabled()) {
log.debug("buildURI : {}",sb.toString());
}
return sb.toString();
}
/**
* QueryString를 Map으로 파싱한다.
*
* @param queryString
* @param keys
* @return
*/
@SuppressWarnings("rawtypes")
public static Map parseQueryString(String queryString, String... keys) {
String[] params = queryString.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String name = param.split("=")[0];
String value = param.split("=")[1];
map.put(name, value);
}
if (keys != null) {
Map<String, String> rstMap = new HashMap<String, String>();
for (String key : keys) {
if (map.containsKey(key)) {
rstMap.put(key, map.get(key));
}
}
return rstMap;
}
return map;
}
/**
* 현재 요청의 URL을 파라미터를 포함하여 리턴한다.
*
* @return
*/
public static String getCurrentRequestURL() {
UriComponentsBuilder uriComponentsBuilder = ServletUriComponentsBuilder.fromCurrentRequest();
String urlStr = uriComponentsBuilder.build().toUriString();
return urlStr;
}
/**
* 로컬 호스트정보 리턴
* @return
* @throws java.net.UnknownHostException
*/
public static Map<String, String> getLocalHostInfo() throws UnknownHostException {
Map<String, String> map = new HashMap<String, String>();
InetAddress ia = InetAddress.getLocalHost();
map.put(KEY_HOSTADDRESS, ia.getHostAddress());
map.put(KEY_HOSTNAME, ia.getHostName());
map.put(KEY_IP, ia.getAddress().toString());
return map;
}
/**
* CORS header 설정
* @param request
* @param response
* @throws Exception
*/
public static void setCORSHeader(HttpServletRequest request, HttpServletResponse response) {
response.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ALLOW_ORIGIN_VALUE);
response.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, ACCESS_CONTROL_ALLOW_CREDENTIALS_VALUE);
response.setHeader(ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_METHODS_VALUE);
}
public static String postHttpURLConnection(HttpServletRequest request,String urlString, Map<String, Object> params) {
StringBuilder result = new StringBuilder();
HttpURLConnection connection = null;
BufferedReader br = null;
OutputStream os = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setDefaultUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 쿠키 정보 셋팅
Enumeration<String> enume = request.getHeaderNames();
while(enume.hasMoreElements()){
String key = enume.nextElement();
connection.setRequestProperty(key, request.getHeader(key));
}
// 파라미터 셋팅
String paramStr = "";
Iterator<String> iter = params.keySet().iterator();
while(iter.hasNext()){
String key = iter.next();
if(!"".equals(paramStr)){
paramStr += "&";
}
paramStr += key + "=" + URLEncoder.encode(String.valueOf(params.get(key)),"UTF-8") ;
}
os = connection.getOutputStream();
os.write( paramStr.getBytes("UTF-8") );
os.flush();
os.close();
br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String inputLine = null;
while ((inputLine = br.readLine()) != null) {
result.append(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(connection != null) connection.disconnect();
if(br !=null) br.close();
if(os !=null) os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result.toString();
}
/**
* JSONObject 에서 값을 반환한다.
*
* @param jsonObject jsonObject
* @param keys 찾을 키
* @return
*/
public static String getJsonValue(JSONObject jsonObject,String... keys){
String value = null;
int len = keys.length;
JSONObject result = jsonObject;
for(int i = 0 ,j = len; i < j ; i++){
if(result != null && !result.isNullObject()){
if((i+1) == j){
Object obj = result.get(keys[i]);
if(obj instanceof String){
value = obj.toString();
}
}else{
Object obj = result.get(keys[i]);
if(obj instanceof JSONObject){
result = result.getJSONObject(keys[i]);
}else if(obj instanceof JSONArray){
JSONArray _obj = (JSONArray)obj;
result = (JSONObject) _obj.get(0);
}
}
}
}
return value;
}
/**
* JSONObject 에서 값을 반환한다.
*
* @param jsonObject JSONObject
* @param keys 찾을 키
* @return String
*/
public static String getJsonValue(JSONObject jsonObject,String keys){
String[] key = StringUtils.split(keys,".");
return getJsonValue(jsonObject , key);
}
/**
* json 형태의 text에서 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return String
*/
public static String getJsonValue(String jsonText,String... keys){
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonValue(jsonObject, keys);
}
/**
* json 형태의 text에서 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return String
*/
public static String getJsonValue(String jsonText,String keys){
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonValue(jsonObject,keys);
}
/**
* JSONObject 값을 반환한다.
*
* @param jsonObject JSONObject
* @param keys 찾을 키
* @return JSONObject
*/
public static JSONObject getJsonObject(JSONObject jsonObject,String... keys){
JSONObject value = null;
int len = keys.length;
JSONObject result = jsonObject;
for(int i = 0 ,j = len; i < j ; i++){
if(result != null && !result.isNullObject()){
if((i+1) == j){
Object obj = result.get(keys[i]);
if(obj instanceof JSONObject){
value = (JSONObject) obj;
}
}else{
Object obj = result.get(keys[i]);
if(obj instanceof JSONObject){
result = result.getJSONObject(keys[i]);
}else if(obj instanceof JSONArray){
JSONArray _obj = (JSONArray)obj;
result = (JSONObject) _obj.get(0);
}
}
}
}
return value;
}
/**
* JSONObject 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return JSONObject
*/
public static JSONObject getJsonObject(String jsonText,String... keys){
if(StringUtils.isBlank(jsonText)){
return null;
}
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonObject(jsonObject,keys);
}
/**
* JSONObject 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return JSONObject
*/
public static JSONObject getJsonObject(String jsonText,String keys){
if(StringUtils.isBlank(jsonText)){
return null;
}
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonObject(jsonObject, keys);
}
/**
* JSONObject 값을 반환한다.
*
* @param jsonObject JSONObject
* @param keys 찾을 키
* @return JSONObject
*/
public static JSONObject getJsonObject(JSONObject jsonObject,String keys){
String[] key = StringUtils.split(keys, ".");
return getJsonObject(jsonObject , key);
}
/**
* JSONArray 값을 반환한다.
*
* @param jsonObject JSONObject
* @param keys 찾을 키
* @return JSONArray
*/
public static JSONArray getJsonArray(JSONObject jsonObject,String... keys){
JSONArray value = null;
int len = keys.length;
JSONObject result = jsonObject;
for(int i = 0 ,j = len; i < j ; i++){
if(result != null && !result.isNullObject()){
if((i+1) == j){
Object obj = result.get(keys[i]);
if(obj instanceof JSONArray){
value = (JSONArray) obj;
}
}else{
Object obj = result.get(keys[i]);
if(obj instanceof JSONObject){
result = result.getJSONObject(keys[i]);
}else if(obj instanceof JSONArray){
JSONArray _obj = (JSONArray)obj;
result = (JSONObject) _obj.get(0);
}
}
}
}
return value;
}
/**
* JSONArray 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return JSONArray
*/
public static JSONArray getJsonArray(String jsonText,String... keys){
if(StringUtils.isBlank(jsonText)){
return null;
}
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonArray(jsonObject,keys);
}
/**
* JSONArray 값을 반환한다.
*
* @param jsonText json 형태의 string문
* @param keys 찾을 키
* @return JSONArray
*/
public static JSONArray getJsonArray(String jsonText,String keys){
if(StringUtils.isBlank(jsonText)){
return null;
}
JSONObject jsonObject = JSONObject.fromObject(jsonText);
return getJsonArray(jsonObject, keys);
}
/**
* JSONArray 값을 반환한다.
*
* @param jsonObject JSONObject
* @param keys 찾을 키
* @return JSONArray
*/
public static JSONArray getJsonArray(JSONObject jsonObject,String keys){
String[] key = StringUtils.split(keys, ".");
return getJsonArray(jsonObject , key);
}
public static String getResponseToStr(String url) throws Exception {
URL ocu = new URL(url);
BufferedReader in = new BufferedReader(new InputStreamReader(ocu.openStream()));
String inputLine;
StringBuffer sb = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
if (log.isDebugEnabled()) {
log.debug("result = " + sb.toString());
}
return sb.toString();
}
}
FileUtils.java
package web.common.util;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* The type File util.
*/
public class FileUtil {
private static final int BUFFER_SIZE = 8192;
private static final String CHARSET = "UTF-8";
/**
* Gets file info.
*
* @param map the map
* @param realPath the real path
* @param savePath the save path
* @param rename the rename
* @return the file info
* @throws IllegalStateException the illegal state exception
* @throws IllegalStateException the illegal state exception
*/
public static List<Map<String,Object>> getFileInfo(MultiValueMap<String, MultipartFile> map,String realPath, String savePath, boolean rename) throws IllegalStateException, IOException {
Date time = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String formatDate = formatter.format(time);
Map<String, Object> returnMap = new HashMap<String, Object>();
List<Map<String,Object>> fileList = new ArrayList<Map<String, Object>>();
Iterator<String> iterator = map.keySet().iterator();
savePath = savePath + File.separator + StringUtils.substring(formatDate, 0, 4) + File.separator + StringUtils.substring(formatDate, 4, 8) + File.separator;
String realFilePath = savePath;
String logicalPath = savePath;
if(File.separator.equalsIgnoreCase("\\")){
realFilePath = realPath+savePath;
logicalPath = savePath.replaceAll("\\\\", "/");
}
//System.err.println("realFilePath : "+realFilePath);
//System.err.println("logicalPath : "+logicalPath);
while(iterator.hasNext()){
Map<String, Object> fileMap = new HashMap<String, Object>();
String key = iterator.next();
LinkedList<MultipartFile> df = (LinkedList<MultipartFile>) map.get(key);
CommonsMultipartFile fileInfo = (CommonsMultipartFile) df.getFirst();
if(fileInfo.getSize()>0){
fileMap.put("key",key);
int idx = fileInfo.getOriginalFilename().lastIndexOf(".");
String extName = "";
if( idx != -1 ) {
extName = fileInfo.getOriginalFilename().substring( idx, fileInfo.getOriginalFilename().length() );
}
File fDir = new File(realFilePath);
if(!fDir.exists()){
fDir.mkdirs();
}
if(rename){
File file1 = new File(realFilePath + formatDate);
fileInfo.transferTo(file1);
fileMap.put("path", logicalPath + formatDate);
fileMap.put("name", fileInfo.getOriginalFilename());
fileMap.put("size", ""+fileInfo.getSize());
fileMap.put("create_file", realFilePath + formatDate);
String imageType = getFileType(file1);
int imageWidthSize = 0;
int imageHeightSize = 0;
if("JPEG".equalsIgnoreCase(imageType)
|| "BMP".equalsIgnoreCase(imageType)
|| "GIF".equalsIgnoreCase(imageType)
|| "JPG".equalsIgnoreCase(imageType)
|| "PNG".equalsIgnoreCase(imageType))
{
// Image Size
BufferedInputStream bufferedis = null;
FileInputStream fileis = null;
BufferedImage bufferedimg = null;
try {
fileis = new FileInputStream(file1);
bufferedis = new BufferedInputStream(fileis);
bufferedimg = ImageIO.read(bufferedis);
imageWidthSize = bufferedimg == null? 0 : bufferedimg.getWidth();
imageHeightSize = bufferedimg == null? 0 : bufferedimg.getHeight();
fileMap.put("width", imageWidthSize+"");
fileMap.put("height", imageHeightSize+"");
} catch (Exception e) {
e.printStackTrace();
}finally{
if (fileis != null) try { fileis.close(); } catch (Exception e){}
if (bufferedis != null) try { bufferedis.close(); } catch (Exception e){}
}
}
}else{
File file1 = new File(realFilePath+formatDate+fileInfo.getName()+extName);
fileInfo.transferTo(file1);
fileMap.put("path", logicalPath + formatDate + fileInfo.getName() + extName);
fileMap.put("name", fileInfo.getOriginalFilename());
fileMap.put("size", ""+fileInfo.getSize());
fileMap.put("create_file", realFilePath+formatDate+fileInfo.getName()+extName);
String imageType = getFileType(file1);
int imageWidthSize = 0;
int imageHeightSize = 0;
if("JPEG".equalsIgnoreCase(imageType)
|| "BMP".equalsIgnoreCase(imageType)
|| "GIF".equalsIgnoreCase(imageType)
|| "JPG".equalsIgnoreCase(imageType)
|| "PNG".equalsIgnoreCase(imageType))
{
// Image Size
BufferedInputStream bufferedis = null;
FileInputStream fileis = null;
BufferedImage bufferedimg = null;
try {
fileis = new FileInputStream(file1);
bufferedis = new BufferedInputStream(fileis);
bufferedimg = ImageIO.read(bufferedis);
imageWidthSize = bufferedimg == null? 0 : bufferedimg.getWidth();
imageHeightSize = bufferedimg == null? 0 : bufferedimg.getHeight();
fileMap.put("width", imageWidthSize+"");
fileMap.put("height", imageHeightSize+"");
} catch (Exception e) {
e.printStackTrace();
}finally{
if (fileis != null) try { fileis.close(); } catch (Exception e){}
if (bufferedis != null) try { bufferedis.close(); } catch (Exception e){}
}
}
}
// for end
fileList.add(fileMap);
}
}
return fileList;
}
/**
* Gets file info.
*
* @param map the map
* @param filePath the file path
* @param savePath the save path
* @return the file info
* @throws IllegalStateException the illegal state exception
* @throws IOException the iO exception
*/
public static List<Map<String,Object>> getFileInfo(MultiValueMap<String, MultipartFile> map,String filePath, String savePath) throws IllegalStateException, IOException{
return getFileInfo(map,filePath,savePath,false);
}
/**
* @param request
* @param response
* @param realPath
* @param fileName
* @throws ServletException
* @throws IOException
*/
public static void download(HttpServletRequest request, HttpServletResponse response, String realPath , String fileName) throws ServletException, IOException {
try {
download(request, response, new File(realPath), fileName);
} catch (Exception e) {}
}
/**
* 파일 다운로드
*
* @param request
* @param response
* @param file
* @param fileName
* @throws ServletException
* @throws IOException
*/
public static void download(HttpServletRequest request,
HttpServletResponse response, File file, String fileName)
throws ServletException, IOException {
String mimetype = request.getSession().getServletContext().getMimeType(file.getName());
if (file == null || !file.exists() || file.length() <= 0 || file.isDirectory()) {
//System.out.println(file.getAbsolutePath());
throw new IOException("파일 객체가 Null 혹은 존재하지 않거나 길이가 0, 혹은 파일이 아닌 디렉토리이다.");
}
InputStream is = null;
try {
is = new FileInputStream(file);
download(request, response, is, fileName, file.length(), mimetype);
} finally {
try {
is.close();
} catch (Exception ex) {
}
}
}
/**
* 파일다운로드
*
* @param request
* @param response
* @param is
* @param filename
* @param filesize
* @param mimetype
* @throws ServletException
* @throws IOException
*/
public static void download(HttpServletRequest request,
HttpServletResponse response, InputStream is, String filename,
long filesize, String mimetype) throws ServletException,
IOException {
String mime = mimetype;
if (mimetype == null || mimetype.length() == 0) {
mime = "application/octet-stream;";
}
byte[] buffer = new byte[BUFFER_SIZE];
response.setContentType(mime + "; charset=" + CHARSET);
// 아래 부분에서 euc-kr 을 utf-8 로 바꾸거나 URLEncoding을 안하거나 등의 테스트를
// 해서 한글이 정상적으로 다운로드 되는 것으로 지정한다.
String userAgent = request.getHeader("User-Agent");
if (userAgent.indexOf("MSIE 5.5") > -1) { // MS IE 5.5 이하
response.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(filename, "UTF-8") + ";");
} else if (userAgent.indexOf("MSIE") > -1) { // MS IE (보통은 6.x 이상 가정)
filename=filename.replaceAll(" ","plmkijnhyrtfsdwerg578jh80jhrt56ghb");
String filename2 = java.net.URLEncoder.encode(filename, "UTF-8");
filename2=filename2.replaceAll("plmkijnhyrtfsdwerg578jh80jhrt56ghb"," ");
response.setHeader("Content-Disposition", "attachment; filename=" + filename2 + ";");
} else { // 모질라나 오페라
response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes(CHARSET), "latin1") + ";");
}
// 파일 사이즈가 정확하지 않을때는 아예 지정하지 않는다.
if (filesize > 0) {
response.setHeader("Content-Length", "" + filesize);
}
BufferedInputStream fin = null;
BufferedOutputStream outs = null;
try {
fin = new BufferedInputStream(is);
outs = new BufferedOutputStream(response.getOutputStream());
int read = 0;
while ((read = fin.read(buffer)) != -1) {
outs.write(buffer, 0, read);
}
} finally {
try {
outs.close();
} catch (Exception ex1) {
}
try {
fin.close();
} catch (Exception ex2) {
}
} // end of try/catch
}
/**
* 파일 타입
*
* @param file the file
* @return file type
*/
protected static String getFileType (File file) {
InputStream inputStream = null;
byte[] buf = new byte[132];
try {
inputStream = new FileInputStream(file);
inputStream.read(buf, 0, 132);
} catch (IOException ioexception) {
return "UNKNOWN";
} finally {
if (inputStream != null) try { inputStream.close(); } catch (Exception exception) {}
}
int b0 = buf[0] & 255;
int b1 = buf[1] & 255;
int b2 = buf[2] & 255;
int b3 = buf[3] & 255;
if (buf[128] == 68 && buf[129] == 73 && buf[130] == 67 && buf[131] == 77 && ((b0 == 73 && b1 == 73) || (b0 == 77 && b1 == 77)))
return "TIFF_AND_DICOM";
if (b0 == 73 && b1 == 73 && b2 == 42 && b3 == 0)
return "TIFF";
if (b0 == 77 && b1 == 77 && b2 == 0 && b3 == 42)
return "TIFF";
if (b0 == 255 && b1 == 216 && b2 == 255)
return "JPEG";
if (b0 == 71 && b1 == 73 && b2 == 70 && b3 == 56)
return "GIF";
if (buf[128] == 68 && buf[129] == 73 && buf[130] == 67 && buf[131] == 77)
return "DICOM";
if (b0 == 8 && b1 == 0 && b3 == 0)
return "DICOM";
if (b0 == 83 && b1 == 73 && b2 == 77 && b3 == 80)
return "FITS";
if (b0 == 80 && (b1 == 50 || b1 == 53) && (b2 == 10 || b2 == 13 || b2 == 32 || b2 == 9))
return "PGM";
if ( b0 == 66 && b1 == 77)
return "BMP";
if (b0 == 73 && b1 == 111)
return "ROI";
if (b0 >= 32 && b0 <= 126 && b1 >= 32 && b1 <= 126 && b2 >= 32 && b2 <= 126 && b3 >= 32 && b3 <= 126 && buf[8] >= 32 && buf[8] <= 126)
return "TEXT";
if (b0 == 137 && b1 == 80 && b2 == 78 && b3 == 71)
return "PNG";
return "UNKNOWN";
}
}
'Programming > java' 카테고리의 다른 글
[java] replaceAll(), trim() 으로 제거되지 않는 공백제거 (0) | 2015.01.09 |
---|---|
[java] 몇 분전, 몇 시간전, 몇 일전 표현 Util (0) | 2014.12.11 |
[java] 문서 파싱 및 추출(pdf, doc, docx, xls, xlsx, ppt, pptx) (0) | 2014.11.13 |
[java] J2EE (0) | 2014.09.18 |
[java] 스레드(Thread) (0) | 2014.09.17 |
'Programming/java'의 다른글
- 현재글[java] WebUtils 및 FileUtils