Commit f07cde2a by java-李谡

代码规范

parent 3f43a184
package com.baidu.ueditor.core; package com.baidu.ueditor.core;
import java.io.BufferedReader; import com.baidu.ueditor.define.ActionMap;
import java.io.File; import com.ejweb.core.utils.FileManipulation;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import com.baidu.ueditor.define.ActionMap; import java.io.*;
import com.ejweb.core.utils.FileManipulation; import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/** /**
* 配置管理器 * 配置管理器
* @author hancong03@baidu.com
* *
* @author hancong03@baidu.com
*/ */
public final class ConfigManager { public final class ConfigManager {
private final String rootPath; private final String rootPath;
private final String originalPath; private final String originalPath;
// private final String contextPath; // private final String contextPath;
private static final String configFileName = "ueditor.json"; private static final String configFileName = "ueditor.json";
private String parentPath = null; private String parentPath = null;
private JSONObject jsonConfig = null; private JSONObject jsonConfig = null;
...@@ -39,15 +32,15 @@ public final class ConfigManager { ...@@ -39,15 +32,15 @@ public final class ConfigManager {
/* /*
* 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件 * 通过一个给定的路径构建一个配置管理器, 该管理器要求地址路径所在目录下必须存在config.properties文件
*/ */
private ConfigManager ( String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException { private ConfigManager(String rootPath, String contextPath, String uri) throws FileNotFoundException, IOException {
rootPath = rootPath.replace( "\\", "/" ); rootPath = rootPath.replace("\\", "/");
this.rootPath = rootPath; this.rootPath = rootPath;
// this.contextPath = contextPath; // this.contextPath = contextPath;
if ( contextPath.length() > 0 ) { if (contextPath.length() > 0) {
this.originalPath = this.rootPath + uri.substring( contextPath.length() ); this.originalPath = this.rootPath + uri.substring(contextPath.length());
} else { } else {
this.originalPath = this.rootPath + uri; this.originalPath = this.rootPath + uri;
} }
...@@ -58,181 +51,175 @@ public final class ConfigManager { ...@@ -58,181 +51,175 @@ public final class ConfigManager {
/** /**
* 配置管理器构造工厂 * 配置管理器构造工厂
*
* @param rootPath 服务器根路径 * @param rootPath 服务器根路径
* @param contextPath 服务器所在项目路径 * @param contextPath 服务器所在项目路径
* @param uri 当前访问的uri * @param uri 当前访问的uri
* @return 配置管理器实例或者null * @return 配置管理器实例或者null
*/ */
public static ConfigManager getInstance ( String rootPath, String contextPath, String uri ) { public static ConfigManager getInstance(String rootPath, String contextPath, String uri) {
try { try {
return new ConfigManager(rootPath, contextPath, uri); return new ConfigManager(rootPath, contextPath, uri);
} catch ( Exception e ) { } catch (Exception e) {
return null; return null;
} }
} }
// 验证配置文件加载是否正确 // 验证配置文件加载是否正确
public boolean valid () { public boolean valid() {
return this.jsonConfig != null; return this.jsonConfig != null;
} }
public JSONObject getAllConfig () { public JSONObject getAllConfig() {
return this.jsonConfig; return this.jsonConfig;
} }
public Map<String, Object> getConfig ( int type ) { public Map<String, Object> getConfig(int type) {
Map<String, Object> conf = new HashMap<String, Object>(); Map<String, Object> conf = new HashMap<String, Object>();
String savePath = null; String savePath = null;
switch ( type ) { switch (type) {
case ActionMap.UPLOAD_FILE: case ActionMap.UPLOAD_FILE:
conf.put( "isBase64", "false" ); conf.put("isBase64", "false");
conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) ); conf.put("maxSize", this.jsonConfig.getLong("fileMaxSize"));
conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) ); conf.put("allowFiles", this.getArray("fileAllowFiles"));
conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) ); conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
savePath = this.jsonConfig.getString( "filePathFormat" ); savePath = this.jsonConfig.getString("filePathFormat");
break; break;
case ActionMap.UPLOAD_IMAGE: case ActionMap.UPLOAD_IMAGE:
conf.put( "isBase64", "false" ); conf.put("isBase64", "false");
conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) ); conf.put("maxSize", this.jsonConfig.getLong("imageMaxSize"));
conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) ); conf.put("allowFiles", this.getArray("imageAllowFiles"));
conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) ); conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
savePath = this.jsonConfig.getString( "imagePathFormat" ); savePath = this.jsonConfig.getString("imagePathFormat");
break; break;
case ActionMap.UPLOAD_VIDEO: case ActionMap.UPLOAD_VIDEO:
conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) ); conf.put("maxSize", this.jsonConfig.getLong("videoMaxSize"));
conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) ); conf.put("allowFiles", this.getArray("videoAllowFiles"));
conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) ); conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
savePath = this.jsonConfig.getString( "videoPathFormat" ); savePath = this.jsonConfig.getString("videoPathFormat");
break; break;
case ActionMap.UPLOAD_SCRAWL: case ActionMap.UPLOAD_SCRAWL:
conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME ); conf.put("filename", ConfigManager.SCRAWL_FILE_NAME);
conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) ); conf.put("maxSize", this.jsonConfig.getLong("scrawlMaxSize"));
conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) ); conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
conf.put( "isBase64", "true" ); conf.put("isBase64", "true");
savePath = this.jsonConfig.getString( "scrawlPathFormat" ); savePath = this.jsonConfig.getString("scrawlPathFormat");
break; break;
case ActionMap.CATCH_IMAGE: case ActionMap.CATCH_IMAGE:
conf.put( "filename", ConfigManager.REMOTE_FILE_NAME ); conf.put("filename", ConfigManager.REMOTE_FILE_NAME);
conf.put( "filter", this.getArray( "catcherLocalDomain" ) ); conf.put("filter", this.getArray("catcherLocalDomain"));
conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) ); conf.put("maxSize", this.jsonConfig.getLong("catcherMaxSize"));
conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) ); conf.put("allowFiles", this.getArray("catcherAllowFiles"));
conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" ); conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
savePath = this.jsonConfig.getString( "catcherPathFormat" ); savePath = this.jsonConfig.getString("catcherPathFormat");
break; break;
case ActionMap.LIST_IMAGE: case ActionMap.LIST_IMAGE:
conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) ); conf.put("allowFiles", this.getArray("imageManagerAllowFiles"));
conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) ); conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) ); conf.put("count", this.jsonConfig.getInt("imageManagerListSize"));
break; break;
case ActionMap.LIST_FILE: case ActionMap.LIST_FILE:
conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) ); conf.put("allowFiles", this.getArray("fileManagerAllowFiles"));
conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) ); conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) ); conf.put("count", this.jsonConfig.getInt("fileManagerListSize"));
break; break;
} }
conf.put( "savePath", savePath ); conf.put("savePath", savePath);
conf.put( "rootPath", this.rootPath ); conf.put("rootPath", this.rootPath);
return conf; return conf;
} }
private void initEnv () throws FileNotFoundException, IOException { private void initEnv() throws FileNotFoundException, IOException {
// 文件验证 // 文件验证
String path=this.originalPath; String path = this.originalPath;
path= FileManipulation.validateFile2(path); path = FileManipulation.validateFile2(path);
File file = new File( FileManipulation.validateFile2(path) ); File file = new File(FileManipulation.validateFile2(path));
if ( !file.isAbsolute() ) { if (!file.isAbsolute()) {
file = new File( file.getAbsolutePath() ); file = new File(file.getAbsolutePath());
} }
this.parentPath = file.getParent(); this.parentPath = file.getParent();
// String configContent = this.readFile( this.getConfigPath() ); try {
try{
// JSONObject jsonConfig = new JSONObject( configContent );
// this.jsonConfig = jsonConfig;
File cfg = new File(this.getConfigPath()); File cfg = new File(this.getConfigPath());
if(cfg.exists() && cfg.isFile()){ if (cfg.exists() && cfg.isFile()) {
String configContent = this.readFile( this.getConfigPath() ); String configContent = this.readFile(this.getConfigPath());
// System.out.println(configContent); this.jsonConfig = new JSONObject(configContent);
this.jsonConfig = new JSONObject( configContent );
} else { } else {
URL in = ConfigManager.class.getClassLoader().getResource(ConfigManager.configFileName); URL in = ConfigManager.class.getClassLoader().getResource(ConfigManager.configFileName);
// System.out.println(in.getPath()); String configContent = this.readFile(in.getPath());
String configContent = this.readFile( in.getPath() );
this.jsonConfig = new JSONObject(configContent); this.jsonConfig = new JSONObject(configContent);
} }
} catch ( Exception e ) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
this.jsonConfig = null; this.jsonConfig = null;
} }
} }
private String getConfigPath () { private String getConfigPath() {
return this.parentPath + File.separator + ConfigManager.configFileName; return this.parentPath + File.separator + ConfigManager.configFileName;
} }
private String[] getArray ( String key ) { private String[] getArray(String key) {
JSONArray jsonArray = this.jsonConfig.getJSONArray( key ); JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
String[] result = new String[ jsonArray.length() ]; String[] result = new String[jsonArray.length()];
for ( int i = 0, len = jsonArray.length(); i < len; i++ ) { for (int i = 0, len = jsonArray.length(); i < len; i++) {
result[i] = jsonArray.getString( i ); result[i] = jsonArray.getString(i);
} }
return result; return result;
} }
private String readFile ( String path ) throws IOException { private String readFile(String path) throws IOException {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
try { try {
InputStreamReader reader = new InputStreamReader( new FileInputStream( path ), "UTF-8" ); InputStreamReader reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
BufferedReader bfReader = new BufferedReader( reader ); BufferedReader bfReader = new BufferedReader(reader);
String tmpContent = null; String tmpContent = null;
while ( ( tmpContent = bfReader.readLine() ) != null ) { while ((tmpContent = bfReader.readLine()) != null) {
builder.append( tmpContent ); builder.append(tmpContent);
} }
bfReader.close(); bfReader.close();
} catch ( UnsupportedEncodingException e ) { } catch (UnsupportedEncodingException e) {
// 忽略 // 忽略
} }
return this.filter( builder.toString() ); return this.filter(builder.toString());
} }
// 过滤输入字符串, 剔除多行注释以及替换掉反斜杠 private String filter(String input) {
private String filter ( String input ) {
return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" ); return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
} }
......
package com.baidu.ueditor.define;
public enum ActionState {
UNKNOW_ERROR
}
package com.baidu.ueditor.hunter; package com.baidu.ueditor.hunter;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import com.baidu.ueditor.core.PathFormat; import com.baidu.ueditor.core.PathFormat;
import com.baidu.ueditor.define.AppInfo; import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState; import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState; import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State; import com.baidu.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 { public class FileManager {
...@@ -20,96 +19,95 @@ public class FileManager { ...@@ -20,96 +19,95 @@ public class FileManager {
private String[] allowFiles = null; private String[] allowFiles = null;
private int count = 0; private int count = 0;
public FileManager ( Map<String, Object> conf ) { public FileManager(Map<String, Object> conf) {
this.rootPath = (String)conf.get( "rootPath" ); this.rootPath = (String) conf.get("rootPath");
this.dir = this.rootPath + (String)conf.get( "dir" ); this.dir = this.rootPath + (String) conf.get("dir");
this.allowFiles = this.getAllowFiles( conf.get("allowFiles") ); this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
this.count = (Integer)conf.get( "count" ); this.count = (Integer) conf.get("count");
} }
public State listFile ( int index ) { public State listFile(int index) {
File dir = new File( this.dir ); File dir = new File(this.dir);
State state = null; State state = null;
if ( !dir.exists() ) { if (!dir.exists()) {
return new BaseState( false, AppInfo.NOT_EXIST ); return new BaseState(false, AppInfo.NOT_EXIST);
} }
if ( !dir.isDirectory() ) { if (!dir.isDirectory()) {
return new BaseState( false, AppInfo.NOT_DIRECTORY ); return new BaseState(false, AppInfo.NOT_DIRECTORY);
} }
Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true ); Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
if ( index < 0 || index > list.size() ) { if (index < 0 || index > list.size()) {
state = new MultiState( true ); state = new MultiState(true);
} else { } else {
Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count ); Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count);
state = this.getState( fileList ); state = this.getState(fileList);
} }
state.putInfo( "start", index ); state.putInfo("start", index);
state.putInfo( "total", list.size() ); state.putInfo("total", list.size());
return state; return state;
} }
private State getState ( Object[] files ) { private State getState(Object[] files) {
MultiState state = new MultiState( true ); MultiState state = new MultiState(true);
BaseState fileState = null; BaseState fileState = null;
File file = null; File file = null;
for ( Object obj : files ) { for (Object obj : files) {
if ( obj == null ) { if (obj == null) {
break; break;
} }
file = (File)obj; file = (File) obj;
fileState = new BaseState( true ); fileState = new BaseState(true);
// fileState.putInfo( "url", PathFormat.format( this.getPathFormat( file ) ) ); fileState.putInfo("url", this.getPathFormat(file));
fileState.putInfo( "url", this.getPathFormat( file ) ); state.addState(fileState);
state.addState( fileState );
} }
return state; return state;
} }
private String getPathFormat ( File file ) { private String getPathFormat(File file) {
String path = file.getAbsolutePath(); String path = file.getAbsolutePath();
path = PathFormat.format(path); path = PathFormat.format(path);
if(this.rootPath.startsWith("/")){ if (this.rootPath.startsWith("/")) {
if(path.startsWith("/") == false){// 解决Windows下路径问题 // 解决Windows下路径问题
path = "/"+path; if (path.startsWith("/") == false) {
path = "/" + path;
} }
} }
// System.out.println(this.rootPath+"=="+path); return path.replace(this.rootPath, "/");
return path.replace( this.rootPath, "/" );
} }
private String[] getAllowFiles ( Object fileExt ) { private String[] getAllowFiles(Object fileExt) {
String[] exts = null; String[] exts = null;
String ext = null; String ext = null;
if ( fileExt == null ) { if (fileExt == null) {
return new String[ 0 ]; return new String[0];
} }
exts = (String[])fileExt; exts = (String[]) fileExt;
for ( int i = 0, len = exts.length; i < len; i++ ) { for (int i = 0, len = exts.length; i < len; i++) {
ext = exts[ i ]; ext = exts[i];
exts[ i ] = ext.replace( ".", "" ); exts[i] = ext.replace(".", "");
} }
......
...@@ -21,7 +21,7 @@ import org.springframework.web.servlet.HandlerInterceptor; ...@@ -21,7 +21,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.ejweb.core.conf.GConstants; import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.LoadExceptions; import com.ejweb.core.utils.LoadException;
/** /**
...@@ -43,7 +43,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -43,7 +43,7 @@ public class URLInterceptor implements HandlerInterceptor {
if(fileSize > maxFileSize) if(fileSize > maxFileSize)
{ {
throw new LoadExceptions("文件大小超出限制,请改正!"); throw new LoadException("文件大小超出限制,请改正!");
} }
...@@ -114,7 +114,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -114,7 +114,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -126,7 +126,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -126,7 +126,7 @@ public class URLInterceptor implements HandlerInterceptor {
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -141,7 +141,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -141,7 +141,7 @@ public class URLInterceptor implements HandlerInterceptor {
||queryString.contains("user.name"))){ ||queryString.contains("user.name"))){
continue; continue;
} }
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -152,7 +152,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -152,7 +152,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
...@@ -163,7 +163,7 @@ public class URLInterceptor implements HandlerInterceptor { ...@@ -163,7 +163,7 @@ public class URLInterceptor implements HandlerInterceptor {
items = entry.elements("keyword"); items = entry.elements("keyword");
for (Element item : items) { for (Element item : items) {
if(url.contains(item.getText())){ if(url.contains(item.getText())){
throw new LoadExceptions("参数传递过程中存在非法字符,请改正!"); throw new LoadException("参数传递过程中存在非法字符,请改正!");
} }
} }
......
...@@ -47,7 +47,6 @@ public abstract class DataEntity<T> extends BaseEntity<T> { ...@@ -47,7 +47,6 @@ public abstract class DataEntity<T> extends BaseEntity<T> {
// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID // 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
if (!this.isNewRecord){ if (!this.isNewRecord){
setId(IdGen.uuid()); setId(IdGen.uuid());
// setId(IdGen.uuid());
} }
User user = UserUtils.getUser(); User user = UserUtils.getUser();
if (StringUtils.isNotBlank(user.getId())){ if (StringUtils.isNotBlank(user.getId())){
......
...@@ -18,7 +18,6 @@ public class DerbyDialect implements Dialect { ...@@ -18,7 +18,6 @@ public class DerbyDialect implements Dialect {
@Override @Override
public String getLimitString(String sql, int offset, int limit) { public String getLimitString(String sql, int offset, int limit) {
// return getLimitString(sql,offset,Integer.toString(offset),limit,Integer.toString(limit));
throw new UnsupportedOperationException("paged queries not supported"); throw new UnsupportedOperationException("paged queries not supported");
} }
...@@ -37,8 +36,8 @@ public class DerbyDialect implements Dialect { ...@@ -37,8 +36,8 @@ public class DerbyDialect implements Dialect {
* @param limitPlaceholder 分页纪录条数占位符号 * @param limitPlaceholder 分页纪录条数占位符号
* @return 包含占位符的分页sql * @return 包含占位符的分页sql
*/ */
public String getLimitString(String sql, int offset,String offsetPlaceholder, int limit, String limitPlaceholder) { public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
throw new UnsupportedOperationException( "paged queries not supported" ); throw new UnsupportedOperationException("paged queries not supported");
} }
} }
package com.ejweb.core.push; package com.ejweb.core.push;
import java.net.URLEncoder;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder;
public class MessagePayload { public class MessagePayload {
private final JSONObject _data = new JSONObject(); private final JSONObject _data = new JSONObject();
private To toPeople;// 默认通过设备号推送 /**
// 发送对象 ALL 发送给所有用户, BY_TOKEN 发送给指定TOKEN的用户,BY_ALIAS 发给也指定别名的用户,PRE_MESSAGE 预存数据,不发送 * 默认通过设备号推送
public enum To{ */
ALL,BY_TOKEN,BY_ALIAS,PRE_MESSAGE private To toPeople;
/**
* 发送对象 ALL 发送给所有用户, BY_TOKEN 发送给指定TOKEN的用户,BY_ALIAS 发给也指定别名的用户,PRE_MESSAGE 预存数据,不发送
*/
public enum To {
ALL, BY_TOKEN, BY_ALIAS, PRE_MESSAGE
} }
public MessagePayload() { public MessagePayload() {
_data.put("appkey", ""); _data.put("appkey", "");
_data.put("topeople", 3); _data.put("topeople", 3);
...@@ -32,6 +38,7 @@ public class MessagePayload { ...@@ -32,6 +38,7 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
public MessagePayload(String appkey, To toPeople, String secret) { public MessagePayload(String appkey, To toPeople, String secret) {
_data.put("appkey", appkey); _data.put("appkey", appkey);
...@@ -62,8 +69,8 @@ public class MessagePayload { ...@@ -62,8 +69,8 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
/** /**
*
* @param appkey APPKEY * @param appkey APPKEY
* @param toPeople 推送人群 * @param toPeople 推送人群
* @param secret 推送接口密码 * @param secret 推送接口密码
...@@ -103,20 +110,23 @@ public class MessagePayload { ...@@ -103,20 +110,23 @@ public class MessagePayload {
_data.getJSONObject("message").put("expire_time", 0L); _data.getJSONObject("message").put("expire_time", 0L);
_data.getJSONObject("message").put("extras", new JSONObject()); _data.getJSONObject("message").put("extras", new JSONObject());
} }
/** /**
* 默认根据用户TOKEN进行推送 * 默认根据用户TOKEN进行推送
* *
* @return
* @author renmb * @author renmb
* @time 2016年8月15日 * @time 2016年8月15日
* @return
*/ */
public final static MessagePayload newPayload(){ public final static MessagePayload newPayload() {
final MessagePayload payload = new MessagePayload(); final MessagePayload payload = new MessagePayload();
payload.setToPeople(MessagePayload.To.BY_TOKEN); payload.setToPeople(MessagePayload.To.BY_TOKEN);
return payload; return payload;
} }
/** /**
* 发送已经生成的信息 * 发送已经生成的信息
*
* @param appkey * @param appkey
* @param toPeople * @param toPeople
* @param token * @param token
...@@ -144,16 +154,19 @@ public class MessagePayload { ...@@ -144,16 +154,19 @@ public class MessagePayload {
_data.put("token", secret); _data.put("token", secret);
_data.put("devices", new JSONArray()); _data.put("devices", new JSONArray());
} }
public MessagePayload setAppkey(String appkey) { public MessagePayload setAppkey(String appkey) {
_data.put("appkey", appkey); _data.put("appkey", appkey);
return this; return this;
} }
public MessagePayload setPushToken(String secret) { public MessagePayload setPushToken(String secret) {
_data.put("token", secret); _data.put("token", secret);
return this; return this;
} }
public MessagePayload setProduction(boolean production) { public MessagePayload setProduction(boolean production) {
if (production) { if (production) {
...@@ -163,6 +176,7 @@ public class MessagePayload { ...@@ -163,6 +176,7 @@ public class MessagePayload {
} }
return this; return this;
} }
public MessagePayload setToPeople(To toPeople) { public MessagePayload setToPeople(To toPeople) {
switch (toPeople) { switch (toPeople) {
...@@ -182,77 +196,81 @@ public class MessagePayload { ...@@ -182,77 +196,81 @@ public class MessagePayload {
this.toPeople = toPeople; this.toPeople = toPeople;
return this; return this;
} }
public To getToPeople() { public To getToPeople() {
return this.toPeople; return this.toPeople;
} }
public MessagePayload addMessageTitle(String title) { public MessagePayload addMessageTitle(String title) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("title", title); message.put("title", title);
return this; return this;
} }
public MessagePayload addMessageContent(String content){ public MessagePayload addMessageContent(String content) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("content", content); message.put("content", content);
return this; return this;
} }
public MessagePayload addMessageBeginTime(long beginTime){ public MessagePayload addMessageBeginTime(long beginTime) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("begin_time", beginTime); message.put("begin_time", beginTime);
return this; return this;
} }
public MessagePayload addMessageExpireTime(long expireTime){
public MessagePayload addMessageExpireTime(long expireTime) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.put("expire_time", expireTime); message.put("expire_time", expireTime);
return this; return this;
} }
public MessagePayload addMessageExtra(String key, Object value){ public MessagePayload addMessageExtra(String key, Object value) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return this; return this;
message.getJSONObject("extras").put(key, value); message.getJSONObject("extras").put(key, value);
return this; return this;
} }
public MessagePayload addDevices(String... devices){ public MessagePayload addDevices(String... devices) {
if(devices == null || devices.length == 0) if (devices == null || devices.length == 0)
return this; return this;
JSONArray d = _data.getJSONArray("devices"); JSONArray d = _data.getJSONArray("devices");
for(String device:devices){ for (String device : devices) {
d.add(device); d.add(device);
} }
return this; return this;
} }
public JSONObject getJSONMessage(String userId) { public JSONObject getJSONMessage(String userId) {
JSONObject message = _data.getJSONObject("message"); JSONObject message = _data.getJSONObject("message");
if(message == null) if (message == null)
return null; return null;
if(StringUtils.isBlank(userId)){ if (StringUtils.isBlank(userId)) {
message.put("user_id", ""); message.put("user_id", "");
} else { } else {
...@@ -261,11 +279,12 @@ public class MessagePayload { ...@@ -261,11 +279,12 @@ public class MessagePayload {
} }
return message; return message;
} }
public byte[] getMessagePayload(){
public byte[] getMessagePayload() {
try { try {
String c = "content="+URLEncoder.encode(_data.toJSONString(), "UTF-8"); String c = "content=" + URLEncoder.encode(_data.toJSONString(), "UTF-8");
return c.getBytes("UTF-8"); return c.getBytes("UTF-8");
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
......
package com.ejweb.core.security; package com.ejweb.core.security;
import java.io.UnsupportedEncodingException; import org.apache.commons.codec.digest.DigestUtils;
import java.security.Security;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import org.apache.commons.codec.digest.DigestUtils;
public class DES3Utils { public class DES3Utils {
// public static final String ALGORITHM = "DES"; // public static final String ALGORITHM = "DES";
private static final String Algorithm = "DESede"; // 定义加密算法,可用 private static final String Algorithm = "DESede"; // 定义加密算法,可用
// DES,DESede,Blowfish // DES,DESede,Blowfish
...@@ -65,7 +63,7 @@ public class DES3Utils { ...@@ -65,7 +63,7 @@ public class DES3Utils {
String f = DigestUtils.md5Hex(username); String f = DigestUtils.md5Hex(username);
byte[] bkeys = new String(f).getBytes(); byte[] bkeys = new String(f).getBytes();
byte[] enk = new byte[24]; byte[] enk = new byte[24];
for (int i = 0; i < 24 && i< bkeys.length; i++) { for (int i = 0; i < 24 && i < bkeys.length; i++) {
enk[i] = bkeys[i]; enk[i] = bkeys[i];
} }
return enk; return enk;
...@@ -121,17 +119,7 @@ public class DES3Utils { ...@@ -121,17 +119,7 @@ public class DES3Utils {
byte[] decrypted = c1.doFinal(data); byte[] decrypted = c1.doFinal(data);
return new String(decrypted, "UTF-8"); return new String(decrypted, "UTF-8");
} catch (Exception e) { } catch (Exception e) {
// e3.printStackTrace();
} }
return null; return null;
} }
public static void main(String[] args) throws UnsupportedEncodingException {
// byte[] ened = encrypt("我是中国人".getBytes(), "123456");
// String en = Base64.encode(ened);
System.out.println(encrypt("我是中国人", "782790337169117184"));
System.out.println(decrypt("fc564cedfd08e11664e33d4ddf381997", "782790337169117184"));
// System.out.println(decrypt(ened, "123456"));
}
} }
...@@ -3,21 +3,22 @@ ...@@ -3,21 +3,22 @@
*/ */
package com.ejweb.core.utils; package com.ejweb.core.utils;
import java.util.HashMap;
import com.ejweb.core.conf.GConstants; import com.ejweb.core.conf.GConstants;
import java.util.HashMap;
/** /**
* 文件安全扫描过滤 * 文件安全扫描过滤
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @team IT Team
* @time 2016年11月5日 * @time 2016年11月5日
*/ */
public class FileManipulation { public class FileManipulation {
public static String Manipulation(String path){ public static String Manipulation(String path) {
HashMap<String, String> map = new HashMap<String, String>(); HashMap<String, String> map = new HashMap<String, String>();
map.put("a", "a"); map.put("a", "a");
map.put("b", "b"); map.put("b", "b");
...@@ -81,73 +82,60 @@ public class FileManipulation { ...@@ -81,73 +82,60 @@ public class FileManipulation {
String temp = ""; String temp = "";
for (int i = 0; i < path.length(); i++) { for (int i = 0; i < path.length(); i++) {
if (map.get(path.charAt(i)+"")!=null) { if (map.get(path.charAt(i) + "") != null) {
temp += map.get(path.charAt(i)+""); temp += map.get(path.charAt(i) + "");
} }
} }
path = temp; path = temp;
return path; return path;
} }
/** /**
*
* 黑名单验证 * 黑名单验证
*
* @return
* @author zhanglg * @author zhanglg
* @time 2016年11月5日 * @time 2016年11月5日
* @return
*/ */
public static String validateFile(String filename){ public static String validateFile(String filename) {
String[] extesions=new String[]{"%",";"}; String[] extesions = new String[]{"%", ";"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename); throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
} }
} }
/* String extesionName = Util.getExtensionName(filename); filename = filename.replaceAll("\\.\\./", "");
filename = filename.replaceAll("\\.\\.\\\\", "");
// if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL filename = filename.replaceAll("\\.\\.", "");
// throw new LoadExceptions("无法获取文件扩展名:"+filename);
// }
String exd=".png;.jpg;.gif;.jpeg;.xls;.xlsx;.bmp;.ico;.swf;.psd;.apk;.doc;.docx;.txt;.sql;.xml;";
if(!exd.contains(extesionName)){
throw new LoadExceptions("此类型文件不允许上传:"+filename);
}*/
/* if(GConstants.FILE_FILTERS.get(extesionName) == null){
throw new LoadExceptions("此类型文件不允许上传:"+filename);
}*/
filename= filename.replaceAll("\\.\\./", "");
filename= filename.replaceAll("\\.\\.\\\\", "");
filename= filename.replaceAll("\\.\\.", "");
return filename; return filename;
} }
public static void check(String filename){ public static void check(String filename) {
String extesionName = Util.getExtensionName(filename); String extesionName = Util.getExtensionName(filename);
if(GConstants.FILE_FILTERS.get(extesionName) == null){ if (GConstants.FILE_FILTERS.get(extesionName) == null) {
throw new LoadExceptions("此类型文件不允许上传:"+filename); throw new LoadException("此类型文件不允许上传:" + filename);
} }
String[] extesions=new String[]{"%",";"}; String[] extesions = new String[]{"%", ";"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :"+filename); throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
} }
} }
} }
/** /**
*
* 黑名单验证2 * 黑名单验证2
*
* @return
* @author zhanglg * @author zhanglg
* @time 2016年11月5日 * @time 2016年11月5日
* @return
*/ */
public static String validateFile2(String filename){ public static String validateFile2(String filename) {
String[] extesions=new String[]{".xmls",".propertiey",".jsons"}; String[] extesions = new String[]{".xmls", ".propertiey", ".jsons"};
for(String extesion:extesions){ for (String extesion : extesions) {
if(filename.contains(extesion)){ if (filename.contains(extesion)) {
throw new LoadExceptions("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件"); throw new LoadException("非法的文件请求,请不要上传或下载含有非法名称或后缀的文件");
} }
} }
return filename; return filename;
......
...@@ -5,28 +5,35 @@ package com.ejweb.core.utils; ...@@ -5,28 +5,35 @@ package com.ejweb.core.utils;
/** /**
* 上传下载非法的异常抛出 * 上传下载非法的异常抛出
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @team IT Team
* @time 2016年11月6日 * @time 2016年11月6日
*/ */
public class LoadExceptions extends RuntimeException { public class LoadException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private String retCd ; //异常对应的返回码 /**
private String msgDes; //异常对应的描述信息 *异常对应的返回码
*/
private String retCd;
/**
*异常对应的描述信息
*/
private String msgDes;
public LoadExceptions() { public LoadException() {
super(); super();
} }
public LoadExceptions(String message) { public LoadException(String message) {
super(message); super(message);
msgDes = message; msgDes = message;
} }
public LoadExceptions(String retCd, String msgDes) { public LoadException(String retCd, String msgDes) {
super(); super();
this.retCd = retCd; this.retCd = retCd;
this.msgDes = msgDes; this.msgDes = msgDes;
......
...@@ -3,31 +3,13 @@ ...@@ -3,31 +3,13 @@
*/ */
package com.ejweb.core.utils.excel; package com.ejweb.core.utils.excel;
import java.io.FileNotFoundException; import com.ejweb.core.utils.Encodes;
import java.io.FileOutputStream; import com.ejweb.core.utils.Reflections;
import java.io.IOException; import com.ejweb.core.utils.excel.annotation.ExcelField;
import java.io.OutputStream; import com.ejweb.modules.sys.utils.DictUtils;
import java.lang.reflect.Field; import com.google.common.collect.Lists;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
...@@ -35,14 +17,18 @@ import org.apache.poi.xssf.usermodel.XSSFRichTextString; ...@@ -35,14 +17,18 @@ import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists; import javax.servlet.http.HttpServletResponse;
import com.ejweb.core.utils.Encodes; import java.io.FileNotFoundException;
import com.ejweb.core.utils.Reflections; import java.io.FileOutputStream;
import com.ejweb.core.utils.excel.annotation.ExcelField; import java.io.IOException;
import com.ejweb.modules.sys.utils.DictUtils; import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/** /**
* 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion) * 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
*
* @author ThinkGem * @author ThinkGem
* @version 2013-04-21 * @version 2013-04-21
*/ */
...@@ -77,65 +63,67 @@ public class ExportExcel { ...@@ -77,65 +63,67 @@ public class ExportExcel {
/** /**
* 构造函数 * 构造函数
*
* @param title 表格标题,传“空值”,表示无标题 * @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题 * @param cls 实体对象,通过annotation.ExportField获取标题
*/ */
public ExportExcel(String title, Class<?> cls){ public ExportExcel(String title, Class<?> cls) {
this(title, cls, 1); this(title, cls, 1);
} }
/** /**
* 构造函数 * 构造函数
*
* @param title 表格标题,传“空值”,表示无标题 * @param title 表格标题,传“空值”,表示无标题
* @param cls 实体对象,通过annotation.ExportField获取标题 * @param cls 实体对象,通过annotation.ExportField获取标题
* @param type 导出类型(1:导出数据;2:导出模板) * @param type 导出类型(1:导出数据;2:导出模板)
* @param groups 导入分组 * @param groups 导入分组
*/ */
public ExportExcel(String title, Class<?> cls, int type, int... groups){ public ExportExcel(String title, Class<?> cls, int type, int... groups) {
// Get annotation field // Get annotation field
Field[] fs = cls.getDeclaredFields(); Field[] fs = cls.getDeclaredFields();
for (Field f : fs){ for (Field f : fs) {
ExcelField ef = f.getAnnotation(ExcelField.class); ExcelField ef = f.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){ if (ef != null && (ef.type() == 0 || ef.type() == type)) {
if (groups!=null && groups.length>0){ if (groups != null && groups.length > 0) {
boolean inGroup = false; boolean inGroup = false;
for (int g : groups){ for (int g : groups) {
if (inGroup){ if (inGroup) {
break; break;
} }
for (int efg : ef.groups()){ for (int efg : ef.groups()) {
if (g == efg){ if (g == efg) {
inGroup = true; inGroup = true;
annotationList.add(new Object[]{ef, f}); annotationList.add(new Object[]{ef, f});
break; break;
} }
} }
} }
}else{ } else {
annotationList.add(new Object[]{ef, f}); annotationList.add(new Object[]{ef, f});
} }
} }
} }
// Get annotation method // Get annotation method
Method[] ms = cls.getDeclaredMethods(); Method[] ms = cls.getDeclaredMethods();
for (Method m : ms){ for (Method m : ms) {
ExcelField ef = m.getAnnotation(ExcelField.class); ExcelField ef = m.getAnnotation(ExcelField.class);
if (ef != null && (ef.type()==0 || ef.type()==type)){ if (ef != null && (ef.type() == 0 || ef.type() == type)) {
if (groups!=null && groups.length>0){ if (groups != null && groups.length > 0) {
boolean inGroup = false; boolean inGroup = false;
for (int g : groups){ for (int g : groups) {
if (inGroup){ if (inGroup) {
break; break;
} }
for (int efg : ef.groups()){ for (int efg : ef.groups()) {
if (g == efg){ if (g == efg) {
inGroup = true; inGroup = true;
annotationList.add(new Object[]{ef, m}); annotationList.add(new Object[]{ef, m});
break; break;
} }
} }
} }
}else{ } else {
annotationList.add(new Object[]{ef, m}); annotationList.add(new Object[]{ef, m});
} }
} }
...@@ -143,18 +131,20 @@ public class ExportExcel { ...@@ -143,18 +131,20 @@ public class ExportExcel {
// Field sorting // Field sorting
Collections.sort(annotationList, new Comparator<Object[]>() { Collections.sort(annotationList, new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) { public int compare(Object[] o1, Object[] o2) {
return new Integer(((ExcelField)o1[0]).sort()).compareTo( return new Integer(((ExcelField) o1[0]).sort()).compareTo(
new Integer(((ExcelField)o2[0]).sort())); new Integer(((ExcelField) o2[0]).sort()));
}; }
;
}); });
// Initialize // Initialize
List<String> headerList = Lists.newArrayList(); List<String> headerList = Lists.newArrayList();
for (Object[] os : annotationList){ for (Object[] os : annotationList) {
String t = ((ExcelField)os[0]).title(); String t = ((ExcelField) os[0]).title();
// 如果是导出,则去掉注释 // 如果是导出,则去掉注释
if (type==1){ if (type == 1) {
String[] ss = StringUtils.split(t, "**", 2); String[] ss = StringUtils.split(t, "**", 2);
if (ss.length==2){ if (ss.length == 2) {
t = ss[0]; t = ss[0];
} }
} }
...@@ -165,6 +155,7 @@ public class ExportExcel { ...@@ -165,6 +155,7 @@ public class ExportExcel {
/** /**
* 构造函数 * 构造函数
*
* @param title 表格标题,传“空值”,表示无标题 * @param title 表格标题,传“空值”,表示无标题
* @param headers 表头数组 * @param headers 表头数组
*/ */
...@@ -174,6 +165,7 @@ public class ExportExcel { ...@@ -174,6 +165,7 @@ public class ExportExcel {
/** /**
* 构造函数 * 构造函数
*
* @param title 表格标题,传“空值”,表示无标题 * @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表 * @param headerList 表头列表
*/ */
...@@ -183,6 +175,7 @@ public class ExportExcel { ...@@ -183,6 +175,7 @@ public class ExportExcel {
/** /**
* 初始化函数 * 初始化函数
*
* @param title 表格标题,传“空值”,表示无标题 * @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表 * @param headerList 表头列表
*/ */
...@@ -191,17 +184,17 @@ public class ExportExcel { ...@@ -191,17 +184,17 @@ public class ExportExcel {
this.sheet = wb.createSheet("Export"); this.sheet = wb.createSheet("Export");
this.styles = createStyles(wb); this.styles = createStyles(wb);
// Create title // Create title
if (StringUtils.isNotBlank(title)){ if (StringUtils.isNotBlank(title)) {
Row titleRow = sheet.createRow(rownum++); Row titleRow = sheet.createRow(rownum++);
titleRow.setHeightInPoints(30); titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0); Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title")); titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title); titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1)); titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1));
} }
// Create header // Create header
if (headerList == null){ if (headerList == null) {
throw new RuntimeException("headerList not null!"); throw new RuntimeException("headerList not null!");
} }
Row headerRow = sheet.createRow(rownum++); Row headerRow = sheet.createRow(rownum++);
...@@ -210,19 +203,19 @@ public class ExportExcel { ...@@ -210,19 +203,19 @@ public class ExportExcel {
Cell cell = headerRow.createCell(i); Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header")); cell.setCellStyle(styles.get("header"));
String[] ss = StringUtils.split(headerList.get(i), "**", 2); String[] ss = StringUtils.split(headerList.get(i), "**", 2);
if (ss.length==2){ if (ss.length == 2) {
cell.setCellValue(ss[0]); cell.setCellValue(ss[0]);
Comment comment = this.sheet.createDrawingPatriarch().createCellComment( Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6)); new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
comment.setString(new XSSFRichTextString(ss[1])); comment.setString(new XSSFRichTextString(ss[1]));
cell.setCellComment(comment); cell.setCellComment(comment);
}else{ } else {
cell.setCellValue(headerList.get(i)); cell.setCellValue(headerList.get(i));
} }
sheet.autoSizeColumn(i); sheet.autoSizeColumn(i);
} }
for (int i = 0; i < headerList.size(); i++) { for (int i = 0; i < headerList.size(); i++) {
int colWidth = sheet.getColumnWidth(i)*2; int colWidth = sheet.getColumnWidth(i) * 2;
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth); sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
} }
log.debug("Initialize success."); log.debug("Initialize success.");
...@@ -230,6 +223,7 @@ public class ExportExcel { ...@@ -230,6 +223,7 @@ public class ExportExcel {
/** /**
* 创建表格样式 * 创建表格样式
*
* @param wb 工作薄对象 * @param wb 工作薄对象
* @return 样式列表 * @return 样式列表
*/ */
...@@ -279,7 +273,6 @@ public class ExportExcel { ...@@ -279,7 +273,6 @@ public class ExportExcel {
style = wb.createCellStyle(); style = wb.createCellStyle();
style.cloneStyleFrom(styles.get("data")); style.cloneStyleFrom(styles.get("data"));
// style.setWrapText(true);
style.setAlignment(CellStyle.ALIGN_CENTER); style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND); style.setFillPattern(CellStyle.SOLID_FOREGROUND);
...@@ -296,37 +289,40 @@ public class ExportExcel { ...@@ -296,37 +289,40 @@ public class ExportExcel {
/** /**
* 添加一行 * 添加一行
*
* @return 行对象 * @return 行对象
*/ */
public Row addRow(){ public Row addRow() {
return sheet.createRow(rownum++); return sheet.createRow(rownum++);
} }
/** /**
* 添加一个单元格 * 添加一个单元格
*
* @param row 添加的行 * @param row 添加的行
* @param column 添加列号 * @param column 添加列号
* @param val 添加值 * @param val 添加值
* @return 单元格对象 * @return 单元格对象
*/ */
public Cell addCell(Row row, int column, Object val){ public Cell addCell(Row row, int column, Object val) {
return this.addCell(row, column, val, 0, Class.class); return this.addCell(row, column, val, 0, Class.class);
} }
/** /**
* 添加一个单元格 * 添加一个单元格
*
* @param row 添加的行 * @param row 添加的行
* @param column 添加列号 * @param column 添加列号
* @param val 添加值 * @param val 添加值
* @param align 对齐方式(1:靠左;2:居中;3:靠右) * @param align 对齐方式(1:靠左;2:居中;3:靠右)
* @return 单元格对象 * @return 单元格对象
*/ */
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){ public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
Cell cell = row.createCell(column); Cell cell = row.createCell(column);
CellStyle style = styles.get("data"+(align>=1&&align<=3?align:"")); CellStyle style = styles.get("data" + (align >= 1 && align <= 3 ? align : ""));
try { try {
if (val == null){ if (val == null) {
cell.setCellValue(""); cell.setCellValue("");
} else if (val instanceof String) { } else if (val instanceof String) {
cell.setCellValue((String) val); cell.setCellValue((String) val);
...@@ -343,15 +339,15 @@ public class ExportExcel { ...@@ -343,15 +339,15 @@ public class ExportExcel {
style.setDataFormat(format.getFormat("yyyy-MM-dd")); style.setDataFormat(format.getFormat("yyyy-MM-dd"));
cell.setCellValue((Date) val); cell.setCellValue((Date) val);
} else { } else {
if (fieldType != Class.class){ if (fieldType != Class.class) {
cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val)); cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
}else{ } else {
cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(), cell.setCellValue((String) Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val)); "fieldtype." + val.getClass().getSimpleName() + "Type")).getMethod("setValue", Object.class).invoke(null, val));
} }
} }
} catch (Exception ex) { } catch (Exception ex) {
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString()); log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
cell.setCellValue(val.toString()); cell.setCellValue(val.toString());
} }
cell.setCellStyle(style); cell.setCellStyle(style);
...@@ -360,32 +356,33 @@ public class ExportExcel { ...@@ -360,32 +356,33 @@ public class ExportExcel {
/** /**
* 添加数据(通过annotation.ExportField添加数据) * 添加数据(通过annotation.ExportField添加数据)
*
* @return list 数据列表 * @return list 数据列表
*/ */
public <E> ExportExcel setDataList(List<E> list){ public <E> ExportExcel setDataList(List<E> list) {
for (E e : list){ for (E e : list) {
int colunm = 0; int colunm = 0;
Row row = this.addRow(); Row row = this.addRow();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Object[] os : annotationList){ for (Object[] os : annotationList) {
ExcelField ef = (ExcelField)os[0]; ExcelField ef = (ExcelField) os[0];
Object val = null; Object val = null;
// Get entity value // Get entity value
try{ try {
if (StringUtils.isNotBlank(ef.value())){ if (StringUtils.isNotBlank(ef.value())) {
val = Reflections.invokeGetter(e, ef.value()); val = Reflections.invokeGetter(e, ef.value());
}else{ } else {
if (os[1] instanceof Field){ if (os[1] instanceof Field) {
val = Reflections.invokeGetter(e, ((Field)os[1]).getName()); val = Reflections.invokeGetter(e, ((Field) os[1]).getName());
}else if (os[1] instanceof Method){ } else if (os[1] instanceof Method) {
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {}); val = Reflections.invokeMethod(e, ((Method) os[1]).getName(), new Class[]{}, new Object[]{});
} }
} }
// If is dict, get dict label // If is dict, get dict label
if (StringUtils.isNotBlank(ef.dictType())){ if (StringUtils.isNotBlank(ef.dictType())) {
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), ""); val = DictUtils.getDictLabel(val == null ? "" : val.toString(), ef.dictType(), "");
} }
}catch(Exception ex) { } catch (Exception ex) {
// Failure to ignore // Failure to ignore
log.info(ex.toString()); log.info(ex.toString());
val = ""; val = "";
...@@ -393,37 +390,40 @@ public class ExportExcel { ...@@ -393,37 +390,40 @@ public class ExportExcel {
this.addCell(row, colunm++, val, ef.align(), ef.fieldType()); this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
sb.append(val + ", "); sb.append(val + ", ");
} }
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString()); log.debug("Write success: [" + row.getRowNum() + "] " + sb.toString());
} }
return this; return this;
} }
/** /**
* 输出数据流 * 输出数据流
*
* @param os 输出数据流 * @param os 输出数据流
*/ */
public ExportExcel write(OutputStream os) throws IOException{ public ExportExcel write(OutputStream os) throws IOException {
wb.write(os); wb.write(os);
return this; return this;
} }
/** /**
* 输出到客户端 * 输出到客户端
*
* @param fileName 输出文件名 * @param fileName 输出文件名
*/ */
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{ public ExportExcel write(HttpServletResponse response, String fileName) throws IOException {
response.reset(); response.reset();
response.setContentType("application/octet-stream; charset=utf-8"); response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName)); response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
write(response.getOutputStream()); write(response.getOutputStream());
return this; return this;
} }
/** /**
* 输出到文件 * 输出到文件
*
* @param fileName 输出文件名 * @param fileName 输出文件名
*/ */
public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{ public ExportExcel writeFile(String name) throws FileNotFoundException, IOException {
FileOutputStream os = new FileOutputStream(name); FileOutputStream os = new FileOutputStream(name);
this.write(os); this.write(os);
return this; return this;
...@@ -432,7 +432,7 @@ public class ExportExcel { ...@@ -432,7 +432,7 @@ public class ExportExcel {
/** /**
* 清理临时文件 * 清理临时文件
*/ */
public ExportExcel dispose(){ public ExportExcel dispose() {
wb.dispose(); wb.dispose();
return this; return this;
} }
......
...@@ -44,39 +44,35 @@ public class CKFinderConnectorServlet extends ConnectorServlet { ...@@ -44,39 +44,35 @@ public class CKFinderConnectorServlet extends ConnectorServlet {
try { try {
Principal principal = (Principal) UserUtils.getPrincipal(); Principal principal = (Principal) UserUtils.getPrincipal();
if (principal == null){ if (principal == null) {
return; return;
} }
String command = request.getParameter("command"); String command = request.getParameter("command");
String type = request.getParameter("type"); String type = request.getParameter("type");
if ("Init".equals(command)){// 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹 // 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹
String startupPath = request.getParameter("startupPath");// 当前文件夹可指定为模块名 if ("Init".equals(command)) {
if (startupPath!=null){ // 当前文件夹可指定为模块名
String startupPath = request.getParameter("startupPath");
if (startupPath != null) {
String[] ss = startupPath.split(":"); String[] ss = startupPath.split(":");
if (ss.length==2){ if (ss.length == 2) {
// String realPath = GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL
// + principal + "/" + ss[0] + ss[1];
// FileUtils.createDirectory(FileUtils.path(realPath));
String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1]; String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1];
realPath= FileManipulation.validateFile(realPath); realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath)); File fileRealPath = new File(FileManipulation.validateFile(realPath));
if(fileRealPath.exists() == false){ if (fileRealPath.exists() == false) {
fileRealPath.mkdirs(); fileRealPath.mkdirs();
} }
} }
} }
} else if ("QuickUpload".equals(command) && type != null){// 快捷上传,自动创建当前文件夹,并上传到该路径 // 快捷上传,自动创建当前文件夹,并上传到该路径
String currentFolder = request.getParameter("currentFolder");// 当前文件夹可指定为模块名 } else if ("QuickUpload".equals(command) && type != null) {
// String realPath = GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL // 当前文件夹可指定为模块名
// + principal + "/" + type + (currentFolder != null ? currentFolder : ""); String currentFolder = request.getParameter("currentFolder");
// FileUtils.createDirectory(FileUtils.path(realPath));
String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : ""); String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : "");
// 验证文件安全 // 验证文件安全
realPath= FileManipulation.validateFile(realPath); realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath)); File fileRealPath = new File(FileManipulation.validateFile(realPath));
if(fileRealPath.exists() == false){ if (fileRealPath.exists() == false) {
fileRealPath.mkdirs(); fileRealPath.mkdirs();
} }
} }
......
...@@ -2,17 +2,16 @@ package com.ejweb.modules.airline.entity; ...@@ -2,17 +2,16 @@ package com.ejweb.modules.airline.entity;
import com.ejweb.core.persistence.DataEntity; import com.ejweb.core.persistence.DataEntity;
//import com.ejweb.modules.sys.entity.Area;
/** /**
*
* Verify Entity * Verify Entity
* @team IT Team *
* @author zhanglg * @author zhanglg
* @version 1.0 * @version 1.0
* @team IT Team
* @time 2016年8月30日 * @time 2016年8月30日
*/ */
public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneable{ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
...@@ -80,6 +79,4 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl ...@@ -80,6 +79,4 @@ public class ConnectEntity extends DataEntity<ConnectEntity> implements Cloneabl
} }
} }
\ No newline at end of file
...@@ -19,15 +19,16 @@ import java.io.*; ...@@ -19,15 +19,16 @@ import java.io.*;
public class FileService { public class FileService {
private static Logger LOG = Logger.getLogger(FileService.class); private static Logger LOG = Logger.getLogger(FileService.class);
private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}"); private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
public String upload(MultipartFile multipartFile,String originalFilename){
public String upload(MultipartFile multipartFile, String originalFilename) {
OutputStream os = null; OutputStream os = null;
String moduleName="image"; String moduleName = "image";
ByteArrayOutputStream baos = null; ByteArrayOutputStream baos = null;
try{ try {
String extesionName = Util.getExtensionName(originalFilename); String extesionName = Util.getExtensionName(originalFilename);
InputStream in=multipartFile.getInputStream(); InputStream in = multipartFile.getInputStream();
in = new BufferedInputStream(in); in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream(); baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE]; byte[] buf = new byte[GConstants.BUFFER_SIZE];
...@@ -38,32 +39,31 @@ public class FileService { ...@@ -38,32 +39,31 @@ public class FileService {
size = in.read(buf); size = in.read(buf);
} }
byte[] data = baos.toByteArray(); byte[] data = baos.toByteArray();
// byte[] data = IOUtils.toByteArray(in);
// 待扩展名称的MOD5 // 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data)+extesionName; String md5 = DigestUtils.md5Hex(data) + extesionName;
if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL // 文件扩展名称不能为NULL
LOG.debug("无法获取文件扩展名:"+originalFilename); if (extesionName == null || extesionName.length() == 0) {
LOG.debug("无法获取文件扩展名:" + originalFilename);
} }
// 文件保存路径:基本路径+模块名称+日期 // 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis()); String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
String basePath = moduleName+GConstants.FS+extesionName.replaceAll("\\.", "")+GConstants.FS; String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// 上传文件基本地址 // 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath); File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath);
if(!baseUploadDir.exists()){// 如果文件夹不存在则创建 if (!baseUploadDir.exists()) {
baseUploadDir.mkdirs(); baseUploadDir.mkdirs();
} }
// 文件保存地址 // 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5); File uploadFilePath = new File(baseUploadDir, md5);
LOG.info("原文件服务器绝对路径:"+uploadFilePath); LOG.info("原文件服务器绝对路径:" + uploadFilePath);
// 将数据保存到指定文件 // 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath); os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os); os = new BufferedOutputStream(os);
os.write(data); os.write(data);
os.flush(); os.flush();
return baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5; return baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath + md5;
}catch (IOException ex){ } catch (IOException ex) {
return "error"+ex.getMessage(); return "error" + ex.getMessage();
} }
} }
......
...@@ -34,7 +34,6 @@ public class FileUploadController extends BaseController { ...@@ -34,7 +34,6 @@ public class FileUploadController extends BaseController {
try { try {
request.setCharacterEncoding("utf-8"); request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html"); response.setHeader("Content-Type", "text/html");
// String fileName = file.getOriginalFilename();
// 转换为文件类型的request // 转换为文件类型的request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
......
...@@ -3,10 +3,7 @@ ...@@ -3,10 +3,7 @@
*/ */
package com.ejweb.modules.sys.security; package com.ejweb.modules.sys.security;
import javax.servlet.ServletRequest; import com.ejweb.core.utils.StringUtils;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.IncorrectCredentialsException;
...@@ -14,10 +11,13 @@ import org.apache.shiro.authc.UnknownAccountException; ...@@ -14,10 +11,13 @@ import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.util.WebUtils; import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.ejweb.core.utils.StringUtils; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
/** /**
* 表单验证(包含验证码)过滤类 * 表单验证(包含验证码)过滤类
*
* @author ThinkGem * @author ThinkGem
* @version 2014-5-19 * @version 2014-5-19
*/ */
...@@ -35,11 +35,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -35,11 +35,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) { protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String username = getUsername(request); String username = getUsername(request);
String password = getPassword(request); String password = getPassword(request);
if (password==null){ if (password == null) {
password = ""; password = "";
} }
boolean rememberMe = isRememberMe(request); boolean rememberMe = isRememberMe(request);
String host = StringUtils.getRemoteAddr((HttpServletRequest)request); String host = StringUtils.getRemoteAddr((HttpServletRequest) request);
String captcha = getCaptcha(request); String captcha = getCaptcha(request);
boolean mobile = isMobileLogin(request); boolean mobile = isMobileLogin(request);
return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile); return new UsernamePasswordToken(username, password.toCharArray(), rememberMe, host, captcha, mobile);
...@@ -75,12 +75,7 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -75,12 +75,7 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
@Override @Override
protected void issueSuccessRedirect(ServletRequest request, protected void issueSuccessRedirect(ServletRequest request,
ServletResponse response) throws Exception { ServletResponse response) throws Exception {
// Principal p = UserUtils.getPrincipal();
// if (p != null && !p.isMobileLogin()){
WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true); WebUtils.issueRedirect(request, response, getSuccessUrl(), null, true);
// }else{
// super.issueSuccessRedirect(request, response);
// }
} }
/** /**
...@@ -91,13 +86,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc. ...@@ -91,13 +86,11 @@ public class FormAuthenticationFilter extends org.apache.shiro.web.filter.authc.
AuthenticationException e, ServletRequest request, ServletResponse response) { AuthenticationException e, ServletRequest request, ServletResponse response) {
String className = e.getClass().getName(), message = ""; String className = e.getClass().getName(), message = "";
if (IncorrectCredentialsException.class.getName().equals(className) if (IncorrectCredentialsException.class.getName().equals(className)
|| UnknownAccountException.class.getName().equals(className)){ || UnknownAccountException.class.getName().equals(className)) {
message = "用户或密码错误, 请重试."; message = "用户或密码错误, 请重试.";
} } else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")) {
else if (e.getMessage() != null && StringUtils.startsWith(e.getMessage(), "msg:")){
message = StringUtils.replace(e.getMessage(), "msg:", ""); message = StringUtils.replace(e.getMessage(), "msg:", "");
} } else {
else{
message = "系统出现点问题,请稍后再试!"; message = "系统出现点问题,请稍后再试!";
e.printStackTrace(); // 输出到控制台 e.printStackTrace(); // 输出到控制台
} }
......
...@@ -3,11 +3,14 @@ ...@@ -3,11 +3,14 @@
*/ */
package com.ejweb.modules.sys.web; package com.ejweb.modules.sys.web;
import java.util.List; import com.ejweb.core.base.BaseController;
import java.util.Map; import com.ejweb.core.conf.GConstants;
import com.ejweb.core.utils.StringUtils;
import javax.servlet.http.HttpServletResponse; import com.ejweb.modules.sys.entity.Area;
import com.ejweb.modules.sys.service.AreaService;
import com.ejweb.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
...@@ -18,17 +21,13 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -18,17 +21,13 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists; import javax.servlet.http.HttpServletResponse;
import com.google.common.collect.Maps; import java.util.List;
import com.ejweb.core.conf.GConstants; import java.util.Map;
import com.ejweb.core.utils.StringUtils;
import com.ejweb.core.base.BaseController;
import com.ejweb.modules.sys.entity.Area;
import com.ejweb.modules.sys.service.AreaService;
import com.ejweb.modules.sys.utils.UserUtils;
/** /**
* 区域Controller * 区域Controller
*
* @author ThinkGem * @author ThinkGem
* @version 2013-5-15 * @version 2013-5-15
*/ */
...@@ -40,10 +39,10 @@ public class AreaController extends BaseController { ...@@ -40,10 +39,10 @@ public class AreaController extends BaseController {
private AreaService areaService; private AreaService areaService;
@ModelAttribute("area") @ModelAttribute("area")
public Area get(@RequestParam(required=false) String id) { public Area get(@RequestParam(required = false) String id) {
if (StringUtils.isNotBlank(id)){ if (StringUtils.isNotBlank(id)) {
return areaService.get(id); return areaService.get(id);
}else{ } else {
return new Area(); return new Area();
} }
} }
...@@ -58,27 +57,14 @@ public class AreaController extends BaseController { ...@@ -58,27 +57,14 @@ public class AreaController extends BaseController {
@RequiresPermissions("sys:area:view") @RequiresPermissions("sys:area:view")
@RequestMapping(value = "form") @RequestMapping(value = "form")
public String form(Area area, Model model) { public String form(Area area, Model model) {
if (area.getParent()==null||area.getParent().getId()==null){ if (area.getParent() == null || area.getParent().getId() == null) {
area.setParent(UserUtils.getUser().getOffice().getArea()); area.setParent(UserUtils.getUser().getOffice().getArea());
} }
if(area.getParent() != null){ if (area.getParent() != null) {
area.setParent(areaService.get(area.getParent().getId())); area.setParent(areaService.get(area.getParent().getId()));
} }
// // 自动获取排序号
// if (StringUtils.isBlank(area.getId())){
// int size = 0;
// List<Area> list = areaService.findAll();
// for (int i=0; i<list.size(); i++){
// Area e = list.get(i);
// if (e.getParent()!=null && e.getParent().getId()!=null
// && e.getParent().getId().equals(area.getParent().getId())){
// size++;
// }
// }
// area.setCode(area.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size : 1), 4, "0"));
// }
model.addAttribute("area", area); model.addAttribute("area", area);
return "modules/sys/areaForm"; return "modules/sys/areaForm";
} }
...@@ -86,16 +72,13 @@ public class AreaController extends BaseController { ...@@ -86,16 +72,13 @@ public class AreaController extends BaseController {
@RequiresPermissions("sys:area:edit") @RequiresPermissions("sys:area:edit")
@RequestMapping(value = "save") @RequestMapping(value = "save")
public String save(Area area, Model model, RedirectAttributes redirectAttributes) { public String save(Area area, Model model, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area"; return "redirect:" + adminPath + "/sys/area";
} }
if (!beanValidator(model, area)){ if (!beanValidator(model, area)) {
return form(area, model); return form(area, model);
} }
// if(StringUtils.isBlank(area.getId())){
// area.setIsNewRecord(true);
// }
areaService.save(area); areaService.save(area);
addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功"); addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
return "redirect:" + adminPath + "/sys/area/"; return "redirect:" + adminPath + "/sys/area/";
...@@ -104,28 +87,24 @@ public class AreaController extends BaseController { ...@@ -104,28 +87,24 @@ public class AreaController extends BaseController {
@RequiresPermissions("sys:area:edit") @RequiresPermissions("sys:area:edit")
@RequestMapping(value = "delete") @RequestMapping(value = "delete")
public String delete(Area area, RedirectAttributes redirectAttributes) { public String delete(Area area, RedirectAttributes redirectAttributes) {
if(GConstants.isDemoMode()){ if (GConstants.isDemoMode()) {
addMessage(redirectAttributes, "演示模式,不允许操作!"); addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area"; return "redirect:" + adminPath + "/sys/area";
} }
// if (Area.isRoot(id)){
// addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
// }else{
areaService.delete(area); areaService.delete(area);
addMessage(redirectAttributes, "删除区域成功"); addMessage(redirectAttributes, "删除区域成功");
// }
return "redirect:" + adminPath + "/sys/area/"; return "redirect:" + adminPath + "/sys/area/";
} }
@RequiresPermissions("user") @RequiresPermissions("user")
@ResponseBody @ResponseBody
@RequestMapping(value = "treeData") @RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) { public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList(); List<Map<String, Object>> mapList = Lists.newArrayList();
List<Area> list = areaService.findAll(); List<Area> list = areaService.findAll();
for (int i=0; i<list.size(); i++){ for (int i = 0; i < list.size(); i++) {
Area e = list.get(i); Area e = list.get(i);
if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){ if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) {
Map<String, Object> map = Maps.newHashMap(); Map<String, Object> map = Maps.newHashMap();
map.put("id", e.getId()); map.put("id", e.getId());
map.put("pId", e.getParentId()); map.put("pId", e.getParentId());
......
...@@ -175,9 +175,6 @@ public class FormController extends BaseController { ...@@ -175,9 +175,6 @@ public class FormController extends BaseController {
@RequiresPermissions("vrf:design:view") @RequiresPermissions("vrf:design:view")
@RequestMapping(value = "preview") @RequestMapping(value = "preview")
public String view(HttpServletRequest request,FormEntity formEntity, Model model){ public String view(HttpServletRequest request,FormEntity formEntity, Model model){
/* if(formEntity!=null){
formEntity.setFormText(formEntity.getFormText().replaceAll("<table","<table class='table table-bordered' "));
}*/
String parse_form= request.getParameter("parse_form"); String parse_form= request.getParameter("parse_form");
if(StringUtils.isNoneBlank(parse_form)){ if(StringUtils.isNoneBlank(parse_form)){
parse_form= parse_form.replaceAll("\\{\\|\\-", ""); parse_form= parse_form.replaceAll("\\{\\|\\-", "");
......
package com.hnatourism.b2b.util; package com.hnatourism.b2b.util;
import javax.crypto.Cipher;
import java.security.Key; import java.security.Key;
import java.security.Security; import java.security.Security;
import javax.crypto.Cipher;
/** /**
* 加密解密 * 加密解密
*/ */
public class DESPlus public class DESPlus {
{
private static String strDefaultKey = "so$so_"; // 默认密钥 private static String strDefaultKey = "so$so_"; // 默认密钥
...@@ -20,31 +18,25 @@ public class DESPlus ...@@ -20,31 +18,25 @@ public class DESPlus
/** /**
* 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程 * 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程
* *
* @param arrB * @param arrB 需要转换的byte数组
* 需要转换的byte数组
* @return 转换后的字符串 * @return 转换后的字符串
* @throws Exception * @throws Exception 本方法不处理任何异常,所有异常全部抛出
* 本方法不处理任何异常,所有异常全部抛出
*/ */
public static String byteArr2HexStr(byte[] arrB) throws Exception public static String byteArr2HexStr(byte[] arrB) throws Exception {
{
int iLen = arrB.length; int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer( iLen * 2 ); StringBuffer sb = new StringBuffer(iLen * 2);
for ( int i = 0; i < iLen; i++ ) for (int i = 0; i < iLen; i++) {
{
int intTmp = arrB[i]; int intTmp = arrB[i];
// 把负数转换为正数 // 把负数转换为正数
while ( intTmp < 0 ) while (intTmp < 0) {
{
intTmp = intTmp + 256; intTmp = intTmp + 256;
} }
// 小于0F的数需要在前面补0 // 小于0F的数需要在前面补0
if ( intTmp < 16 ) if (intTmp < 16) {
{ sb.append("0");
sb.append( "0" );
} }
sb.append( Integer.toString( intTmp, 16 ) ); sb.append(Integer.toString(intTmp, 16));
} }
return sb.toString(); return sb.toString();
} }
...@@ -52,23 +44,19 @@ public class DESPlus ...@@ -52,23 +44,19 @@ public class DESPlus
/** /**
* 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 互为可逆的转换过程 * 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 互为可逆的转换过程
* *
* @param strIn * @param strIn 需要转换的字符串
* 需要转换的字符串
* @return 转换后的byte数组 * @return 转换后的byte数组
* @throws Exception * @throws Exception 本方法不处理任何异常,所有异常全部抛出
* 本方法不处理任何异常,所有异常全部抛出
* @author <a href="mailto:leo841001@163.com">LiGuoQing</a> * @author <a href="mailto:leo841001@163.com">LiGuoQing</a>
*/ */
public static byte[] hexStr2ByteArr(String strIn) throws Exception public static byte[] hexStr2ByteArr(String strIn) throws Exception {
{
byte[] arrB = strIn.getBytes(); byte[] arrB = strIn.getBytes();
int iLen = arrB.length; int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2]; byte[] arrOut = new byte[iLen / 2];
for ( int i = 0; i < iLen; i = i + 2 ) for (int i = 0; i < iLen; i = i + 2) {
{ String strTmp = new String(arrB, i, 2);
String strTmp = new String( arrB, i, 2 ); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
arrOut[i / 2] = (byte) Integer.parseInt( strTmp, 16 );
} }
return arrOut; return arrOut;
} }
...@@ -78,128 +66,107 @@ public class DESPlus ...@@ -78,128 +66,107 @@ public class DESPlus
* *
* @throws Exception * @throws Exception
*/ */
public DESPlus() throws Exception public DESPlus() throws Exception {
{ this(strDefaultKey);
this( strDefaultKey );
} }
/** /**
* 指定密钥构造方法 * 指定密钥构造方法
* *
* @param strKey * @param strKey 指定的密钥
* 指定的密钥
* @throws Exception * @throws Exception
*/ */
public DESPlus(String strKey) throws Exception public DESPlus(String strKey) throws Exception {
{
Security.addProvider(new com.sun.crypto.provider.SunJCE()); Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key key = getKey( strKey.getBytes() ); Key key = getKey(strKey.getBytes());
encryptCipher = Cipher.getInstance( "DES" ); encryptCipher = Cipher.getInstance("DES");
encryptCipher.init( Cipher.ENCRYPT_MODE, key ); encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance( "DES" ); decryptCipher = Cipher.getInstance("DES");
decryptCipher.init( Cipher.DECRYPT_MODE, key ); decryptCipher.init(Cipher.DECRYPT_MODE, key);
} }
/** /**
* 加密字节数组 * 加密字节数组
* *
* @param arrB * @param arrB 需加密的字节数组
* 需加密的字节数组
* @return 加密后的字节数组 * @return 加密后的字节数组
* @throws Exception * @throws Exception
*/ */
public byte[] encrypt(byte[] arrB) throws Exception public byte[] encrypt(byte[] arrB) throws Exception {
{ return encryptCipher.doFinal(arrB);
return encryptCipher.doFinal( arrB );
} }
/** /**
* 加密字符串 * 加密字符串
* *
* @param strIn * @param strIn 需加密的字符串
* 需加密的字符串
* @return 加密后的字符串 * @return 加密后的字符串
* @throws Exception * @throws Exception
*/ */
public String encrypt(String strIn) throws Exception public String encrypt(String strIn) throws Exception {
{
return byteArr2HexStr( encrypt( strIn.getBytes() ) ); return byteArr2HexStr(encrypt(strIn.getBytes()));
} }
/** /**
* 解密字节数组 * 解密字节数组
* *
* @param arrB * @param arrB 需解密的字节数组
* 需解密的字节数组
* @return 解密后的字节数组 * @return 解密后的字节数组
* @throws Exception * @throws Exception
*/ */
public byte[] decrypt(byte[] arrB) throws Exception public byte[] decrypt(byte[] arrB) throws Exception {
{ return decryptCipher.doFinal(arrB);
return decryptCipher.doFinal( arrB );
} }
/** /**
* 解密字符串 * 解密字符串
* *
* @param strIn * @param strIn 需解密的字符串
* 需解密的字符串
* @return 解密后的字符串 * @return 解密后的字符串
* @throws Exception * @throws Exception
*/ */
public String decrypt(String strIn) throws Exception public String decrypt(String strIn) throws Exception {
{ return new String(decrypt(hexStr2ByteArr(strIn)));
return new String( decrypt( hexStr2ByteArr( strIn ) ) );
} }
/** /**
* 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位
* *
* @param arrBTmp * @param arrBTmp 构成该字符串的字节数组
* 构成该字符串的字节数组
* @return 生成的密钥 * @return 生成的密钥
* @throws java.lang.Exception * @throws java.lang.Exception
*/ */
private Key getKey(byte[] arrBTmp) throws Exception private Key getKey(byte[] arrBTmp) throws Exception {
{
// 创建一个空的8位字节数组(默认值为0) // 创建一个空的8位字节数组(默认值为0)
byte[] arrB = new byte[8]; byte[] arrB = new byte[8];
// 将原始字节数组转换为8位 // 将原始字节数组转换为8位
for ( int i = 0; i < arrBTmp.length && i < arrB.length; i++ ) for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
{
arrB[i] = arrBTmp[i]; arrB[i] = arrBTmp[i];
} }
// 生成密钥 // 生成密钥
Key key = new javax.crypto.spec.SecretKeySpec( arrB, "DES" ); Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");
return key; return key;
} }
public static void main(String[] args) public static void main(String[] args) {
{
System.out.println("123".matches("\\d+")); System.out.println("123".matches("\\d+"));
System.exit(0); System.exit(0);
String test = "lgjdair123!@#"; String test = "lgjdair123!@#";
//String test="123456789@"+System.currentTimeMillis(); try {
// DESPlus des; System.out.println("加密前的字符:" + test);
try
{
// des = new DESPlus( );//定义密钥
System.out.println( "加密前的字符:" + test );
//String miwen = des.encrypt( test );
String miwen = "9affe36dba5385c41ac289290d7f86f8"; String miwen = "9affe36dba5385c41ac289290d7f86f8";
System.out.println( "加密后的字符:" + miwen ); System.out.println("加密后的字符:" + miwen);
DESPlus des1 = new DESPlus();//定义密钥 DESPlus des1 = new DESPlus();
System.out.println( "解密后的字符:" + des1.decrypt( miwen )); System.out.println("解密后的字符:" + des1.decrypt(miwen));
} catch ( Exception e ) } catch (Exception e) {
{
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -179,29 +179,4 @@ public class DESPlus ...@@ -179,29 +179,4 @@ public class DESPlus
return key; return key;
} }
public static void main(String[] args)
{
System.out.println("123".matches("\\d+"));
// System.exit(0);
String test = "foc_android";
//String test="123456789@"+System.currentTimeMillis();
// DESPlus des;
try
{
// des = new DESPlus( );//定义密钥
System.out.println( "加密前的字符:" + test );
//String miwen = des.encrypt( test );
String miwen = "9affe36dba5385c41ac289290d7f86f8";
System.out.println( "加密后的字符:" + miwen );
DESPlus des1 = new DESPlus();//定义密钥
System.out.println( "解密后的字符:" + des1.decrypt( miwen ));
} catch ( Exception e )
{
e.printStackTrace();
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment