增加BaseController全局异常捕获

glusterfs-api
Chariesliven 9 years ago
parent c66ba751a7
commit 8b64314d95

@ -2,17 +2,17 @@
<classpath> <classpath>
<classpathentry kind="src" path="src"/> <classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="test"/> <classpathentry kind="src" path="test"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/Java"> <classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0">
<attributes> <attributes>
<attribute name="owner.project.facets" value="java"/> <attribute name="owner.project.facets" value="jst.web"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.server.core.container/org.eclipse.jst.server.tomcat.runtimeTarget/Apache Tomcat v7.0"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes> <attributes>
<attribute name="owner.project.facets" value="jst.web"/> <attribute name="owner.project.facets" value="java"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.module.container"/>
<classpathentry kind="output" path="build/classes"/> <classpathentry kind="output" path="build/classes"/>
</classpath> </classpath>

@ -25,6 +25,11 @@
<arguments> <arguments>
</arguments> </arguments>
</buildCommand> </buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec> </buildSpec>
<natures> <natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature> <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>

@ -0,0 +1,2 @@
eclipse.preferences.version=1
performed.operation.correct.unbound.jre=1.0

@ -0,0 +1,2 @@
/com/
/dataSystem.properties

@ -0,0 +1,48 @@
/**
* BaseController.java
* : XX
* : <>
* 201697
* <>
*/
package com.base;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* <>
* <>
* @author chen
* @version [201697]
* @see [/]
* @since [/]
*/
public class BaseController {
/**
* <> @ExceptionHandler----
* <>
* @param request
* @param ex
* @return
* @see [##]
*/
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
request.setAttribute("ex", ex);
System.err.println("BaseController --exp ");
// 根据不同错误转向不同页面
if(ex instanceof CustomException) {
//TODO 从新封装json
System.err.println("BaseController --exp -- CustomException ");
return "error-business";
} else {
//TODO 其他错误则 调到指定页面
return "error";
}
}
}

@ -0,0 +1,33 @@
package com.base;
import java.io.File;
/**
* @
* @author chen
* @date 2016830
* @package com.base
*/
public class Constant {
/** 配置文件文件-dataSystem.properties */
public static String SYSTEM_PROPERTIES_FIEL_PATH = "/com/base/dataSystem.properties";
/** 国际话配置文件文件-i18n.properties */
public static String I18N_PROPERTIES_FIEL_PATH = "/com/base/i18n.properties";
/** 记录异常的文件-system_exception.txt-的位置-- */
public final static String SYSTEM_EXCEPTION_FILEPATH = "\\log\\system_exception.txt";
/** WritefileThread-线程睡眠时间--3000 */
public final static long THREAD_SLEEP_WRITEFILETHREAD = 3000;
/** 是否将异常写入文件 */
public final static String IS_WRITE_LOGFILE = "iswritelogfile";
/** CustomException记录报异常的对象的对象个数--10 */
public final static int CustomException_log_object_size = 10;
}

@ -0,0 +1,41 @@
package com.base;
/**
* @
* @author chen
* @date 2016822
* @package com.base
*/
public class Custom4exception {
//3003001001 : 第一位:标识异常, 第二到第四位:标识模块,第五道第七位:标识类别,第八道第十位标识具体异常
/** 3
* 003
* 001
* 001
*/
/** 虚拟机-资源-虚拟机VM启动异常 */
public final static String vbox_start_exp = "3003001001";
/** 虚拟机-资源-虚拟机VBoxManage.exe 不存在异常 */
public final static String vbox_exe_non_exist_exp = "3003001002";
/** 虚拟机-共享-设置共享文件夹中断异常 */
public final static String share_dir_interrupted_exp = "3003002001";
/** 数据管理-数据上报-中断或读写异常 */
public final static String data_manage_interrupted_exp = "3004001001";
/** 公共模块utils-xml类-xml非法异常 */
public final static String xml_field_Illega_exp = "3005001001";
/** 公共模块utils-xml类-document异常 */
public final static String xml_docu_exp = "3005001002";
/** 公共模块utils-xml类-读写异常 */
public final static String xml_io_exp = "3005001003";
/** 公共模块utils-oracle类-读写异常 */
public final static String oracle_io_exp = "3005002001";
}

@ -0,0 +1,112 @@
package com.base;
@SuppressWarnings("serial")
public class CustomException extends Exception {
/** 自定义异常信息-错误信息 */
private String msg;
/** 操作对象 */
private Object[] objArray;
/** 异常 */
private Throwable cause;
static{
// 是否 启动 记录 异常的线程
if (Boolean.valueOf(Resource.getProperties().get(Constant.IS_WRITE_LOGFILE))) {
//启动 记录 异常的线程
WritefileThread wt = new WritefileThread();
wt.start();
}
}
public CustomException() {
super();
}
/**
* @
* @param code
* @param msg
* @param e
* @param obj
*/
public CustomException(String code,Exception e,Object... obj) {
super(code);
StringBuffer sbuf= new StringBuffer();
sbuf.append(msg);
sbuf.append(code);
sbuf.append("\r\n");
msg = Resource.getProperties().get(code);
// 记录自定义的 异常
if (null != msg) {
sbuf.append(msg);
sbuf.append("\r\n");
}
// 记录原始的异常
if (null != e) {
StackTraceElement[] array = e.getStackTrace();
cause = e.getCause();
for (StackTraceElement stackTraceElement : array) {
sbuf.append(stackTraceElement.toString());
sbuf.append("\r\n");
}
}
//记录 出现异常时 当前的对象
if (null != obj) {
Object[] array = obj;
sbuf.append("Object[] size : ");
sbuf.append(array.length);
int forSize = 0;
if (Constant.CustomException_log_object_size < array.length) {
forSize = Constant.CustomException_log_object_size;
}
else {
forSize = array.length;
}
for (int i = 0; i < forSize; i++) {
sbuf.append(array[i]);
sbuf.append("\r\n");
}
sbuf.append("......");
sbuf.append("\r\n");
}
else {
sbuf.append("null");
sbuf.append("\r\n");
}
sbuf.append("\r\n");
// 是否 写入 文件
if (Boolean.valueOf(Resource.getProperties().get(Constant.IS_WRITE_LOGFILE))) {
WritefileThread.getStrArray().add(sbuf.toString());
}
}
/**
* @ msg
* @return msg
*/
public String getMsg() {
return msg;
}
/**
* @ objArray
* @return objArray
*/
public Object[] getObjArray() {
return objArray;
}
/**
* @ cause
* @return cause
*/
public Throwable getCause() {
return cause;
}
}

@ -0,0 +1,383 @@
package com.base;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.filechooser.FileSystemView;
/**
* @
* @author chen
* @date 201688
* @package com.utils
*/
public class FileOperate {
private final static String localDiskName = "本地磁盘";
private final static String enlocalDiskName = "Local Disk";
private final static String CD = "CD";
private final static String DVD = "DVD";
public static String usbPath = "";
/**
* @
*
* @return
*/
public static List<String> filterDiskPath() {
FileSystemView fileSystemView = FileSystemView.getFileSystemView();
List<String> diskPathName = new ArrayList<String>();
File[] roots = File.listRoots();
for (File file : roots) {
String diskName = fileSystemView.getSystemTypeDescription(file);// 获取磁盘的类型描述信息
if (diskName.startsWith(localDiskName) || diskName.startsWith(enlocalDiskName) || diskName.contains(CD)
|| diskName.contains(CD) || diskName.contains(DVD)) // 当磁盘为可移动磁盘时{
continue;
diskPathName.add(file.getAbsolutePath());
}
return diskPathName;
}
/**
* @
* @param path
*
* @param dirName
*
* @return
*/
public static int createDir(String path, String dirName) {
File dirFile = new File(path + "\\" + dirName);
if (!dirFile.exists()) {
if (!dirFile.mkdirs()) {
System.out.println("目录不存在,创建失败!");
return 2;
}
return 1;
}
return 0;
}
/**
* @
*
* @param path
*
* @return
*/
public static boolean isFileExists(String path) {
File file = new File(path);
if (file.exists())
return true;
return false;
}
/**
* @
*
* @param name
*
* @return
*/
public static boolean file_dir_exist(String name) {
try {
File file = new File(name);
if (!file.exists()) {
return false;
// return true;
}
}
catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
/**
* @ 26
* @param length
*
* @return
*/
public static String getRandomString(int length) { // length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* @
* @param fiel_name
*
* @return
*/
public static String read_fileToStr(String fiel_name) {
String str = "";
try {
File file = new File(fiel_name);
String lineTxt = "";
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "gbk");// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
while ((lineTxt = bufferedReader.readLine()) != null) {
str = str + lineTxt;
}
bufferedReader.close();
read.close();
}
catch (Exception e) {
e.printStackTrace();
return "Exception";
}
return str;
}
/**
* @
* @param path_filename
*
* @return
*/
public static String get_filename_from_path(String path_filename) {
String[] strings = path_filename.split("\\\\");
return strings[strings.length - 1];
}
/**
* @ dirPath
* @param dirPath
*
* @return
*/
public static List<String> findAllFilenameFromPath(String dirPath) {
ArrayList<String> fileAbsolutePaths = new ArrayList<>();
FileOperate.findFiles(dirPath, fileAbsolutePaths);
return fileAbsolutePaths;
}
/**
* @
* @param dirPath
*
* @return
*/
public static boolean delAllFileByDir(String dirPath) {
boolean flag = false;
File file = new File(dirPath);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
}
else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(dirPath);
}
else { // 为目录时调用删除目录方法
return deleteDirectory(dirPath);
}
}
}
/**
* @
* @param content
*
* @param filePathName
*
*/
public static void writeFile(List<Object> content, String filePathName) {
if (null == content) {
return;
}
try {
FileWriter writer = new FileWriter(filePathName);
for (Object one : content) {
writer.write(one.toString());
writer.write("\r\n");
}
writer.close();
}
catch (Exception e) {
// TODO: handle exception
// e.printStackTrace();
}
}
/**
* @
* @param content
* @param filePathName
*/
public static void appendWriteFile(String content, String filePathName){
File file = new File(filePathName);
if (!file.exists() || !file.isFile()) {
ArrayList<Object> list = new ArrayList<>();
list.add("系统异常日志\n");
writeFile(list, filePathName);
}
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(filePathName, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
// randomFile.writeBytes(content);
//解决中文乱码
randomFile.write(content.getBytes());
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @
* @param fileName
*
*/
public static boolean islockFile(String fileName) {
Object result = null;
boolean isSuccess = true;
try {
result = tryLock(fileName);
if (null == result) {
isSuccess = false;
}
}
catch (IOException e) {
e.printStackTrace();
isSuccess = false;
}
return isSuccess;
}
/**
* @
* @param dirPath
*
* @return
*/
private static boolean deleteDirectory(String dirPath) {
// 如果sPath不以文件分隔符结尾自动添加文件分隔符
if (!dirPath.endsWith(File.separator)) {
dirPath = dirPath + File.separator;
}
File dirFile = new File(dirPath);
// 如果dir对应的文件不存在或者不是一个目录则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
}
else {
return false;
}
}
/**
* @
* @param filePath
*
* @return
*/
private static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* @ dirPath
* @param dirPath
*
* @param fileAbsolutePaths
*
* @return
*/
private static List<String> findFiles(String dirPath, List<String> fileAbsolutePaths) {
File file = new File(dirPath);
// 是文件时
if (!file.isDirectory()) {
String path = file.getAbsolutePath();
fileAbsolutePaths.add(path);
}
// 是文件夹时
else if (file.isDirectory()) {
String[] filelist = file.list();
if (null != filelist) {
int fileNum = filelist.length;
for (int i = 0; i < fileNum; i++) {
String tempPath = dirPath + "\\" + filelist[i];
findFiles(tempPath, fileAbsolutePaths);
}
}
}
return fileAbsolutePaths;
}
/**
* @
* @param fileName
* @return
* @throws IOException
*/
@SuppressWarnings("resource")
private static FileLock tryLock(String fileName) throws IOException {
File lockF = new File(fileName); // 要锁的文件
lockF.deleteOnExit(); // 指定在退出时释放锁
RandomAccessFile file = new RandomAccessFile(lockF, "rws"); // 指定要锁的文件
FileLock res = null;
try {
res = file.getChannel().tryLock(); // 试图取得文件的锁
}
catch (Exception e) { // 文件被其它线程锁时抛出此异常
file.close();
return null;
}
return res;
}
}

@ -0,0 +1,79 @@
package com.base;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import com.base.Constant;
public class Resource {
private static Map<String, String> properties = new HashMap<>();
static{
// 读取 properties文件
// readPropertiesFile(Constant.SYSTEM_PROPERTIES_FIEL_PATH);
readPropertiesFile4Chinese(Constant.I18N_PROPERTIES_FIEL_PATH);
}
/**
* @
* @param filename "/com/utils/exception/i18n.properties"
*/
public static void readPropertiesFile4Chinese(String filename) {
Properties pro = new Properties();
try {
// 读取属性文件 XXXX.propertiesReader。writer解决中文乱码
// InputStreamReader in= new InputStreamReader(Resource.class.getClassLoader().getResourceAsStream(filename), "UTF-8");
InputStreamReader in= new InputStreamReader(Resource.class.getResourceAsStream(filename), "UTF-8");
BufferedReader bf = new BufferedReader(in);
// InputStreamReader in = new BufferedInputStream(new FileInputStream(filename));
pro.load(bf); // /加载属性列表
Iterator<String> it = pro.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
properties.put(key, pro.getProperty(key));
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @ properties
* @return properties
*/
public static Map<String, String> getProperties() {
return properties;
}
/**
* @
* @param filename
*/
public static void readPropertiesFile(String filename) {
Properties pro = new Properties();
try {
// 读取属性文件 XXXX.properties 中文会 乱码)
BufferedInputStream bf = new BufferedInputStream(new FileInputStream(filename));
pro.load(bf); // /加载属性列表
Iterator<String> it = pro.stringPropertyNames().iterator();
while (it.hasNext()) {
String key = it.next();
properties.put(key, pro.getProperty(key));
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,68 @@
package com.base;
import java.util.ArrayList;
import java.util.List;
import com.base.Constant;
/**
* @ --system_exception.txt
* @author chen
* @date 2016830
* @package com.utils.exception
*/
public class WritefileThread extends Thread implements Runnable{
/** 存储异常信息 */
private static List<String> strArray = new ArrayList<>();
/** 是否继续运行 */
private static boolean isContinue = true;
@Override
public void run() {
super.run();
while(isContinue){
try {
Thread.sleep(Constant.THREAD_SLEEP_WRITEFILETHREAD);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (strArray) {
//同步代码--写入日志
String str = array2Str(strArray);
//TODO FileOperate.appendWriteFile(str, Constant.SYSTEM_EXCEPTION_FILEPATH);
strArray.clear();
}
}
}
/**
* @ strArray
* @return strArray
*/
public static List<String> getStrArray() {
return strArray;
}
/**
* @ isContinue
* @param isContinue
*/
public static void setContinue(boolean isContinue) {
WritefileThread.isContinue = isContinue;
}
/**
* @ list --> String
* @param array arrayList
* @return String
*/
@SuppressWarnings("rawtypes")
private static String array2Str(List array) {
StringBuffer sbuf = new StringBuffer();
for (Object object : array) {
sbuf.append(object);
}
return sbuf.toString();
}
}

@ -14,6 +14,7 @@ import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.base.BaseController;
import com.platform.entities.PagerOptions; import com.platform.entities.PagerOptions;
import com.platform.service.DataInfoService; import com.platform.service.DataInfoService;
import com.platform.service.OracleStatusService; import com.platform.service.OracleStatusService;
@ -21,7 +22,7 @@ import com.platform.utils.Configs;
import com.platform.utils.UtilsHelper; import com.platform.utils.UtilsHelper;
@Controller @Controller
public class DataModelController { public class DataModelController extends BaseController{
@Resource(name = "dataInfoService") @Resource(name = "dataInfoService")
private DataInfoService dfs; private DataInfoService dfs;

@ -7,10 +7,13 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import com.base.BaseController;
import com.base.CustomException;
import com.base.Resource;
import com.platform.utils.Configs; import com.platform.utils.Configs;
@Controller @Controller
public class DefaultController { public class DefaultController extends BaseController{
@RequestMapping("/") @RequestMapping("/")
public ModelAndView defaultHandler(HttpServletRequest req, HttpServletResponse res){ public ModelAndView defaultHandler(HttpServletRequest req, HttpServletResponse res){
//处理不匹配的请求 //处理不匹配的请求
@ -20,9 +23,15 @@ public class DefaultController {
} }
@RequestMapping("/test") @RequestMapping("/test")
public void test(HttpServletRequest req, HttpServletResponse res){ public void test(HttpServletRequest req, HttpServletResponse res) throws CustomException{
//System.out.println(Class.class.getClass().getResource("/").getPath()); //System.out.println(Class.class.getClass().getResource("/").getPath());
new Resource();
System.out.println(Configs.EXTRACT_LOG_LOCALTION); System.out.println(Configs.EXTRACT_LOG_LOCALTION);
boolean istrue = true;
if (istrue) {
throw new CustomException("3212", null);
}
System.out.println("end");
} }
} }

@ -8,8 +8,10 @@ package com.platform.entities;
* *
*/ */
public class EncodedInfoEntity { public class EncodedInfoEntity {
private String name; //Ãû³Æ /** Ãû³Æ */
private String code; //±àÂë private String name;
/** ±àÂë */
private String code;
public EncodedInfoEntity() {} public EncodedInfoEntity() {}

@ -0,0 +1,23 @@
/**
* ResourceTest.java
* : XX
* : <>
* 201697
* <>
*/
package com.test.base;
import java.io.InputStream;
import com.base.Constant;
import com.base.Resource;
public class ResourceTest {
public static void main(String[] args) {
Resource ss = new Resource();
Resource.readPropertiesFile(Constant.SYSTEM_PROPERTIES_FIEL_PATH);
}
}
Loading…
Cancel
Save