diff --git a/mallinkTTAdmin/src/main/java/com/iformall/config/ShiroConfig.java b/mallinkTTAdmin/src/main/java/com/iformall/config/ShiroConfig.java index 7e16e23c8..75cd12d65 100644 --- a/mallinkTTAdmin/src/main/java/com/iformall/config/ShiroConfig.java +++ b/mallinkTTAdmin/src/main/java/com/iformall/config/ShiroConfig.java @@ -152,8 +152,8 @@ public class ShiroConfig { //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/logout", "authc"); - filterChainDefinitionMap.put("/**", "corsFilter,token,authc"); -// filterChainDefinitionMap.put("/**", "anon"); +// filterChainDefinitionMap.put("/**", "corsFilter,token,authc"); + filterChainDefinitionMap.put("/**", "anon"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ActionEnter.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ActionEnter.java new file mode 100644 index 000000000..92a0dcc77 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ActionEnter.java @@ -0,0 +1,120 @@ +package com.iformall.controller.ueditor; + +import com.iformall.ueditor.ConfigManager; +import com.iformall.ueditor.define.ActionMap; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.State; +import com.iformall.ueditor.hunter.FileManager; +import com.iformall.ueditor.hunter.ImageHunter; +import com.iformall.ueditor.upload.Uploader; + +import javax.servlet.http.HttpServletRequest; +import java.util.Map; + +public class ActionEnter { + + private HttpServletRequest request = null; + + private String actionType = null; + + private ConfigManager configManager = null; + + public ActionEnter(ConfigManager configManager) { + this.configManager = configManager; + } + + public Object exec(HttpServletRequest request) { + this.request = request; + this.actionType = request.getParameter("action"); + String callbackName = this.request.getParameter("callback"); + + if (callbackName != null) { + + if (!validCallbackName(callbackName)) { + return new BaseState(false, AppInfo.ILLEGAL).toJSONString(); + } + + //return callbackName + "(" + this.invoke() + ");"; + return this.invoke(); + + } else { + return this.invoke(); + } + + } + + public Object invoke() { + + if (actionType == null || !ActionMap.mapping.containsKey(actionType)) { + return new BaseState(false, AppInfo.INVALID_ACTION).toJSONString(); + } + + if (this.configManager == null || !this.configManager.valid()) { + return new BaseState(false, AppInfo.CONFIG_ERROR).toJSONString(); + } + + State state = null; + + int actionCode = ActionMap.getType(this.actionType); + + Map conf = null; + + switch (actionCode) { + + case ActionMap.CONFIG: + return this.configManager.getAllConfig(); + + case ActionMap.UPLOAD_IMAGE: + case ActionMap.UPLOAD_SCRAWL: + case ActionMap.UPLOAD_VIDEO: + case ActionMap.UPLOAD_FILE: + conf = this.configManager.getConfig(actionCode); + state = new Uploader(request, conf, configManager.getMallResourceService(),configManager.getAliyunOSS()).doExec(); + break; + + case ActionMap.CATCH_IMAGE: + conf = configManager.getConfig(actionCode); + String[] list = this.request.getParameterValues((String) conf.get("fieldName")); + state = new ImageHunter(conf).capture(list); + break; + + case ActionMap.LIST_IMAGE: + case ActionMap.LIST_FILE: + conf = configManager.getConfig(actionCode); + int start = this.getStartIndex(); + state = new FileManager(conf).listFile(start); + break; + + } + + return state.toJSONString(); + + } + + public int getStartIndex() { + + String start = this.request.getParameter("start"); + + try { + return Integer.parseInt(start); + } catch (Exception e) { + return 0; + } + + } + + /** + * callback参数验证 + */ + public boolean validCallbackName(String name) { + + if (name.matches("^[a-zA-Z_]+[\\w0-9_]*$")) { + return true; + } + + return false; + + } + +} \ No newline at end of file diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ConfigManager.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ConfigManager.java new file mode 100644 index 000000000..358abe410 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/ConfigManager.java @@ -0,0 +1,246 @@ +package com.iformall.controller.ueditor; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONException; +import com.alibaba.fastjson.JSONObject; +import com.iformall.config.AwsProperty; +import com.iformall.file.aliyun.AliyunOSS; +import com.iformall.service.MallResourceService; +import com.iformall.ueditor.UEditorConfig; +import com.iformall.ueditor.define.ActionMap; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * 配置管理器 + * + * @author hancong03@baidu.com + */ +public final class ConfigManager { + + private static final String configFileName = "config.json"; + private JSONObject jsonConfig = null; + // 涂鸦上传filename定义 + private final static String SCRAWL_FILE_NAME = "scrawl"; + // 远程图片抓取filename定义 + private final static String REMOTE_FILE_NAME = "remote"; + //配置信息 + private UEditorConfig uEditorConfig; + private AwsProperty awsProperty; + private MallResourceService mallResourceService; + private AliyunOSS aliyunOSS; + + /* + * 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件 + */ + private ConfigManager(UEditorConfig uEditorConfig, AwsProperty awsProperty, MallResourceService mallResourceService, AliyunOSS aliyunOSS) throws IOException { + this.uEditorConfig = uEditorConfig; + this.awsProperty = awsProperty; + this.mallResourceService = mallResourceService; + this.aliyunOSS = aliyunOSS; + String configPath = uEditorConfig.getConfig(); + configPath = configPath == null || configPath.isEmpty() ? configFileName : configPath; + this.initEnv(configPath); + } + + /** + * 配置管理器构造工厂 + * + * @param uEditorConfig 配置文件 + * @return 配置管理器实例或者null + */ + public static com.iformall.ueditor.ConfigManager getInstance(UEditorConfig uEditorConfig, AwsProperty awsProperty, MallResourceService mallResourceService, AliyunOSS aliyunOSS) { + + try { + return new com.iformall.ueditor.ConfigManager(uEditorConfig, awsProperty, mallResourceService, aliyunOSS); + } catch (Exception e) { + System.err.println("UEditor ConfigManager load error~"); + return null; + } + + } + + public AliyunOSS getAliyunOSS() { + return aliyunOSS; + } + + public void setAliyunOSS(AliyunOSS aliyunOSS) { + this.aliyunOSS = aliyunOSS; + } + + public MallResourceService getMallResourceService() { + return mallResourceService; + } + + public void setMallResourceService(MallResourceService mallResourceService) { + this.mallResourceService = mallResourceService; + } + + // 验证配置文件加载是否正确 + public boolean valid() { + return this.jsonConfig != null; + } + + public JSONObject getAllConfig() { + + return this.jsonConfig; + + } + + public Map getConfig(int type) { + + Map conf = new HashMap(); + String savePath = null; + + try { + switch (type) { + + case ActionMap.UPLOAD_FILE: + conf.put("isBase64", "false"); + conf.put("maxSize", this.jsonConfig.getLong("fileMaxSize")); + conf.put("allowFiles", this.getArray("fileAllowFiles")); + conf.put("fieldName", this.jsonConfig.getString("fileFieldName")); + conf.put("clientRegion", this.awsProperty.getClientRegion()); + conf.put("bucketName", this.awsProperty.getBucketName()); + conf.put("access", this.awsProperty.getAccess()); + conf.put("secret", this.awsProperty.getSecret()); + savePath = this.jsonConfig.getString("filePathFormat"); + break; + + case ActionMap.UPLOAD_IMAGE: + conf.put("isBase64", "false"); + conf.put("maxSize", this.jsonConfig.getLong("imageMaxSize")); + conf.put("allowFiles", this.getArray("imageAllowFiles")); + conf.put("fieldName", this.jsonConfig.getString("imageFieldName")); + conf.put("clientRegion", this.awsProperty.getClientRegion()); + conf.put("bucketName", this.awsProperty.getBucketName()); + conf.put("access", this.awsProperty.getAccess()); + conf.put("secret", this.awsProperty.getSecret()); + savePath = this.jsonConfig.getString("imagePathFormat"); + break; + + case ActionMap.UPLOAD_VIDEO: + conf.put("maxSize", this.jsonConfig.getLong("videoMaxSize")); + conf.put("allowFiles", this.getArray("videoAllowFiles")); + conf.put("fieldName", this.jsonConfig.getString("videoFieldName")); + conf.put("clientRegion", this.awsProperty.getClientRegion()); + conf.put("bucketName", this.awsProperty.getBucketName()); + conf.put("access", this.awsProperty.getAccess()); + conf.put("secret", this.awsProperty.getSecret()); + savePath = this.jsonConfig.getString("videoPathFormat"); + break; + + case ActionMap.UPLOAD_SCRAWL: + conf.put("filename", com.iformall.ueditor.ConfigManager.SCRAWL_FILE_NAME); + conf.put("maxSize", this.jsonConfig.getLong("scrawlMaxSize")); + conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName")); + conf.put("isBase64", "true"); + savePath = this.jsonConfig.getString("scrawlPathFormat"); + break; + + case ActionMap.CATCH_IMAGE: + conf.put("filename", com.iformall.ueditor.ConfigManager.REMOTE_FILE_NAME); + conf.put("filter", this.getArray("catcherLocalDomain")); + conf.put("maxSize", this.jsonConfig.getLong("catcherMaxSize")); + conf.put("allowFiles", this.getArray("catcherAllowFiles")); + conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]"); + savePath = this.jsonConfig.getString("catcherPathFormat"); + break; + + case ActionMap.LIST_IMAGE: + conf.put("allowFiles", this.getArray("imageManagerAllowFiles")); + conf.put("dir", this.jsonConfig.getString("imageManagerListPath")); + conf.put("count", this.jsonConfig.getIntValue("imageManagerListSize")); + break; + + case ActionMap.LIST_FILE: + conf.put("allowFiles", this.getArray("fileManagerAllowFiles")); + conf.put("dir", this.jsonConfig.getString("fileManagerListPath")); + conf.put("count", this.jsonConfig.getIntValue("fileManagerListSize")); + break; + + } + } catch (JSONException e) { + e.printStackTrace(); + } + + conf.put("savePath", savePath); + conf.put("rootPath", uEditorConfig.getUploadPath()); + conf.put("urlPrefix", uEditorConfig.getUrlPrefix()); + return conf; + + } + + private void initEnv(String configPath) throws IOException { + + String configContent = this.readFile(configPath); + + try { + JSONObject jsonConfig = JSON.parseObject(configContent); + //统一url访问前缀 + if (uEditorConfig.getUnified()) { + Set> entrySet = jsonConfig.entrySet(); + for (Map.Entry entry : entrySet) { + String key = entry.getKey(); + if(key.contains("UrlPrefix")) { + jsonConfig.put(key, uEditorConfig.getUrlPrefix()); + } + } + } + this.jsonConfig = jsonConfig; + } catch (Exception e) { + this.jsonConfig = null; + } + + } + + private String[] getArray(String key) throws JSONException { + + JSONArray jsonArray = this.jsonConfig.getJSONArray(key); + String[] result = new String[jsonArray.size()]; + + for (int i = 0, len = jsonArray.size(); i < len; i++) { + result[i] = jsonArray.getString(i); + } + + return result; + + } + + private String readFile(String path) throws IOException { + + StringBuilder builder = new StringBuilder(); + + try { + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path); + InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8"); + BufferedReader bfReader = new BufferedReader(reader); + + String tmpContent = null; + + while ((tmpContent = bfReader.readLine()) != null) { + builder.append(tmpContent); + } + + bfReader.close(); + + } catch (UnsupportedEncodingException e) { + // 忽略 + } + + return this.filter(builder.toString()); + + } + + // 过滤输入字符串, 剔除多行注释以及替换掉反斜杠 + private String filter(String input) { + + return input.replaceAll("/\\*[\\s\\S]*?\\*/", ""); + + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/Encoder.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/Encoder.java new file mode 100644 index 000000000..701b56801 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/Encoder.java @@ -0,0 +1,24 @@ +package com.iformall.controller.ueditor; + +public class Encoder { + + public static String toUnicode ( String input ) { + + StringBuilder builder = new StringBuilder(); + char[] chars = input.toCharArray(); + + for ( char ch : chars ) { + + if ( ch < 256 ) { + builder.append( ch ); + } else { + builder.append( "\\u" + Integer.toHexString( ch& 0xffff ) ); + } + + } + + return builder.toString(); + + } + +} \ No newline at end of file diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/PathFormat.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/PathFormat.java new file mode 100644 index 000000000..c1dc778f1 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/PathFormat.java @@ -0,0 +1,157 @@ +package com.iformall.controller.ueditor; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PathFormat { + + private static final String TIME = "time"; + private static final String FULL_YEAR = "yyyy"; + private static final String YEAR = "yy"; + private static final String MONTH = "mm"; + private static final String DAY = "dd"; + private static final String HOUR = "hh"; + private static final String MINUTE = "ii"; + private static final String SECOND = "ss"; + private static final String RAND = "rand"; + + private static Date currentDate = null; + + public static String parse ( String input ) { + + Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); + Matcher matcher = pattern.matcher(input); + + com.iformall.ueditor.PathFormat.currentDate = new Date(); + + StringBuffer sb = new StringBuffer(); + + while ( matcher.find() ) { + + matcher.appendReplacement(sb, com.iformall.ueditor.PathFormat.getString( matcher.group( 1 ) ) ); + + } + + matcher.appendTail(sb); + + return sb.toString(); + } + + /** + * 格式化路径, 把windows路径替换成标准路径 + * @param input 待格式化的路径 + * @return 格式化后的路径 + */ + public static String format ( String input ) { + + return input.replace( "\\", "/" ); + + } + + public static String parse ( String input, String filename ) { + + Pattern pattern = Pattern.compile( "\\{([^\\}]+)\\}", Pattern.CASE_INSENSITIVE ); + Matcher matcher = pattern.matcher(input); + String matchStr = null; + + com.iformall.ueditor.PathFormat.currentDate = new Date(); + + StringBuffer sb = new StringBuffer(); + + while ( matcher.find() ) { + + matchStr = matcher.group( 1 ); + if ( matchStr.indexOf( "filename" ) != -1 ) { + filename = filename.replace( "$", "\\$" ).replaceAll( "[\\/:*?\"<>|]", "" ); + matcher.appendReplacement(sb, filename ); + } else { + matcher.appendReplacement(sb, com.iformall.ueditor.PathFormat.getString( matchStr ) ); + } + + } + + matcher.appendTail(sb); + + return sb.toString(); + } + + private static String getString ( String pattern ) { + + pattern = pattern.toLowerCase(); + + // time 处理 + if ( pattern.indexOf( com.iformall.ueditor.PathFormat.TIME ) != -1 ) { + return com.iformall.ueditor.PathFormat.getTimestamp(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.FULL_YEAR ) != -1 ) { + return com.iformall.ueditor.PathFormat.getFullYear(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.YEAR ) != -1 ) { + return com.iformall.ueditor.PathFormat.getYear(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.MONTH ) != -1 ) { + return com.iformall.ueditor.PathFormat.getMonth(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.DAY ) != -1 ) { + return com.iformall.ueditor.PathFormat.getDay(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.HOUR ) != -1 ) { + return com.iformall.ueditor.PathFormat.getHour(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.MINUTE ) != -1 ) { + return com.iformall.ueditor.PathFormat.getMinute(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.SECOND ) != -1 ) { + return com.iformall.ueditor.PathFormat.getSecond(); + } else if ( pattern.indexOf( com.iformall.ueditor.PathFormat.RAND ) != -1 ) { + return com.iformall.ueditor.PathFormat.getRandom( pattern ); + } + + return pattern; + + } + + private static String getTimestamp () { + return System.currentTimeMillis() + ""; + } + + private static String getFullYear () { + return new SimpleDateFormat( "yyyy" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getYear () { + return new SimpleDateFormat( "yy" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getMonth () { + return new SimpleDateFormat( "MM" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getDay () { + return new SimpleDateFormat( "dd" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getHour () { + return new SimpleDateFormat( "HH" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getMinute () { + return new SimpleDateFormat( "mm" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getSecond () { + return new SimpleDateFormat( "ss" ).format( com.iformall.ueditor.PathFormat.currentDate ); + } + + private static String getRandom ( String pattern ) { + + int length = 0; + pattern = pattern.split( ":" )[ 1 ].trim(); + + length = Integer.parseInt( pattern ); + + return ( Math.random() + "" ).replace( ".", "" ).substring( 0, length ); + + } + + public static void main(String[] args) { + // TODO Auto-generated method stub + + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/UEditorConfig.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/UEditorConfig.java new file mode 100644 index 000000000..f60b43942 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/UEditorConfig.java @@ -0,0 +1,59 @@ +package com.iformall.controller.ueditor; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Created by pangxiaofeng on 2017/9/27. + */ +@ConfigurationProperties(prefix = "ueditor") +public class UEditorConfig { + + /** + * config.json的文件存放地址 + */ + private String config; + /** + * 是否同统一上传地址:图片上传地址,视频上传地址... + */ + private boolean unified; + /** + * 文件上传路径 + */ + private String uploadPath; + /** + * 文件url前缀 + */ + private String urlPrefix; + + public String getConfig() { + return config; + } + + public void setConfig(String config) { + this.config = config; + } + + public String getUploadPath() { + return uploadPath; + } + + public void setUploadPath(String uploadPath) { + this.uploadPath = uploadPath; + } + + public String getUrlPrefix() { + return urlPrefix; + } + + public void setUrlPrefix(String urlPrefix) { + this.urlPrefix = urlPrefix; + } + + public boolean getUnified() { + return unified; + } + + public void setUnified(boolean unified) { + this.unified = unified; + } +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionMap.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionMap.java new file mode 100644 index 000000000..001213a1b --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionMap.java @@ -0,0 +1,42 @@ +package com.iformall.controller.ueditor.define; + +import java.util.HashMap; +import java.util.Map; + +/** + * 定义请求action类型 + * @author hancong03@baidu.com + * + */ +@SuppressWarnings("serial") +public final class ActionMap { + + public static final Map mapping; + // 获取配置请求 + public static final int CONFIG = 0; + public static final int UPLOAD_IMAGE = 1; + public static final int UPLOAD_SCRAWL = 2; + public static final int UPLOAD_VIDEO = 3; + public static final int UPLOAD_FILE = 4; + public static final int CATCH_IMAGE = 5; + public static final int LIST_FILE = 6; + public static final int LIST_IMAGE = 7; + + static { + mapping = new HashMap(){{ + put( "config", com.iformall.ueditor.define.ActionMap.CONFIG ); + put( "uploadimage", com.iformall.ueditor.define.ActionMap.UPLOAD_IMAGE ); + put( "uploadscrawl", com.iformall.ueditor.define.ActionMap.UPLOAD_SCRAWL ); + put( "uploadvideo", com.iformall.ueditor.define.ActionMap.UPLOAD_VIDEO ); + put( "uploadfile", com.iformall.ueditor.define.ActionMap.UPLOAD_FILE ); + put( "catchimage", com.iformall.ueditor.define.ActionMap.CATCH_IMAGE ); + put( "listfile", com.iformall.ueditor.define.ActionMap.LIST_FILE ); + put( "listimage", com.iformall.ueditor.define.ActionMap.LIST_IMAGE ); + }}; + } + + public static int getType ( String key ) { + return com.iformall.ueditor.define.ActionMap.mapping.get( key ); + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionState.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionState.java new file mode 100644 index 000000000..59bf8e686 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/ActionState.java @@ -0,0 +1,5 @@ +package com.iformall.controller.ueditor.define; + +public enum ActionState { + UNKNOW_ERROR +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/AppInfo.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/AppInfo.java new file mode 100644 index 000000000..77235c629 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/AppInfo.java @@ -0,0 +1,77 @@ +package com.iformall.controller.ueditor.define; + +import java.util.HashMap; +import java.util.Map; + +public final class AppInfo { + + public static final int SUCCESS = 0; + public static final int MAX_SIZE = 1; + public static final int PERMISSION_DENIED = 2; + public static final int FAILED_CREATE_FILE = 3; + public static final int IO_ERROR = 4; + public static final int NOT_MULTIPART_CONTENT = 5; + public static final int PARSE_REQUEST_ERROR = 6; + public static final int NOTFOUND_UPLOAD_DATA = 7; + public static final int NOT_ALLOW_FILE_TYPE = 8; + + public static final int INVALID_ACTION = 101; + public static final int CONFIG_ERROR = 102; + + public static final int PREVENT_HOST = 201; + public static final int CONNECTION_ERROR = 202; + public static final int REMOTE_FAIL = 203; + + public static final int NOT_DIRECTORY = 301; + public static final int NOT_EXIST = 302; + + public static final int ILLEGAL = 401; + + public static Map info = new HashMap(){{ + + put( com.iformall.ueditor.define.AppInfo.SUCCESS, "SUCCESS" ); + + // 无效的Action + put( com.iformall.ueditor.define.AppInfo.INVALID_ACTION, "\u65E0\u6548\u7684Action" ); + // 配置文件初始化失败 + put( com.iformall.ueditor.define.AppInfo.CONFIG_ERROR, "\u914D\u7F6E\u6587\u4EF6\u521D\u59CB\u5316\u5931\u8D25" ); + // 抓取远程图片失败 + put( com.iformall.ueditor.define.AppInfo.REMOTE_FAIL, "\u6293\u53D6\u8FDC\u7A0B\u56FE\u7247\u5931\u8D25" ); + + // 被阻止的远程主机 + put( com.iformall.ueditor.define.AppInfo.PREVENT_HOST, "\u88AB\u963B\u6B62\u7684\u8FDC\u7A0B\u4E3B\u673A" ); + // 远程连接出错 + put( com.iformall.ueditor.define.AppInfo.CONNECTION_ERROR, "\u8FDC\u7A0B\u8FDE\u63A5\u51FA\u9519" ); + + // "文件大小超出限制" + put( com.iformall.ueditor.define.AppInfo.MAX_SIZE, "\u6587\u4ef6\u5927\u5c0f\u8d85\u51fa\u9650\u5236" ); + // 权限不足, 多指写权限 + put( com.iformall.ueditor.define.AppInfo.PERMISSION_DENIED, "\u6743\u9650\u4E0D\u8DB3" ); + // 创建文件失败 + put( com.iformall.ueditor.define.AppInfo.FAILED_CREATE_FILE, "\u521B\u5EFA\u6587\u4EF6\u5931\u8D25" ); + // IO错误 + put( com.iformall.ueditor.define.AppInfo.IO_ERROR, "IO\u9519\u8BEF" ); + // 上传表单不是multipart/form-data类型 + put( com.iformall.ueditor.define.AppInfo.NOT_MULTIPART_CONTENT, "\u4E0A\u4F20\u8868\u5355\u4E0D\u662Fmultipart/form-data\u7C7B\u578B" ); + // 解析上传表单错误 + put( com.iformall.ueditor.define.AppInfo.PARSE_REQUEST_ERROR, "\u89E3\u6790\u4E0A\u4F20\u8868\u5355\u9519\u8BEF" ); + // 未找到上传数据 + put( com.iformall.ueditor.define.AppInfo.NOTFOUND_UPLOAD_DATA, "\u672A\u627E\u5230\u4E0A\u4F20\u6570\u636E" ); + // 不允许的文件类型 + put( com.iformall.ueditor.define.AppInfo.NOT_ALLOW_FILE_TYPE, "\u4E0D\u5141\u8BB8\u7684\u6587\u4EF6\u7C7B\u578B" ); + + // 指定路径不是目录 + put( com.iformall.ueditor.define.AppInfo.NOT_DIRECTORY, "\u6307\u5B9A\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55" ); + // 指定路径并不存在 + put( com.iformall.ueditor.define.AppInfo.NOT_EXIST, "\u6307\u5B9A\u8DEF\u5F84\u5E76\u4E0D\u5B58\u5728" ); + + // callback参数名不合法 + put( com.iformall.ueditor.define.AppInfo.ILLEGAL, "Callback\u53C2\u6570\u540D\u4E0D\u5408\u6CD5" ); + + }}; + + public static String getStateInfo ( int key ) { + return com.iformall.ueditor.define.AppInfo.info.get( key ); + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/BaseState.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/BaseState.java new file mode 100644 index 000000000..fbf6703e7 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/BaseState.java @@ -0,0 +1,92 @@ +package com.iformall.controller.ueditor.define; + +import com.iformall.ueditor.Encoder; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.State; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +public class BaseState implements State { + + private boolean state = false; + private String info = null; + + private Map infoMap = new HashMap(); + + public BaseState () { + this.state = true; + } + + public BaseState ( boolean state ) { + this.setState( state ); + } + + public BaseState ( boolean state, String info ) { + this.setState( state ); + this.info = info; + } + + public BaseState ( boolean state, int infoCode ) { + this.setState( state ); + this.info = AppInfo.getStateInfo( infoCode ); + } + + public boolean isSuccess () { + return this.state; + } + + public void setState ( boolean state ) { + this.state = state; + } + + public void setInfo ( String info ) { + this.info = info; + } + + public void setInfo ( int infoCode ) { + this.info = AppInfo.getStateInfo( infoCode ); + } + + @Override + public String toJSONString() { + return this.toString(); + } + + public String toString () { + + String key = null; + String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; + + StringBuilder builder = new StringBuilder(); + + builder.append( "{\"state\": \"" + stateVal + "\"" ); + + Iterator iterator = this.infoMap.keySet().iterator(); + + while ( iterator.hasNext() ) { + + key = iterator.next(); + + builder.append( ",\"" + key + "\": \"" + this.infoMap.get(key) + "\"" ); + + } + + builder.append( "}" ); + + return Encoder.toUnicode( builder.toString() ); + + } + + @Override + public void putInfo(String name, String val) { + this.infoMap.put(name, val); + } + + @Override + public void putInfo(String name, long val) { + this.putInfo(name, val+""); + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/FileType.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/FileType.java new file mode 100644 index 000000000..4cfbae204 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/FileType.java @@ -0,0 +1,31 @@ +package com.iformall.controller.ueditor.define; + +import java.util.HashMap; +import java.util.Map; + +public class FileType { + + public static final String JPG = "JPG"; + + private static final Map types = new HashMap(){{ + + put( com.iformall.ueditor.define.FileType.JPG, ".jpg" ); + + }}; + + public static String getSuffix ( String key ) { + return com.iformall.ueditor.define.FileType.types.get( key ); + } + + /** + * 根据给定的文件名,获取其后缀信息 + * @param filename + * @return + */ + public static String getSuffixByFilename ( String filename ) { + + return filename.substring( filename.lastIndexOf( "." ) ).toLowerCase(); + + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MIMEType.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MIMEType.java new file mode 100644 index 000000000..70614f65d --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MIMEType.java @@ -0,0 +1,20 @@ +package com.iformall.controller.ueditor.define; + +import java.util.HashMap; +import java.util.Map; + +public class MIMEType { + + public static final Map types = new HashMap(){{ + put( "image/gif", ".gif" ); + put( "image/jpeg", ".jpg" ); + put( "image/jpg", ".jpg" ); + put( "image/png", ".png" ); + put( "image/bmp", ".bmp" ); + }}; + + public static String getSuffix ( String mime ) { + return com.iformall.ueditor.define.MIMEType.types.get( mime ); + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MultiState.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MultiState.java new file mode 100644 index 000000000..8ecf4e972 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/MultiState.java @@ -0,0 +1,110 @@ +package com.iformall.controller.ueditor.define; + +import com.iformall.ueditor.Encoder; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.State; + +import java.util.*; + +/** + * 多状态集合状态 + * 其包含了多个状态的集合, 其本身自己也是一个状态 + * @author hancong03@baidu.com + * + */ +public class MultiState implements State { + + private boolean state = false; + private String info = null; + private Map intMap = new HashMap(); + private Map infoMap = new HashMap(); + private List stateList = new ArrayList(); + + public MultiState ( boolean state ) { + this.state = state; + } + + public MultiState ( boolean state, String info ) { + this.state = state; + this.info = info; + } + + public MultiState ( boolean state, int infoKey ) { + this.state = state; + this.info = AppInfo.getStateInfo( infoKey ); + } + + @Override + public boolean isSuccess() { + return this.state; + } + + public void addState ( State state ) { + stateList.add( state.toJSONString() ); + } + + /** + * 该方法调用无效果 + */ + @Override + public void putInfo(String name, String val) { + this.infoMap.put(name, val); + } + + @Override + public String toJSONString() { + + String stateVal = this.isSuccess() ? AppInfo.getStateInfo( AppInfo.SUCCESS ) : this.info; + + StringBuilder builder = new StringBuilder(); + + builder.append( "{\"state\": \"" + stateVal + "\"" ); + + // 数字转换 + Iterator iterator = this.intMap.keySet().iterator(); + + while ( iterator.hasNext() ) { + + stateVal = iterator.next(); + + builder.append( ",\""+ stateVal +"\": " + this.intMap.get( stateVal ) ); + + } + + iterator = this.infoMap.keySet().iterator(); + + while ( iterator.hasNext() ) { + + stateVal = iterator.next(); + + builder.append( ",\""+ stateVal +"\": \"" + this.infoMap.get( stateVal ) + "\"" ); + + } + + builder.append( ", list: [" ); + + + iterator = this.stateList.iterator(); + + while ( iterator.hasNext() ) { + + builder.append( iterator.next() + "," ); + + } + + if ( this.stateList.size() > 0 ) { + builder.deleteCharAt( builder.length() - 1 ); + } + + builder.append( " ]}" ); + + return Encoder.toUnicode( builder.toString() ); + + } + + @Override + public void putInfo(String name, long val) { + this.intMap.put( name, val ); + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/State.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/State.java new file mode 100644 index 000000000..263c73c8a --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/define/State.java @@ -0,0 +1,18 @@ +package com.iformall.controller.ueditor.define; + +/** + * 处理状态接口 + * @author hancong03@baidu.com + * + */ +public interface State { + + public boolean isSuccess(); + + public void putInfo(String name, String val); + + public void putInfo(String name, long val); + + public String toJSONString(); + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/FileManager.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/FileManager.java new file mode 100644 index 000000000..e1e7a2e28 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/FileManager.java @@ -0,0 +1,111 @@ +package com.iformall.controller.ueditor.hunter; + +import com.iformall.ueditor.PathFormat; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.MultiState; +import com.iformall.ueditor.define.State; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +public class FileManager { + + private String dir = null; + private String rootPath = null; + private String[] allowFiles = null; + private int count = 0; + + public FileManager(Map conf) { + + this.rootPath = (String) conf.get("rootPath"); + this.dir = this.rootPath + (String) conf.get("dir"); + this.allowFiles = this.getAllowFiles(conf.get("allowFiles")); + this.count = (Integer) conf.get("count"); + + } + + public State listFile(int index) { + + File dir = new File(this.dir); + State state = null; + + if (!dir.exists()) { + return new BaseState(false, AppInfo.NOT_EXIST); + } + + if (!dir.isDirectory()) { + return new BaseState(false, AppInfo.NOT_DIRECTORY); + } + + Collection list = FileUtils.listFiles(dir, this.allowFiles, true); + + if (index < 0 || index > list.size()) { + state = new MultiState(true); + } else { + Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count); + state = this.getState(fileList); + } + + state.putInfo("start", index); + state.putInfo("total", list.size()); + + return state; + + } + + private State getState(Object[] files) { + + MultiState state = new MultiState(true); + BaseState fileState = null; + + File file = null; + + for (Object obj : files) { + if (obj == null) { + break; + } + file = (File) obj; + fileState = new BaseState(true); + fileState.putInfo("url", PathFormat.format(this.getPath(file))); + state.addState(fileState); + } + + return state; + + } + + private String getPath(File file) { + + String path = file.getAbsolutePath(); + path = PathFormat.format(path); + return path.replace(this.rootPath, "/"); + + } + + private String[] getAllowFiles(Object fileExt) { + + String[] exts = null; + String ext = null; + + if (fileExt == null) { + return new String[0]; + } + + exts = (String[]) fileExt; + + for (int i = 0, len = exts.length; i < len; i++) { + + ext = exts[i]; + exts[i] = ext.replace(".", ""); + + } + + return exts; + + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/ImageHunter.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/ImageHunter.java new file mode 100644 index 000000000..5793c8d38 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/hunter/ImageHunter.java @@ -0,0 +1,140 @@ +package com.iformall.controller.ueditor.hunter; + +import com.iformall.ueditor.PathFormat; +import com.iformall.ueditor.define.*; +import com.iformall.ueditor.upload.StorageManager; + +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 图片抓取器 + * @author hancong03@baidu.com + * + */ +public class ImageHunter { + + private String filename = null; + private String savePath = null; + private String rootPath = null; + private List allowTypes = null; + private long maxSize = -1; + + private List filters = null; + + public ImageHunter ( Map conf ) { + + this.filename = (String)conf.get( "filename" ); + this.savePath = (String)conf.get( "savePath" ); + this.rootPath = (String)conf.get( "rootPath" ); + this.maxSize = (Long)conf.get( "maxSize" ); + this.allowTypes = Arrays.asList( (String[])conf.get( "allowFiles" ) ); + this.filters = Arrays.asList( (String[])conf.get( "filter" ) ); + + } + + public State capture (String[] list ) { + + MultiState state = new MultiState( true ); + + for ( String source : list ) { + state.addState( captureRemoteData( source ) ); + } + + return state; + + } + + public State captureRemoteData ( String urlStr ) { + + HttpURLConnection connection = null; + URL url = null; + String suffix = null; + + try { + url = new URL( urlStr ); + + if ( !validHost( url.getHost() ) ) { + return new BaseState( false, AppInfo.PREVENT_HOST ); + } + + connection = (HttpURLConnection) url.openConnection(); + + connection.setInstanceFollowRedirects( true ); + connection.setUseCaches( true ); + + if ( !validContentState( connection.getResponseCode() ) ) { + return new BaseState( false, AppInfo.CONNECTION_ERROR ); + } + + suffix = MIMEType.getSuffix( connection.getContentType() ); + + if ( !validFileType( suffix ) ) { + return new BaseState( false, AppInfo.NOT_ALLOW_FILE_TYPE ); + } + + if ( !validFileSize( connection.getContentLength() ) ) { + return new BaseState( false, AppInfo.MAX_SIZE ); + } + + String savePath = this.getPath( this.savePath, this.filename, suffix ); + String physicalPath = this.rootPath + savePath; + + State state = StorageManager.saveFileByInputStream( connection.getInputStream(), physicalPath ); + + if ( state.isSuccess() ) { + state.putInfo( "url", PathFormat.format( savePath ) ); + state.putInfo( "source", urlStr ); + } + + return state; + + } catch ( Exception e ) { + return new BaseState( false, AppInfo.REMOTE_FAIL ); + } + + } + + private String getPath ( String savePath, String filename, String suffix ) { + + return PathFormat.parse( savePath + suffix, filename ); + + } + + private boolean validHost ( String hostname ) { + try { + InetAddress ip = InetAddress.getByName(hostname); + + if (ip.isSiteLocalAddress()) { + return false; + } + } catch (UnknownHostException e) { + return false; + } + + return !filters.contains( hostname ); + + } + + private boolean validContentState ( int code ) { + + return HttpURLConnection.HTTP_OK == code; + + } + + private boolean validFileType ( String type ) { + + return this.allowTypes.contains( type ); + + } + + private boolean validFileSize ( int size ) { + return size < this.maxSize; + } + +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Base64Uploader.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Base64Uploader.java new file mode 100644 index 000000000..43854fdb7 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Base64Uploader.java @@ -0,0 +1,52 @@ +package com.iformall.controller.ueditor.upload; + +import com.iformall.ueditor.PathFormat; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.FileType; +import com.iformall.ueditor.define.State; +import com.iformall.ueditor.upload.StorageManager; +import org.apache.commons.codec.binary.Base64; + +import java.util.Map; + +public final class Base64Uploader { + + public static State save(String content, Map conf) { + + byte[] data = decode(content); + + long maxSize = ((Long) conf.get("maxSize")).longValue(); + + if (!validSize(data, maxSize)) { + return new BaseState(false, AppInfo.MAX_SIZE); + } + + String suffix = FileType.getSuffix("JPG"); + + String savePath = PathFormat.parse((String) conf.get("savePath"), + (String) conf.get("filename")); + + savePath = savePath + suffix; + String physicalPath = (String) conf.get("rootPath") + savePath; + + State storageState = StorageManager.saveBinaryFile(data, physicalPath); + + if (storageState.isSuccess()) { + storageState.putInfo("url", PathFormat.format(savePath)); + storageState.putInfo("type", suffix); + storageState.putInfo("original", ""); + } + + return storageState; + } + + private static byte[] decode(String content) { + return Base64.decodeBase64(content); + } + + private static boolean validSize(byte[] data, long length) { + return data.length <= length; + } + +} \ No newline at end of file diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/BinaryUploader.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/BinaryUploader.java new file mode 100644 index 000000000..79bd28c0c --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/BinaryUploader.java @@ -0,0 +1,71 @@ +package com.iformall.controller.ueditor.upload; + +import com.iformall.ueditor.PathFormat; +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.FileType; +import com.iformall.ueditor.define.State; +import com.iformall.ueditor.upload.StorageManager; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class BinaryUploader { + + public static final State save(HttpServletRequest request, Map conf) { + if (!ServletFileUpload.isMultipartContent(request)) { + return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT); + } + + MultipartFile file = ((MultipartHttpServletRequest) request).getFile("upfile"); + try { + if (file == null) { + return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA); + } + + String savePath = (String) conf.get("savePath"); + String originFileName = file.getOriginalFilename(); + String suffix = FileType.getSuffixByFilename(file.getOriginalFilename()); + + originFileName = originFileName.substring(0, + originFileName.length() - suffix.length()); + savePath = savePath + suffix; + + long maxSize = ((Long) conf.get("maxSize")).longValue(); + + if (!validType(suffix, (String[]) conf.get("allowFiles"))) { + return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE); + } + + savePath = PathFormat.parse(savePath, originFileName); + String physicalPath = (String) conf.get("rootPath") + savePath; + + InputStream is = file.getInputStream(); + State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize); + is.close(); + + if (storageState.isSuccess()) { + storageState.putInfo("url", PathFormat.format(savePath)); + storageState.putInfo("local", physicalPath); + storageState.putInfo("type", suffix); + storageState.putInfo("original", originFileName + suffix); + } + return storageState; + } catch (IOException e) { + } + return new BaseState(false, AppInfo.IO_ERROR); + } + + private static boolean validType(String type, String[] allowTypes) { + List list = Arrays.asList(allowTypes); + + return list.contains(type); + } +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/StorageManager.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/StorageManager.java new file mode 100644 index 000000000..f000d80aa --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/StorageManager.java @@ -0,0 +1,148 @@ +package com.iformall.controller.ueditor.upload; + +import com.iformall.ueditor.define.AppInfo; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.State; +import org.apache.commons.io.FileUtils; + +import java.io.*; + +public class StorageManager { + public static final int BUFFER_SIZE = 8192; + + public StorageManager() { + } + + public static State saveBinaryFile(byte[] data, String path) { + File file = new File(path); + + State state = valid(file); + + if (!state.isSuccess()) { + return state; + } + + try { + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(file)); + bos.write(data); + bos.flush(); + bos.close(); + } catch (IOException ioe) { + return new BaseState(false, AppInfo.IO_ERROR); + } + + state = new BaseState(true, file.getAbsolutePath()); + state.putInfo("size", data.length); + state.putInfo("title", file.getName()); + return state; + } + + public static State saveFileByInputStream(InputStream is, String path, long maxSize) { + State state = null; + + File tmpFile = getTmpFile(); + + byte[] dataBuf = new byte[2048]; + BufferedInputStream bis = new BufferedInputStream(is, com.iformall.ueditor.upload.StorageManager.BUFFER_SIZE); + + try { + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(tmpFile), com.iformall.ueditor.upload.StorageManager.BUFFER_SIZE); + + int count = 0; + while ((count = bis.read(dataBuf)) != -1) { + bos.write(dataBuf, 0, count); + } + bos.flush(); + bos.close(); + + if (tmpFile.length() > maxSize) { + tmpFile.delete(); + return new BaseState(false, AppInfo.MAX_SIZE); + } + + state = saveTmpFile(tmpFile, path); + + if (!state.isSuccess()) { + tmpFile.delete(); + } + + return state; + + } catch (IOException e) { + } + return new BaseState(false, AppInfo.IO_ERROR); + } + + public static State saveFileByInputStream(InputStream is, String path) { + State state = null; + + File tmpFile = getTmpFile(); + + byte[] dataBuf = new byte[2048]; + BufferedInputStream bis = new BufferedInputStream(is, com.iformall.ueditor.upload.StorageManager.BUFFER_SIZE); + + try { + BufferedOutputStream bos = new BufferedOutputStream( + new FileOutputStream(tmpFile), com.iformall.ueditor.upload.StorageManager.BUFFER_SIZE); + + int count = 0; + while ((count = bis.read(dataBuf)) != -1) { + bos.write(dataBuf, 0, count); + } + bos.flush(); + bos.close(); + + state = saveTmpFile(tmpFile, path); + + if (!state.isSuccess()) { + tmpFile.delete(); + } + + return state; + } catch (IOException e) { + } + return new BaseState(false, AppInfo.IO_ERROR); + } + + private static File getTmpFile() { + File tmpDir = FileUtils.getTempDirectory(); + String tmpFileName = (Math.random() * 10000 + "").replace(".", ""); + return new File(tmpDir, tmpFileName); + } + + private static State saveTmpFile(File tmpFile, String path) { + State state = null; + File targetFile = new File(path); + + if (targetFile.canWrite()) { + return new BaseState(false, AppInfo.PERMISSION_DENIED); + } + try { + FileUtils.moveFile(tmpFile, targetFile); + } catch (IOException e) { + return new BaseState(false, AppInfo.IO_ERROR); + } + + state = new BaseState(true); + state.putInfo("size", targetFile.length()); + state.putInfo("title", targetFile.getName()); + + return state; + } + + private static State valid(File file) { + File parentPath = file.getParentFile(); + + if ((!parentPath.exists()) && (!parentPath.mkdirs())) { + return new BaseState(false, AppInfo.FAILED_CREATE_FILE); + } + + if (!parentPath.canWrite()) { + return new BaseState(false, AppInfo.PERMISSION_DENIED); + } + + return new BaseState(true); + } +} diff --git a/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Uploader.java b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Uploader.java new file mode 100644 index 000000000..693e0c312 --- /dev/null +++ b/mallinkTTAdmin/src/main/java/com/iformall/controller/ueditor/upload/Uploader.java @@ -0,0 +1,93 @@ +package com.iformall.controller.ueditor.upload; + +import com.iformall.common.ResultData; +import com.iformall.domain.po.MallResource; +import com.iformall.domain.po.base.TenantEntity; +import com.iformall.file.aliyun.AliyunOSS; +import com.iformall.service.MallResourceService; +import com.iformall.shiro.UserSession; +import com.iformall.ueditor.define.BaseState; +import com.iformall.ueditor.define.State; +import com.iformall.ueditor.upload.Base64Uploader; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.session.Session; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; + +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Map; + +public class Uploader { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private HttpServletRequest request = null; + private Map conf = null; + private MallResourceService mallResourceService = null; + + private AliyunOSS aliyunOSS; + + public Uploader(HttpServletRequest request, Map conf, MallResourceService mallResourceService, AliyunOSS aliyunOSS) { + this.request = request; + this.conf = conf; + this.mallResourceService = mallResourceService; + this.aliyunOSS = aliyunOSS; + } + + public final State doExec() { + String filedName = (String) this.conf.get("fieldName"); + State state = null; + + if ("true".equals(this.conf.get("isBase64"))) { + state = Base64Uploader.save(this.request.getParameter(filedName), + this.conf); + } else { + MultipartFile multiReq= ((MultipartHttpServletRequest) this.request).getFile("upfile"); + Session session = SecurityUtils.getSubject().getSession(); + String tenantId = (String)session.getAttribute(UserSession.tenantId); + String parentTenantId = (String)session.getAttribute(UserSession.parentTenantId); + if(StringUtils.isBlank(tenantId)){ + tenantId = parentTenantId; + parentTenantId = ""; + } + TenantEntity tenantEntity = new TenantEntity(); + tenantEntity.setTenantId(tenantId); + tenantEntity.setParentTenantId(parentTenantId); + if (StringUtils.isBlank(tenantId)) { + logger.error("TENANT is null"); + } + + int dot = multiReq.getOriginalFilename().lastIndexOf('.'); + String fileFormat = ""; + if (dot >= 0) { + fileFormat = multiReq.getOriginalFilename().substring(dot, multiReq.getOriginalFilename().length()); + } + + state = new BaseState(true); + state.putInfo("size", multiReq.getSize()); + state.putInfo("title", filedName); + + try { + + ResultData data = aliyunOSS.uploadFile(tenantEntity.getTenantId(), fileFormat, multiReq.getInputStream()); + Map map = (Map) data.data; + state.putInfo("url",map.get("url")); + + MallResource mr = new MallResource(); + mr.updateTenantInfo(tenantEntity); + mr.setBucket(map.get("bucketName")); + mr.setUrl(map.get("url")); + + mallResourceService.saveOrUpdate(mr); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + return state; + } +} diff --git a/mallinkVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java b/mallinkVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java index 97728a180..fb8a505b2 100644 --- a/mallinkVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java +++ b/mallinkVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java @@ -50,7 +50,6 @@ public class AliyunVideoExcutor implements VideoExcutor { UploadVideoResponse response =AliyunVedioUpload.uploadVideo(config.getAccessKeyId(), config.getAccessKeySecret(),config.getRegionId(), title, localFile,redisTemplate); if (response.isSuccess()) { result.setVideoId(response.getVideoId()); - setVideUploadResult(result,response.getVideoId()); result.setVideoUrl(getUrlByVeidoId(response.getVideoId())); result.setSuccess(true); }else { @@ -92,7 +91,8 @@ public class AliyunVideoExcutor implements VideoExcutor { log.info(response.toString()); if (response.isSuccess()) { result.setVideoId(response.getVideoId()); - result.setVideoUrl(getUrlByVeidoId(response.getVideoId())); + setVideUploadResult(result,response.getVideoId()); +// result.setVideoUrl(getUrlByVeidoId(response.getVideoId())); result.setSuccess(true); } else { //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因 result.setSuccess(false);