├── src ├── other.properties ├── com │ └── jzero │ │ ├── upload │ │ ├── vssver2.scc │ │ ├── ffmpeg获取视频时长.txt │ │ ├── MDown.java │ │ ├── MFFmpeg.java │ │ └── MImageTools.java │ │ ├── log │ │ ├── LogEnum.java │ │ └── Log.java │ │ ├── cache │ │ ├── Test.java │ │ ├── Cache.java │ │ ├── CacheManager.java │ │ └── C.java │ │ ├── pool │ │ ├── IPool.java │ │ ├── BasePool.java │ │ ├── PoolFactory.java │ │ ├── ProxoolPool.java │ │ ├── BoneCpPool.java │ │ └── C3poPool.java │ │ ├── db │ │ ├── back │ │ │ ├── MBackup.java │ │ │ ├── SqliteBack.java │ │ │ └── MysqlBack.java │ │ ├── cache │ │ │ ├── ICache.java │ │ │ ├── MFile.java │ │ │ └── MCache.java │ │ ├── core │ │ │ ├── COracle.java │ │ │ ├── IDb.java │ │ │ ├── CMySQL.java │ │ │ └── CSqlite.java │ │ ├── utility │ │ │ ├── MFieldDb.java │ │ │ ├── MSqlite.java │ │ │ ├── MssqlDb.java │ │ │ └── MysqlDb.java │ │ └── exp │ │ │ ├── MDbTool.java │ │ │ └── MHandler.java │ │ ├── util │ │ ├── MPrint.java │ │ ├── MSession.java │ │ ├── MEnum.java │ │ ├── MCheck.java │ │ ├── MySQL.java │ │ ├── Msg.java │ │ ├── MImage.java │ │ ├── MSee.java │ │ ├── MPro.java │ │ ├── MCnt.java │ │ ├── MEncrypt.java │ │ ├── MDate.java │ │ ├── MCookie.java │ │ ├── MPath.java │ │ ├── MDividPage.java │ │ └── MMD5.java │ │ ├── aop │ │ └── Uncheck.java │ │ ├── render │ │ ├── MJspRender.java │ │ ├── M301Render.java │ │ ├── MRender.java │ │ ├── MJsonRender.java │ │ ├── M500Render.java │ │ ├── MTextRender.java │ │ ├── MB.java │ │ ├── M404Render.java │ │ └── MImaRender.java │ │ ├── json │ │ ├── Test.java │ │ ├── JSONObj.java │ │ └── JSONTool.java │ │ ├── core │ │ ├── MInit.java │ │ ├── MReport.java │ │ ├── MURI.java │ │ └── MRouter.java │ │ ├── token │ │ └── MToken.java │ │ ├── filter │ │ └── JFilter.java │ │ ├── i18n │ │ └── I18N.java │ │ └── comm │ │ └── MCommHelp.java ├── routes.properties ├── database.properties ├── log4j.properties └── config.properties ├── WebRoot ├── META-INF │ └── MANIFEST.MF └── WEB-INF │ └── web.xml ├── README.md ├── .mymetadata ├── .gitattributes ├── 控制器操作 ├── 简单使用 ├── .gitignore └── 视图操作 /src/other.properties: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /WebRoot/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /src/com/jzero/upload/vssver2.scc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hubs/JZero/master/src/com/jzero/upload/vssver2.scc -------------------------------------------------------------------------------- /src/com/jzero/upload/ffmpeg获取视频时长.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hubs/JZero/master/src/com/jzero/upload/ffmpeg获取视频时长.txt -------------------------------------------------------------------------------- /src/com/jzero/log/LogEnum.java: -------------------------------------------------------------------------------- 1 | package com.jzero.log; 2 | 3 | /** 2012-10-3 */ 4 | public enum LogEnum { 5 | NONE,ERROR, DEBUG, INFO, ALL 6 | } 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | JZero 2 | ===== 3 | 4 | JZero=Codeigniter+JFinal 5 | 6 | 一个简单的Java Servlet框架,框架的主要思想来源于 Codeigniter与JFinal二大框架,目前自已使用于公司的项目中. 7 | 8 | JZero会根据当前项目中出现的问题进一步完善. 9 | 10 | -------------------------------------------------------------------------------- /src/routes.properties: -------------------------------------------------------------------------------- 1 | controller_package=com.gl.action 2 | default_controller=Welcome 3 | default_method=index 4 | backstage_package=backstage,xitong 5 | default_view =/xitong/login/login.jsp 6 | 7 | -------------------------------------------------------------------------------- /src/database.properties: -------------------------------------------------------------------------------- 1 | hostname=localhost 2 | username=0CDCEBEDC74CCAED 3 | password=031C707A09F97905BF3A1701246E7F40 4 | database=gldcj 5 | #sqlite 6 | dbdriver=mysql 7 | port=3306 8 | cache_on=true 9 | -------------------------------------------------------------------------------- /src/com/jzero/cache/Test.java: -------------------------------------------------------------------------------- 1 | package com.jzero.cache; 2 | 3 | import com.jzero.util.MPrint; 4 | 5 | public class Test { 6 | 7 | public static void main(String[] args) { 8 | MPrint.print(CacheManager.me().toString()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/com/jzero/pool/IPool.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.pool; 3 | 4 | import java.sql.Connection; 5 | 6 | /** 2012-10-3 */ 7 | public interface IPool { 8 | Connection getConnection(String driver,String url,String user,String pass); 9 | } 10 | -------------------------------------------------------------------------------- /src/com/jzero/db/back/MBackup.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.db.back; 3 | 4 | import com.jzero.util.MRecord; 5 | 6 | 7 | /** 8 | * 2012-10-24: 9 | * wangujqw@gmail.com 10 | */ 11 | public interface MBackup { 12 | MRecord backup(); 13 | void load(String filename); 14 | } 15 | -------------------------------------------------------------------------------- /.mymetadata: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/com/jzero/util/MPrint.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | public class MPrint { 4 | private static String identifying="-------"; 5 | public static void print(Object obj){ 6 | System.out.println(identifying+"【程序调试打印数据:"+obj+"】"+identifying); 7 | } 8 | public static void print(Object ...objects ){ 9 | System.out.println(objects); 10 | } 11 | public static void print(Object obj1 ,Object obj2,Object ...obj3){ 12 | System.out.println(obj1+" \t "+obj2+"\t"+obj3); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/com/jzero/db/cache/ICache.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.cache; 2 | 3 | import java.io.File; 4 | import java.util.List; 5 | 6 | import com.jzero.util.MRecord; 7 | /** 8 | * 2012-10-3:此类主要用于将查询出来的数据写入文件中,当下次查询相同的数据时,直接从文件中读取显示 9 | */ 10 | public interface ICache { 11 | File get_path(String sql); 12 | 13 | void write(String sql, List lst); 14 | public List read(String sql); 15 | 16 | void delete(String sql); 17 | 18 | public void delete_all(); 19 | 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/com/jzero/aop/Uncheck.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.aop; 3 | 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Inherited; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * 2012-11-13:应用于类名上,表示当前类不会检测是否已存在session值 12 | * wangujqw@gmail.com 13 | */ 14 | @Inherited 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Target({ElementType.TYPE,ElementType.METHOD}) 17 | public @interface Uncheck { 18 | } 19 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /src/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=error,stdout, R 2 | 3 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 4 | log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 | 6 | log4j.appender.stdout.layout.ConversionPattern=%5p - %m%n 7 | 8 | log4j.appender.R=org.apache.log4j.RollingFileAppender 9 | log4j.appender.R.File=firestorm.log 10 | 11 | log4j.appender.R.MaxFileSize=100KB 12 | log4j.appender.R.MaxBackupIndex=1 13 | 14 | log4j.appender.R.layout=org.apache.log4j.PatternLayout 15 | log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n 16 | 17 | log4j.logger.com.codefutures=error -------------------------------------------------------------------------------- /src/com/jzero/db/core/COracle.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.core; 2 | 3 | import java.util.List; 4 | 5 | import com.jzero.util.MRecord; 6 | 7 | public class COracle extends CBase { 8 | 9 | @Override 10 | public List pager(String table, String where, String field, 11 | int current, int pageSize, Object... params) { 12 | return null; 13 | } 14 | 15 | @Override 16 | public List pager_sql(String sql, int current, int pageSize, 17 | Object... params) { 18 | return null; 19 | } 20 | 21 | @Override 22 | public MRecord select_one(String table, String where, String field, 23 | boolean cache, Object... params) { 24 | return null; 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/com/jzero/render/MJspRender.java: -------------------------------------------------------------------------------- 1 | package com.jzero.render; 2 | 3 | import com.jzero.log.Log; 4 | 5 | /** 6 | * 2012-10-3: 来源于JFinal wangujqw@gmail.com 7 | */ 8 | class MJspRender extends MRender { 9 | 10 | private static final long serialVersionUID = 1L; 11 | 12 | 13 | public MJspRender() { 14 | } 15 | 16 | public MJspRender(String view) { 17 | setView(view); 18 | } 19 | 20 | public void render() { 21 | try { 22 | request.getRequestDispatcher(getView()).forward(request, response); 23 | } catch (Exception e) { 24 | Log.me().write_error(e); 25 | } 26 | } 27 | 28 | 29 | @Override 30 | public boolean isJsp() { 31 | // TODO Auto-generated method stub 32 | return true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/com/jzero/pool/BasePool.java: -------------------------------------------------------------------------------- 1 | package com.jzero.pool; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | 6 | import com.jzero.core.MInit; 7 | import com.jzero.log.Log; 8 | import com.jzero.log.LogEnum; 9 | 10 | /** 2012-10-3 */ 11 | public class BasePool implements IPool { 12 | 13 | public Connection getConnection(String driver, String url, String user, 14 | String pass) { 15 | Connection connection = null; 16 | try { 17 | Class.forName(driver); 18 | connection = DriverManager.getConnection(url, user, pass); 19 | } catch (Exception e) { 20 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 21 | MInit.get().getMb().getTextRender(e.getMessage()).render(); 22 | } 23 | return connection; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/com/jzero/db/back/SqliteBack.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.back; 2 | 3 | import java.io.File; 4 | 5 | import com.jzero.db.core.M; 6 | import com.jzero.util.MDate; 7 | import com.jzero.util.MRecord; 8 | import com.jzero.util.MTool; 9 | 10 | public class SqliteBack implements MBackup { 11 | 12 | public MRecord backup() { 13 | MRecord record = new MRecord(); 14 | String backName = MDate.get_ymd_hms_join() + ".db"; 15 | record.set("name", backName); 16 | try { 17 | M.me().execute("backup to " + backName); 18 | record.set("size", MTool.formart_bytes(new File(backName))); 19 | } catch (Exception e) { 20 | e.printStackTrace(); 21 | } 22 | return record; 23 | } 24 | 25 | public void load(String filename) { 26 | M.me().execute("restore from " + filename); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /WebRoot/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | MFilter 9 | com.jzero.filter.JFilter 10 | 11 | cache 12 | 3600 13 | 14 | 15 | 16 | MFilter 17 | /* 18 | 19 | 20 | 21 | index.jsp 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/com/jzero/pool/PoolFactory.java: -------------------------------------------------------------------------------- 1 | package com.jzero.pool; 2 | 3 | import java.sql.Connection; 4 | 5 | import com.jzero.db.exp.MDbTool; 6 | import com.jzero.log.Log; 7 | import com.jzero.log.LogEnum; 8 | import com.jzero.util.MPro; 9 | import com.jzero.util.MRecord; 10 | 11 | /** 2012-10-3 */ 12 | public final class PoolFactory { 13 | 14 | public static Connection getConnection() { 15 | MRecord record = MDbTool.getDbConnectInfo(); 16 | String pool_name="com.jzero.pool."+MPro.me().getStr("pool"); 17 | IPool pool = null; 18 | try { 19 | pool = (IPool) Class.forName(pool_name).newInstance(); 20 | } catch (Exception e) { 21 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 22 | } 23 | String driver = record.getStr("driver"); 24 | String url = record.getStr("url"); 25 | String user = record.getStr("user"); 26 | String pass = record.getStr("pass"); 27 | return pool.getConnection(driver, url, user, pass); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/com/jzero/db/utility/MFieldDb.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.db.utility; 3 | 4 | import java.util.List; 5 | 6 | import com.jzero.util.MRecord; 7 | 8 | /** 9 | * --- 2012-4-9 --- 10 | * DbField.java : 用于操作指定表中的表字段。 11 | */ 12 | public interface MFieldDb { 13 | 14 | /** 15 | *得到数据库中的所有的表 16 | */ 17 | List getAllTable(); 18 | 19 | /** 20 | * 得到指定表中的字段,getCommentAndFieldName(),getDefaultAndFieldName()从此方法返回的值取数据。 21 | */ 22 | List getFieldForTable(String tableName); 23 | 24 | /** 25 | * 得到表结构中的字段名与备注信息 26 | */ 27 | List getCommentAndFieldName(String tableName); 28 | 29 | /** 30 | * 得到表结构中的默认值与备注信息 31 | */ 32 | List getDefaultAndFieldName(String tableName); 33 | 34 | /** 35 | * 得到表中的默认值,备注信息与表字段 36 | * 默认值用来判断是什么类型(text,data,select...准备在高搜索中使用) 37 | */ 38 | List getSelectField(String tableName); 39 | 40 | String get_pager_sql(String table, String where,String field, int current,int pageSize, Object... obj); 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/com/jzero/cache/Cache.java: -------------------------------------------------------------------------------- 1 | package com.jzero.cache; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Cache implements Serializable { 6 | private static final long serialVersionUID = 1L; 7 | private String key; 8 | private Object value; 9 | private long timeOut; 10 | private boolean expired; 11 | 12 | public Cache() { 13 | super(); 14 | } 15 | 16 | public Cache(String key, String value, long timeOut, boolean expired) { 17 | this.key = key; 18 | this.value = value; 19 | this.timeOut = timeOut; 20 | this.expired = expired; 21 | } 22 | 23 | public String getKey() { 24 | return key; 25 | } 26 | 27 | public long getTimeOut() { 28 | return timeOut; 29 | } 30 | 31 | public Object getValue() { 32 | return value; 33 | } 34 | 35 | public void setKey(String string) { 36 | key = string; 37 | } 38 | 39 | public void setTimeOut(long l) { 40 | timeOut = l; 41 | } 42 | 43 | public void setValue(Object object) { 44 | value = object; 45 | } 46 | 47 | public boolean isExpired() { 48 | return expired; 49 | } 50 | 51 | public void setExpired(boolean b) { 52 | expired = b; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/com/jzero/util/MSession.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.jzero.core.MR; 7 | 8 | public class MSession { 9 | 10 | private static List userList = new ArrayList(); 11 | 12 | public static void save(MRecord obj) { 13 | MR.me().setSessionAttr(Msg.USER_NAME, obj); 14 | userList.add(obj.get("xm")); 15 | } 16 | 17 | public static MRecord get() { 18 | MRecord record=MR.me().getSessionAttr(Msg.USER_NAME); 19 | return MCheck.isNull(record)?null:record; 20 | } 21 | public static String getName(){ 22 | return MCheck.isNull(get())?"":get().getStr("xm"); 23 | } 24 | 25 | public static void clear() { 26 | MRecord record=get(); 27 | if(!MCheck.isNull(record)){ 28 | MR.me().removeSessionAttr(Msg.USER_NAME); 29 | if(userList.contains(record.get("xm"))){ 30 | userList.remove(record.get("xm")); 31 | } 32 | } 33 | MPrint.print(record.get("xm")+" is out!"); 34 | 35 | } 36 | 37 | public static void loopCurrUser() { 38 | for (Object s : userList) { 39 | MPrint.print("Now online user =>"+s); 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /src/com/jzero/render/M301Render.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.render; 3 | 4 | import javax.servlet.http.HttpServletResponse; 5 | 6 | /** 7 | * 2012-10-3: 来源于JFinal 8 | * wangujqw@gmail.com 9 | */ 10 | class M301Render extends MRender { 11 | 12 | private static final long serialVersionUID = 6487819781831800339L; 13 | private String url; 14 | private boolean withOutQueryString; 15 | 16 | public M301Render(String url) { 17 | this.url = url; 18 | this.withOutQueryString = false; 19 | } 20 | 21 | public M301Render(String url, boolean withOutQueryString) { 22 | this.url = url; 23 | this.withOutQueryString = withOutQueryString; 24 | } 25 | 26 | public void render() { 27 | if (withOutQueryString == false) { 28 | String queryString = request.getQueryString(); 29 | queryString = (queryString == null ? "" : "?" + queryString); 30 | url = url + queryString; 31 | } 32 | 33 | response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); 34 | response.setHeader("Location", url); 35 | response.setHeader("Connection", "close"); 36 | } 37 | 38 | @Override 39 | public boolean isJsp() { 40 | return false; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/com/jzero/pool/ProxoolPool.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.pool; 3 | 4 | import java.sql.Connection; 5 | 6 | import org.logicalcobwebs.proxool.ProxoolDataSource; 7 | 8 | import com.jzero.core.MInit; 9 | import com.jzero.log.Log; 10 | import com.jzero.log.LogEnum; 11 | 12 | /** 2012-10-3 */ 13 | public class ProxoolPool implements IPool { 14 | 15 | public Connection getConnection(String driver, String url, String user, 16 | String pass) { 17 | Connection connection=null; 18 | try { 19 | ProxoolDataSource config=new ProxoolDataSource(); 20 | config.setDriverUrl(url); 21 | config.setUser(user); 22 | config.setPassword(pass); 23 | config.setHouseKeepingSleepTime(9000); 24 | config.setMaximumConnectionCount(100); 25 | config.setMinimumConnectionCount(10); 26 | config.setMaximumActiveTime(20); 27 | config.setTestBeforeUse(true); 28 | config.setHouseKeepingTestSql("select 1"); 29 | config.setDriver(driver); 30 | connection=config.getConnection(); 31 | } catch (Exception e) { 32 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 33 | MInit.get().getMb().getTextRender(e.getMessage()).render(); 34 | } 35 | return connection; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /控制器操作: -------------------------------------------------------------------------------- 1 | 2 | package com.gl.action.backstage; 3 | 4 | import com.gl.utils.MMsg; 5 | import com.jzero.comm.MComm; 6 | import com.jzero.core.MR; 7 | import com.jzero.util.MDate; 8 | import com.jzero.util.MRecord; 9 | import com.jzero.util.MSession; 10 | 11 | /** 12 | * 友情链接 13 | * wangujqw@gmail.com 14 | */ 15 | public class Friend { 16 | 17 | public void index(){ 18 | MComm.me().m_list(MMsg.WZ_FRIEND, new Object[]{"order by lrry desc"}); 19 | } 20 | public void find(){ 21 | MComm.me().m_find(MMsg.WZ_FRIEND, new Object[]{"order by lrry desc"}); 22 | } 23 | public void add(){ 24 | MComm.me().m_add(); 25 | } 26 | public void save(){ 27 | MRecord in=MR.me().getPara(); 28 | in.set("lrrq", MDate.get_ymd_hms()).set("lrry", MSession.getName()); 29 | MComm.me().m_save(MMsg.WZ_FRIEND,in); 30 | } 31 | public void edit(){ 32 | MComm.me().m_edit(MMsg.WZ_FRIEND,3); 33 | } 34 | public void update(){ 35 | MComm.me().m_update(MMsg.WZ_FRIEND); 36 | } 37 | public void del(){ 38 | MComm.me().m_del(MMsg.WZ_FRIEND,3); 39 | } 40 | public void view(){ 41 | MComm.me().m_view(MMsg.WZ_FRIEND,3); 42 | } 43 | public void batch(){ 44 | MComm.me().m_batch_del(MMsg.WZ_FRIEND); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /简单使用: -------------------------------------------------------------------------------- 1 | 2 | 3 | package com.gl.action.backstage; 4 | 5 | import com.gl.utils.MMsg; 6 | import com.jzero.comm.MComm; 7 | import com.jzero.core.MR; 8 | import com.jzero.util.MDate; 9 | import com.jzero.util.MRecord; 10 | import com.jzero.util.MSession; 11 | 12 | /** 13 | * 2012-11-15: 友情链接 14 | * wangujqw@gmail.com 15 | */ 16 | public class Friend { 17 | 18 | public void index(){ 19 | MComm.me().m_list(MMsg.WZ_FRIEND, new Object[]{"order by lrry desc"}); 20 | } 21 | public void find(){ 22 | MComm.me().m_find(MMsg.WZ_FRIEND, new Object[]{"order by lrry desc"}); 23 | } 24 | public void add(){ 25 | MComm.me().m_add(); 26 | } 27 | public void save(){ 28 | MRecord in=MR.me().getPara(); 29 | in.set("lrrq", MDate.get_ymd_hms()).set("lrry", MSession.getName()); 30 | MComm.me().m_save(MMsg.WZ_FRIEND,in); 31 | } 32 | public void edit(){ 33 | MComm.me().m_edit(MMsg.WZ_FRIEND,3); 34 | } 35 | public void update(){ 36 | MComm.me().m_update(MMsg.WZ_FRIEND); 37 | } 38 | public void del(){ 39 | MComm.me().m_del(MMsg.WZ_FRIEND,3); 40 | } 41 | public void view(){ 42 | MComm.me().m_view(MMsg.WZ_FRIEND,3); 43 | } 44 | public void batch(){ 45 | MComm.me().m_batch_del(MMsg.WZ_FRIEND); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/com/jzero/db/core/IDb.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.core; 2 | 3 | import java.sql.Connection; 4 | import java.util.List; 5 | 6 | import com.jzero.db.core.CBase.ITX; 7 | import com.jzero.util.MRecord; 8 | 9 | /** 10 | * 2012-10-3: wangujqw@gmail.com 11 | */ 12 | public interface IDb { 13 | 14 | Connection getConnection(); 15 | 16 | String getSQLVersion(); 17 | 18 | boolean isConnect(); 19 | 20 | List select(String sql, Object... params); 21 | 22 | List select(String table, String where, String field,Object... params); 23 | MRecord select_one(String table, String where, String field,boolean cache,Object... params); 24 | 25 | List pager(String table, String where,String field, int current, int pageSize,Object... params); 26 | List pager_sql(String sql,int current,int pageSize,Object ...params); 27 | 28 | int update(String sql, Object... params); 29 | 30 | int update(String table, MRecord record, String where); 31 | 32 | void insert_batch(String sql, Object[][] params); 33 | 34 | int insert(String table, MRecord record); 35 | 36 | int delete(String table, String where); 37 | 38 | MRecord one_s(String sql, Object... params); 39 | 40 | 41 | boolean is_show_sql(); 42 | 43 | boolean tx(ITX tx); 44 | } 45 | -------------------------------------------------------------------------------- /src/config.properties: -------------------------------------------------------------------------------- 1 | #log记录级别 NO,ERROR, DEBUG, INFO, ALL 2 | log_enabled=true 3 | log_level=ERROR 4 | log_reload=false 5 | 6 | #cookie管理,MToken 7 | cookie_prefix= 8 | cookie_domain=null 9 | cookie_path=/ddsx 10 | 11 | #INPUT 12 | charset=UTF-8 13 | #GLOBAL XSSFiltering INPUT 14 | global_xss_filtering=TRUE 15 | 16 | 17 | #token管理 18 | #是否开启验证MR 19 | csrf_protection=false 20 | csrf_token_name=csrf_jzero 21 | csrf_cookie_name=csrf_cookie_name 22 | #秒,二个小时 23 | csrf_expire=7200 24 | 25 | #是否开启压缩页面,还未实现,可参考多个filter拦截实现 26 | compress_output=false 27 | 28 | #pool 暂时实现的有 BoneCpPool,C3poPool,BasePool,ProxoolPool 29 | pool=C3poPool 30 | #数据库读取等待的最大时间(秒) 31 | db_max_time=60 32 | #数据库类型,暂时只实现了MySQL,CSqlite,其它的以后再完善 33 | db_type=CMySQL 34 | 35 | #显示参数项 properties 36 | show_prop=false 37 | #打印出当条语句执行的类与方法 38 | is_dev=true 39 | #查看当条SQL运行的时间 40 | show_run_time=false 41 | #是否显示执行的sql 42 | show_sql=true 43 | 44 | #充许URI字符 URI 45 | permitted_uri_chars=\\w*[,]*\\w*[,]*\\w*[,]*\\w*[,]*\\w[_]*\\w* 46 | 47 | sess_expiration =15 48 | sess_match_ip=true 49 | #是否需要需要浏览器 50 | sess_match_useragent=true 51 | 52 | #显示文件名后辍 53 | suffix="" 54 | DEFAULT_I18N_MAX_AGE_OF_COOKIE = 999999999; 55 | 56 | #cache_time//默认缓存3分钟 57 | cache_time=3 58 | 59 | 60 | -------------------------------------------------------------------------------- /src/com/jzero/render/MRender.java: -------------------------------------------------------------------------------- 1 | package com.jzero.render; 2 | 3 | import java.io.Serializable; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | /** 9 | * 2012-10-3: 主要用于页面的渲染,来源于JFinal wangujqw@gmail.com 10 | */ 11 | public abstract class MRender implements Serializable { 12 | 13 | private static final long serialVersionUID = 1617632731853793227L; 14 | protected String view=null; 15 | protected transient HttpServletRequest request; 16 | protected transient HttpServletResponse response; 17 | 18 | final static String getEncoding() { 19 | return "UTF-8"; 20 | } 21 | 22 | public final MRender setContext(HttpServletRequest request, 23 | HttpServletResponse response) { 24 | this.request = request; 25 | this.response = response; 26 | return this; 27 | } 28 | 29 | public final MRender setContext(HttpServletRequest request, 30 | HttpServletResponse response, String viewPath) { 31 | this.request = request; 32 | this.response = response; 33 | if (viewPath != null && !viewPath.startsWith("/")) 34 | viewPath ="/"+ viewPath; 35 | setView(viewPath); 36 | return this; 37 | } 38 | 39 | /** 40 | * Render to client 41 | */ 42 | public abstract void render(); 43 | public abstract boolean isJsp(); 44 | 45 | public String getView() { 46 | return view; 47 | } 48 | 49 | public void setView(String view) { 50 | this.view = view; 51 | } 52 | } -------------------------------------------------------------------------------- /src/com/jzero/util/MEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * --- 2011-10-25 --- 3 | * --- Administrator --- 4 | * MyEnum.java : 所有操作类型 5 | */ 6 | package com.jzero.util; 7 | 8 | public enum MEnum { 9 | LT("<"), GT(">"), EQ("="), LT_E("<="), GT_E(">="), LIKE("LIKE"), OR("OR"), NOT( 10 | "NOT"), IN("IN"), NOT_IN("NOT_IN"), BETWEEN("BETWEEN"), AND("AND"),NOT_EQ(" !="); 11 | 12 | private final String value; 13 | 14 | private MEnum(String value) { 15 | this.value = value; 16 | } 17 | 18 | public String getValue() { 19 | return value; 20 | } 21 | 22 | public static String get(MEnum e) { 23 | String str = null; 24 | switch (e) { 25 | case LT: 26 | str = MEnum.LT.getValue(); 27 | break; 28 | case GT: 29 | str = MEnum.GT.getValue(); 30 | break; 31 | case EQ: 32 | str = MEnum.EQ.getValue(); 33 | break; 34 | case LT_E: 35 | str = MEnum.LT_E.getValue(); 36 | break; 37 | case GT_E: 38 | str = MEnum.GT_E.getValue(); 39 | break; 40 | case LIKE: 41 | str = MEnum.LIKE.getValue(); 42 | break; 43 | case NOT: 44 | str = MEnum.NOT.getValue(); 45 | break; 46 | case IN: 47 | str = MEnum.IN.getValue(); 48 | break; 49 | case NOT_IN: 50 | str = MEnum.NOT_IN.getValue(); 51 | break; 52 | case BETWEEN: 53 | str = MEnum.BETWEEN.getValue(); 54 | break; 55 | case OR: 56 | str = MEnum.OR.getValue(); 57 | break; 58 | case AND: 59 | str = MEnum.AND.getValue(); 60 | break; 61 | case NOT_EQ: 62 | str=MEnum.NOT_EQ.getValue(); 63 | break; 64 | } 65 | return str; 66 | } 67 | 68 | } -------------------------------------------------------------------------------- /src/com/jzero/pool/BoneCpPool.java: -------------------------------------------------------------------------------- 1 | package com.jzero.pool; 2 | 3 | import java.sql.Connection; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | import com.jolbox.bonecp.BoneCP; 7 | import com.jolbox.bonecp.BoneCPConfig; 8 | import com.jzero.core.MInit; 9 | import com.jzero.log.Log; 10 | import com.jzero.log.LogEnum; 11 | 12 | /** 2012-10-3 */ 13 | public class BoneCpPool implements IPool { 14 | 15 | public Connection getConnection(String driver,String url,String user,String pass) { 16 | Connection connection=null; 17 | try { 18 | Class.forName(driver); 19 | BoneCPConfig config = new BoneCPConfig(); 20 | config.setJdbcUrl(url); 21 | config.setUsername(user); 22 | config.setPassword(pass); 23 | config.setMinConnectionsPerPartition(10); //设置每个分区中的最小连接数 10 24 | config.setMaxConnectionsPerPartition(30);//设置每个分区中的最大连接数 30 25 | config.setPartitionCount(3);//设置分区 分区数为3 26 | config.setStatisticsEnabled(true); 27 | config.setAcquireIncrement(5);//当连接池中的连接耗尽的时候 BoneCP一次同时获取的连接数 28 | config.setReleaseHelperThreads(3);//连接释放处理 29 | config.setIdleConnectionTestPeriod(5, TimeUnit.MINUTES);//设置每60秒检查数据库中的空闲连接数 30 | config.setIdleMaxAge(5, TimeUnit.MINUTES); //设置连接空闲时间 31 | BoneCP connectionPool = new BoneCP(config); 32 | connection=connectionPool.getConnection(); 33 | } catch (Exception e) { 34 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 35 | MInit.get().getMb().getTextRender(e.getMessage()).render(); 36 | } 37 | return connection; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/com/jzero/pool/C3poPool.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.pool; 3 | 4 | import java.sql.Connection; 5 | 6 | import com.jzero.core.MInit; 7 | import com.jzero.log.Log; 8 | import com.jzero.log.LogEnum; 9 | import com.mchange.v2.c3p0.ComboPooledDataSource; 10 | 11 | /** 2012-10-3 */ 12 | public class C3poPool implements IPool { 13 | 14 | public Connection getConnection(String driver, String url, String user, 15 | String pass) { 16 | Connection connection=null; 17 | try { 18 | ComboPooledDataSource config = new ComboPooledDataSource(); 19 | config.setJdbcUrl(url); 20 | config.setUser(user); 21 | config.setPassword(pass); 22 | config.setDriverClass(driver); 23 | config.setInitialPoolSize(20); 24 | config.setMaxPoolSize(1000); 25 | config.setMinPoolSize(100); 26 | config.setInitialPoolSize(10); 27 | config.setMaxIdleTime(25000);//最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 28 | config.setAcquireIncrement(2); 29 | config.setIdleConnectionTestPeriod(18000); 30 | config.setTestConnectionOnCheckin(true);//如果设为true那么在取得连接的同时将校验连接的有效性 31 | //c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试 使用。Default: null 32 | // config.setAutomaticTestTable("c3potest"); 33 | config.setTestConnectionOnCheckout(true); 34 | // config.setPreferredTestQuery("SELECT 1"); 35 | config.setIdleConnectionTestPeriod(18000);//每60秒检查所有连接池中的空闲连接 36 | connection=config.getConnection(); 37 | } catch (Exception e) { 38 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 39 | MInit.get().getMb().getTextRender(e.getMessage()).render(); 40 | } 41 | return connection; 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/com/jzero/db/utility/MSqlite.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.utility; 2 | 3 | import java.util.List; 4 | 5 | import com.jzero.util.MCheck; 6 | import com.jzero.util.MRecord; 7 | 8 | public final class MSqlite implements MFieldDb { 9 | private MSqlite() { 10 | } 11 | 12 | private static MFieldDb db = new MSqlite(); 13 | 14 | public List getAllTable() { 15 | return null; 16 | } 17 | 18 | public List getCommentAndFieldName(String tableName) { 19 | // TODO Auto-generated method stub 20 | return null; 21 | } 22 | 23 | public List getDefaultAndFieldName(String tableName) { 24 | // TODO Auto-generated method stub 25 | return null; 26 | } 27 | 28 | public List getFieldForTable(String tableName) { 29 | // TODO Auto-generated method stub 30 | return null; 31 | } 32 | 33 | public List getSelectField(String tableName) { 34 | // TODO Auto-generated method stub 35 | return null; 36 | } 37 | 38 | public String get_pager_sql(String table, String where, String field, 39 | int current, int pageSize, Object... obj) { 40 | StringBuffer sql_bf = new StringBuffer(); 41 | if (MCheck.isNull(field)) { 42 | sql_bf.append(" SELECT * FROM ").append(table); 43 | } else { 44 | sql_bf.append(" SELECT ").append(field).append(" FROM ").append( 45 | table); 46 | } 47 | if (!MCheck.isNull(where)) { // 不为空,则有where 语句 48 | sql_bf.append(" WHERE 1=1 ").append(where); 49 | } 50 | if (!MCheck.isNull(obj)) { 51 | sql_bf.append(" ").append(obj[0]); 52 | } 53 | current = current < 0 ? 0 : current; 54 | sql_bf.append(" LIMIT ").append(current).append(" , ").append(pageSize); 55 | return sql_bf.toString(); 56 | } 57 | 58 | public static MFieldDb getIns() { 59 | return db; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/com/jzero/render/MJsonRender.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.render; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | 7 | import com.jzero.log.Log; 8 | 9 | /** 10 | * 2012-10-3: 来源于JFinal 11 | * wangujqw@gmail.com 12 | */ 13 | public class MJsonRender extends MRender { 14 | 15 | private static final long serialVersionUID = 1L; 16 | 17 | /** 18 | * http://zh.wikipedia.org/zh/MIME 19 | * 在wiki中查到: 尚未被接受为正式数据类型的subtype,可以使用x-开始的独立名称(例如application/x-gzip) 20 | * 所以以下可能要改成 application/x-json 21 | * 22 | * 通过使用firefox测试,struts2-json-plugin返回的是 application/json, 所以暂不改为 application/x-json 23 | * 1: 官方的 MIME type为application/json, 见 http://en.wikipedia.org/wiki/MIME_type 24 | * 2: ie 不支持 application/json, 在 ajax 上传文件完成后返回 json时 ie 提示下载文件 25 | */ 26 | private static final String contentType = "application/json;charset=" + getEncoding(); 27 | 28 | private String value; 29 | 30 | public MJsonRender(String value) { 31 | this.value = value; 32 | } 33 | 34 | public void render() { 35 | 36 | PrintWriter writer = null; 37 | try { 38 | response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache 39 | response.setHeader("Cache-Control", "no-cache"); 40 | response.setDateHeader("Expires", 0); 41 | response.setContentType(contentType); 42 | writer = response.getWriter(); 43 | writer.write(value); 44 | writer.flush(); 45 | } catch (IOException e) { 46 | Log.me().write_error(e); 47 | } 48 | finally { 49 | writer.close(); 50 | } 51 | } 52 | 53 | @Override 54 | public boolean isJsp() { 55 | // TODO Auto-generated method stub 56 | return false; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/com/jzero/render/M500Render.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.render; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | 7 | import com.jzero.core.MInit; 8 | import com.jzero.log.Log; 9 | import com.jzero.util.MCheck; 10 | 11 | /** 12 | * 2012-10-4: 13 | * wangujqw@gmail.com 14 | */ 15 | public class M500Render extends MRender { 16 | private static final long serialVersionUID = 1L; 17 | private static final String contentType = "text/html;charset=" + getEncoding(); 18 | private static final String defaultHtml = "500 Internal Server Error

500 Internal Server Error


500 ERROR
"; 19 | private MRender render; 20 | 21 | public M500Render(String view) { 22 | this.view = view; 23 | } 24 | 25 | public M500Render() { 26 | 27 | } 28 | 29 | public void render() { 30 | // response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 31 | 32 | // render with view 33 | if (!MCheck.isNull(getView())) { 34 | render = MInit.get().getMb().getRender(view); 35 | render.setContext(request, response); 36 | render.render(); 37 | return; 38 | } 39 | 40 | // render with defaultHtml 41 | PrintWriter writer = null; 42 | try { 43 | response.setContentType(contentType); 44 | writer = response.getWriter(); 45 | if(writer!=null){ 46 | writer.write(defaultHtml); 47 | writer.flush(); 48 | } 49 | } catch (IOException e) { 50 | Log.me().write_error(e); 51 | } 52 | finally { 53 | if(!MCheck.isNull(writer)){ 54 | writer.close(); 55 | } 56 | 57 | } 58 | } 59 | 60 | @Override 61 | public boolean isJsp() { 62 | // TODO Auto-generated method stub 63 | return false; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/com/jzero/util/MCheck.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.util.List; 4 | @SuppressWarnings("unchecked") 5 | public final class MCheck { 6 | private MCheck() { 7 | } 8 | 9 | public static boolean isNull(String obj) { 10 | return isNull((Object) obj); 11 | } 12 | 13 | public static boolean isNull(Object obj) { 14 | boolean bool = false; 15 | if (obj == null) { 16 | bool = true; 17 | } else { 18 | String str = obj.toString(); 19 | if(str.equals("[]")){ 20 | bool=true; 21 | }else if (str.equals("''")) { 22 | bool = true; 23 | } else if ("".equals(str)) { 24 | bool = true; 25 | } else if ("".equals(str.trim())) { 26 | bool = true; 27 | } else if ("null".equalsIgnoreCase(str)) { 28 | bool = true; 29 | } 30 | } 31 | return bool; 32 | } 33 | 34 | public static boolean isNull(Object... obj) { 35 | boolean bool = false; 36 | if (obj == null) { 37 | bool = true; 38 | } else if (obj.length == 0) { 39 | bool = true; 40 | } 41 | return bool; 42 | } 43 | 44 | public static boolean isNull(String... obj) { 45 | boolean bool = false; 46 | if (obj == null) { 47 | bool = true; 48 | } else if (obj.length == 0) { 49 | bool = true; 50 | }else if(obj[0].equals("")){ 51 | bool=true; 52 | } 53 | return bool; 54 | } 55 | 56 | public static boolean isNull(MRecord record) { 57 | if (record == null) { 58 | return true; 59 | } 60 | return record.getColumns().isEmpty() ? true : false; 61 | } 62 | 63 | public static boolean isNull(List obj) { 64 | boolean bool = false; 65 | if (obj == null) { 66 | bool = true; 67 | } else if (obj.size() == 0) { 68 | bool = true; 69 | } 70 | return bool; 71 | } 72 | public static boolean isNull(Integer in){ 73 | return in==null?true:in==0?true:false; 74 | } 75 | } -------------------------------------------------------------------------------- /src/com/jzero/render/MTextRender.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.render; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | 7 | import com.jzero.log.Log; 8 | import com.jzero.util.MCheck; 9 | 10 | /** 11 | * 2012-10-3: 来源于JFinal 12 | * wangujqw@gmail.com 13 | */ 14 | class MTextRender extends MRender { 15 | 16 | private static final long serialVersionUID = -6559692075690567088L; 17 | 18 | private static final String defaultContentType = "text/plain;charset=" + getEncoding(); 19 | 20 | private String text; 21 | 22 | public MTextRender(String text) { 23 | this.text = text; 24 | } 25 | 26 | private String contentType; 27 | public MTextRender(String text, String contentType) { 28 | this.text = text; 29 | this.contentType = contentType; 30 | } 31 | 32 | public void render() { 33 | PrintWriter writer = null; 34 | try { 35 | if(!MCheck.isNull(response)){ 36 | response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache 37 | response.setHeader("Cache-Control", "no-cache"); 38 | response.setDateHeader("Expires", 0); 39 | 40 | if (contentType == null) { 41 | response.setContentType(defaultContentType); 42 | } 43 | else { 44 | response.setContentType(contentType); 45 | response.setCharacterEncoding(getEncoding()); 46 | } 47 | 48 | writer = response.getWriter(); 49 | if(!MCheck.isNull(writer)){ 50 | writer.write(text); 51 | writer.flush(); 52 | } 53 | } 54 | } catch (IOException e) { 55 | Log.me().write_error(e); 56 | } 57 | finally { 58 | if(!MCheck.isNull(writer)){writer.close();} 59 | } 60 | } 61 | 62 | @Override 63 | public boolean isJsp() { 64 | // TODO Auto-generated method stub 65 | return false; 66 | } 67 | } 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/com/jzero/render/MB.java: -------------------------------------------------------------------------------- 1 | package com.jzero.render; 2 | 3 | import com.jzero.core.MInit; 4 | 5 | 6 | /** 7 | * 2012-10-4:来源JFinal wangujqw@gmail.com 8 | */ 9 | public class MB{ 10 | // singleton 11 | private MRender render; 12 | 13 | public MRender getRender() { 14 | return render; 15 | } 16 | public static MB me(){ 17 | return MInit.get().getMb(); 18 | } 19 | 20 | public MRender getJsonRender(String value) { 21 | render= new MJsonRender(value); 22 | return render; 23 | } 24 | 25 | public MRender getRender(String view) { 26 | render= new MJspRender(view); 27 | return render; 28 | } 29 | 30 | public MRender getJspRender(String view) { 31 | render= new MJspRender(view); 32 | return render; 33 | } 34 | public MRender getJspRender(){ 35 | render=new MJspRender(); 36 | return render; 37 | } 38 | public MRender getTextRender(String text) { 39 | render= new MTextRender(text); 40 | return render; 41 | } 42 | 43 | public MRender getTextRender(String text, String contentType) { 44 | render= new MTextRender(text, contentType); 45 | return render; 46 | } 47 | 48 | 49 | public MRender getRedirect301Render(String url) { 50 | render= new M301Render(url); 51 | return render; 52 | } 53 | 54 | public MRender getRedirect301Render(String url, boolean withOutQueryString) { 55 | render= new M301Render(url, withOutQueryString); 56 | return render; 57 | } 58 | 59 | public MRender getError404Render(String view) { 60 | render= new M404Render(view); 61 | return render; 62 | } 63 | 64 | public MRender getError404Render() { 65 | render= new M404Render(); 66 | return render; 67 | } 68 | 69 | public MRender getError500Render(String view) { 70 | render= new M500Render(view); 71 | return render; 72 | } 73 | 74 | public MRender getError500Render() { 75 | render= new M500Render(); 76 | return render; 77 | } 78 | public MRender getImgRender() { 79 | render= new MImaRender(); 80 | return render; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/com/jzero/render/M404Render.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.render; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | 7 | import com.jzero.core.MInit; 8 | import com.jzero.log.Log; 9 | import com.jzero.util.MCheck; 10 | 11 | 12 | /** 13 | * 2012-10-4:来源JFinal 14 | * wangujqw@gmail.com 15 | */ 16 | public class M404Render extends MRender { 17 | 18 | /** 19 | * 20 | */ 21 | private static final long serialVersionUID = 1L; 22 | private static final String contentType = "text/html;charset=" + getEncoding(); 23 | private static final String defaultHtml = "404 Not Found

404 Not Found


404
"; 24 | private MRender render; 25 | 26 | public M404Render(String view) { 27 | setView(view); 28 | } 29 | 30 | public M404Render() { 31 | 32 | } 33 | 34 | public void render() { 35 | // response.setStatus(HttpServletResponse.SC_NOT_FOUND); 36 | 37 | if (!MCheck.isNull(getView())) { 38 | render = MInit.get().getMb().getRender(view); 39 | render.setContext(request, response); 40 | render.render(); 41 | return; 42 | } 43 | 44 | // render with defaultHtml 45 | PrintWriter writer = null; 46 | try { 47 | // response.setHeader("Pragma", "no-cache"); // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache 48 | // response.setHeader("Cache-Control", "no-cache"); 49 | // response.setDateHeader("Expires", 0); 50 | response.setContentType(contentType); 51 | writer = response.getWriter(); 52 | if(writer!=null){ 53 | writer.write(defaultHtml); 54 | writer.flush(); 55 | } 56 | } catch (IOException e) { 57 | Log.me().write_error(e); 58 | } 59 | finally { 60 | if(writer!=null){writer.close();} 61 | } 62 | } 63 | 64 | @Override 65 | public boolean isJsp() { 66 | // TODO Auto-generated method stub 67 | return false; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/com/jzero/db/exp/MDbTool.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.db.exp; 3 | 4 | import com.jzero.util.MCheck; 5 | import com.jzero.util.MEncrypt; 6 | import com.jzero.util.MPath; 7 | import com.jzero.util.MPro; 8 | import com.jzero.util.MRecord; 9 | 10 | /** 2012-10-3 */ 11 | public class MDbTool { 12 | // -------------------------读取当前数据库开始 13 | // 2012-4-12:得到当前所使用的数据库 14 | public static String getWhoDb() { 15 | return MPro.me().getStr("dbdriver"); 16 | } 17 | 18 | // 得到连接数据库连接 19 | public static MRecord getDbConnectInfo() { 20 | // 读取配置文件 21 | MRecord record = new MRecord(); 22 | // 得到是哪个数据库 23 | String db = getWhoDb(); 24 | String user = MEncrypt.decrypt(MPro.me().getStr("username")); 25 | String _temp_pass=MPro.me().getStr("password"); 26 | String pwd =MCheck.isNull(_temp_pass)?"": MEncrypt.decrypt(_temp_pass); 27 | String port =MPro.me().getStr("port"); 28 | String addr =MPro.me().getStr("hostname"); 29 | String dbname =MPro.me().getStr("database"); 30 | String url = null, driver = null; 31 | if ("oracle".equalsIgnoreCase(db)) { 32 | url = "jdbc:oracle:thin:@" + addr + ":" + port + ":" + dbname; 33 | driver = "oracle.jdbc.driver.OracleDriver"; 34 | } else if ("mssql".equalsIgnoreCase(db)) { 35 | url = "jdbc:jtds:sqlserver://" + addr + ":" + port + "/" + dbname; 36 | driver = "net.sourceforge.jtds.jdbc.Driver"; 37 | } else if ("mysql".equalsIgnoreCase(db)) { 38 | url="jdbc:mysql://"+addr+":"+port+"/"+dbname+"?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false"; 39 | driver = "com.mysql.jdbc.Driver"; 40 | }else if("sqlite".equalsIgnoreCase(db)){ 41 | String mysqlpaths=MPath.me().getWebInfPath()+"classes/"; 42 | url="jdbc:sqlite:"+mysqlpaths+dbname;//sqlite是嵌入式,所以不用指定addr,port 43 | driver = "org.sqlite.JDBC"; 44 | } 45 | 46 | record.set("url", url); 47 | record.set("driver", driver); 48 | record.set("user", user); 49 | record.set("pass", pwd); 50 | return record; 51 | } 52 | 53 | // -------------------------读取当前数据库结束 54 | } 55 | -------------------------------------------------------------------------------- /src/com/jzero/util/MySQL.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.util; 3 | /** 4 | * --- 2012-4-12 --- 5 | * --- Administrator --- 6 | * MySQL.java : 存放自定义SQL 7 | */ 8 | public class MySQL { 9 | 10 | /*************************************MSSQL读取字段属性SQL开始**********************************/ 11 | /** 12 | * --- 2012-4-9 --- 13 | * --- Administrator --- 14 | * MssqlDb.java : 针对Mssql操作 15 | * 取出的数据为:表名、字段名称、字段长度、字段类型、默认值、描述 16 | * 1、从Sysobject 中取出表名 (id) 17 | * 2、从Systeproperties:取出描述字段(id)(smallid=>colid) 18 | * 3、从syscolumns:取出字段名称与长度(id)(cdefault)(xtype)(colid) 19 | * 4、从syscomments:取默认值(id=>cdefault) 20 | * 5、从systypes:取字段类型(xtype) 21 | */ 22 | public static final String MSSQL_FIELD = "select " 23 | + "a.name as tablename,a.id," 24 | + "b.name as fieldname,b.length as length,b.colid ," 25 | + "c.name as typename," 26 | + "d.text as defaultname ," 27 | + "e.value as commentname" 28 | + " from sysobjects as a" 29 | + " left join syscolumns as b on a.id=b.id " 30 | + " left join systypes as c on b.xtype=c.xtype" 31 | + " left join syscomments as d on b.cdefault=d.id" 32 | + " left join sysproperties as e on b.colid=e.smallid and a.id=e.id" 33 | + " where a.xtype='U' and a.name=?"; 34 | 35 | // 只读取表名与表注释,未注释的不读出来 36 | public static final String MSSQL_TABLE = "select b.name tablename,a.value commentfield from sysproperties a " 37 | + " left join sysobjects b on a.id=b.id" 38 | + " where a.type='3' -- 3是表名,4是表字段名";// 取表名 39 | 40 | /*************************************MSSQL读取字段属性SQL结束**********************************/ 41 | 42 | /*************************************MYSQL读取字段属性SQL开始**********************************/ 43 | // 读取所有的表 44 | public static final String MYSQL_TABLE = "SHOW TABLE STATUS"; 45 | 46 | // 读取某一个表的字段 47 | public static final String MYSQL_FIELD = "SHOW FULL FIELDS FROM "; 48 | /*************************************MYSQL读取字段属性SQL结束**********************************/ 49 | /*************************************SQLITE读取字段属性SQL开始**********************************/ 50 | // 读取所有的表 51 | public static final String SQLITE_TABLE = "SELECT * FROM sqlite_master"; 52 | 53 | /*************************************SQLITE读取字段属性SQL结束**********************************/ 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/com/jzero/json/Test.java: -------------------------------------------------------------------------------- 1 | package com.jzero.json; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.jzero.util.MPrint; 7 | import com.jzero.util.MRecord; 8 | 9 | /** 10 | * --- 2012-5-8 --- --- Administrator --- Test.java : 11 | */ 12 | public class Test { 13 | 14 | public static void main(String[] args) { 15 | tree(); 16 | } 17 | public static void tree(){ 18 | } 19 | public static void test1(){ 20 | List lst=init(); 21 | String jsonString = JSONObj.toJSONString(lst); 22 | MPrint.print(jsonString); 23 | MRecord mRecord=JSONObj.parseJson(jsonString); 24 | MPrint.print(mRecord); 25 | String json="{\"crcode\":\"MS0001456\",\"psname\":\"冯兆云\",\"sex\":\"男\",\"tel\":\"\",\"insname\":\"大额救助\",\"Topsrate\":0,\"CrState\":\"退保\"}"; 26 | MRecord obj2=JSONObj.parseJson(json); 27 | MPrint.print(obj2); 28 | MPrint.print(obj2.get("psname")); 29 | MPrint.print(obj2.get("sex")); 30 | MRecord obj=init2(); 31 | MPrint.print(obj); 32 | List lobj=init(); 33 | MPrint.print(lobj); 34 | } 35 | public static void test2(){ 36 | String sql="[{\"six\":\"15.0\",\"one\":\"1\",\"two\":\"2\",\"three\":\"3\",\"four\":\"4\",\"five\":\"5\"},{\"six\":\"15.0\",\"one\":\"1\",\"two\":\"2\",\"three\":\"3\",\"four\":\"4\",\"five\":\"5\"}]"; 37 | String ss[] = sql.replace("[", "").replace("]", "").replace("\"", "").split("},"); 38 | List records=new ArrayList(); 39 | for(String s:ss){ 40 | MRecord record=JSONObj.parseJson(s); 41 | records.add(record); 42 | } 43 | MPrint.print(records); 44 | } 45 | //jiema 46 | public static MRecord parse(String json){ 47 | MRecord reMap=new MRecord(); 48 | 49 | return reMap; 50 | } 51 | public static MRecord init2() { 52 | MRecord obj = new MRecord(); 53 | obj.set("ONE", "1"); 54 | obj.set("TWO", "2"); 55 | obj.set("THREE", "3"); 56 | obj.set("FOUR", 4); 57 | obj.set("FIVE", 5); 58 | obj.set("Six", Double.parseDouble("15")); 59 | return obj; 60 | } 61 | 62 | public static List init() { 63 | List lst = new ArrayList(); 64 | MRecord obj =new MRecord(); 65 | obj.set("ONE", 1); 66 | obj.set("TWO", 2); 67 | obj.set("THREE", 3); 68 | obj.set("FOUR", 4); 69 | obj.set("FIVE", 5); 70 | obj.set("Six", Double.parseDouble("15")); 71 | lst.add(obj); 72 | obj =new MRecord(); 73 | obj.set("ONE", 1); 74 | obj.set("TWO", 2); 75 | obj.set("THREE", 3); 76 | obj.set("FOUR", 4); 77 | obj.set("FIVE", 5); 78 | obj.set("Six", Double.parseDouble("15")); 79 | lst.add(obj); 80 | return lst; 81 | } 82 | 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/com/jzero/render/MImaRender.java: -------------------------------------------------------------------------------- 1 | package com.jzero.render; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.Graphics; 6 | import java.awt.image.BufferedImage; 7 | import java.io.IOException; 8 | import java.util.Random; 9 | 10 | import javax.imageio.ImageIO; 11 | import javax.servlet.ServletOutputStream; 12 | import javax.servlet.http.HttpSession; 13 | 14 | import com.jzero.log.Log; 15 | 16 | /** 17 | * image验譓 wangujqw@gmail.com 18 | */ 19 | public class MImaRender extends MRender { 20 | 21 | private static final long serialVersionUID = 1L; 22 | 23 | public MImaRender() { 24 | } 25 | 26 | public void render() { 27 | response.setContentType("image/jpeg"); 28 | response.setHeader("Pragma", "No-cache"); 29 | response.setHeader("Cache-Control", "no-cache"); 30 | response.setDateHeader("Expires", 0L); 31 | HttpSession session = request.getSession(); 32 | 33 | int width = 60; 34 | int height = 20; 35 | BufferedImage image = new BufferedImage(width, height, 1); 36 | 37 | Graphics g = image.getGraphics(); 38 | 39 | Random random = new Random(); 40 | 41 | g.setColor(getRandColor(200, 250)); 42 | g.fillRect(0, 0, width, height); 43 | 44 | g.setFont(new Font("Times New Roman", 0, 18)); 45 | 46 | g.setColor(getRandColor(160, 200)); 47 | for (int i = 0; i < 155; ++i) { 48 | int x = random.nextInt(width); 49 | int y = random.nextInt(height); 50 | int xl = random.nextInt(12); 51 | int yl = random.nextInt(12); 52 | g.drawLine(x, y, x + xl, y + yl); 53 | } 54 | 55 | String sRand = ""; 56 | for (int i = 0; i < 4; ++i) { 57 | String rand = String.valueOf(random.nextInt(10)); 58 | sRand = sRand + rand; 59 | 60 | g.setColor(new Color(20 + random.nextInt(110), 20 + random 61 | .nextInt(110), 20 + random.nextInt(110))); 62 | g.drawString(rand, 13 * i + 6, 16); 63 | } 64 | session.setAttribute("rand", sRand); 65 | g.dispose(); 66 | try { 67 | ServletOutputStream responseOutputStream = response.getOutputStream(); 68 | ImageIO.write(image, "JPEG", responseOutputStream); 69 | responseOutputStream.flush(); 70 | responseOutputStream.close(); 71 | } catch (IOException e) { 72 | Log.me().write_error(e); 73 | } 74 | } 75 | 76 | Color getRandColor(int fc, int bc) { 77 | Random random = new Random(); 78 | if (fc > 255) 79 | fc = 255; 80 | if (bc > 255) 81 | bc = 255; 82 | int r = fc + random.nextInt(bc - fc); 83 | int g = fc + random.nextInt(bc - fc); 84 | int b = fc + random.nextInt(bc - fc); 85 | return new Color(r, g, b); 86 | } 87 | 88 | @Override 89 | public boolean isJsp() { 90 | // TODO Auto-generated method stub 91 | return false; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/com/jzero/db/exp/MHandler.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.exp; 2 | 3 | import java.sql.ResultSet; 4 | import java.sql.ResultSetMetaData; 5 | import java.sql.SQLException; 6 | import java.sql.Types; 7 | import java.text.SimpleDateFormat; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | import org.apache.commons.dbutils.BasicRowProcessor; 12 | import org.apache.commons.dbutils.handlers.AbstractListHandler; 13 | 14 | import com.jzero.util.MCheck; 15 | import com.jzero.util.MDate; 16 | import com.jzero.util.MRecord; 17 | 18 | /** 19 | * --- 2012-5-31 --- --- Administrator --- MyMapListHandler.java : 20 | * 继承实现Map的handleRow方法 在DBUtils中它是:result.put(rsmd.getColumnName(i), 21 | * rs.getObject(i));用rs.getObject()取值 就不能把数据库中的Decimal后面的小数点取值出来.所以在此实现它的方法 22 | */ 23 | public class MHandler extends AbstractListHandler { 24 | private static ConvertToMap convert; 25 | private static java.text.DecimalFormat df =new java.text.DecimalFormat("0.00"); 26 | private static SimpleDateFormat ymd_hms=MDate.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 27 | public MHandler() { 28 | if (MCheck.isNull(convert)) { 29 | convert = new ConvertToMap(); 30 | } 31 | } 32 | 33 | @Override 34 | protected MRecord handleRow(ResultSet rs) throws SQLException { 35 | return new MRecord().setColumns(convert.toMap(rs)); 36 | } 37 | 38 | private class ConvertToMap extends BasicRowProcessor { 39 | 40 | @Override 41 | public Map toMap(ResultSet rs) throws SQLException { 42 | Map result = new HashMap(); 43 | ResultSetMetaData rsmd = rs.getMetaData(); 44 | int cols = rsmd.getColumnCount(); 45 | for (int i = 1; i <= cols; i++) { 46 | result.put(rsmd.getColumnName(i).toLowerCase(), getTypeValue(rsmd, rs, i)); 47 | } 48 | 49 | return result; 50 | } 51 | 52 | } 53 | 54 | private Object getTypeValue(ResultSetMetaData rsmd, ResultSet rs, int index) 55 | throws SQLException { 56 | Object result = null; 57 | int type = rsmd.getColumnType(index); 58 | switch (type) { 59 | case Types.NUMERIC: 60 | case Types.FLOAT: 61 | case Types.DOUBLE: 62 | case Types.INTEGER: 63 | int scale=rsmd.getScale(index); 64 | if(scale>0){ 65 | result=df.format(rs.getDouble(index)); 66 | }else{ 67 | result=rs.getInt(index); 68 | } 69 | break; 70 | case Types.DATE: 71 | result=rs.getDate(index);break; 72 | case Types.TIMESTAMP: 73 | Object obj=rs.getTimestamp(index); 74 | result=MCheck.isNull(obj)?null:ymd_hms.format(rs.getTimestamp(index)); 75 | break; 76 | default: 77 | result = rs.getObject(index); 78 | break; 79 | } 80 | return result; 81 | 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/com/jzero/json/JSONObj.java: -------------------------------------------------------------------------------- 1 | package com.jzero.json; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.jzero.util.MCheck; 7 | import com.jzero.util.MRecord; 8 | 9 | /** 10 | * --- 2012-5-8 --- --- Administrator --- 11 | * JsonObj.java :来源于json-simple:http://code.google.com/p/json-simple/ 12 | * 增加过来只为将Oracle返回的字段弄成小写 13 | */ 14 | @SuppressWarnings("unchecked") 15 | public class JSONObj { 16 | 17 | public static String toJSONString(Object value) { 18 | if (value instanceof List) 19 | return JSONTool.toJSONString((List) value); 20 | if (value instanceof MRecord) 21 | return JSONTool.toJSONString((MRecord) value); 22 | 23 | if (value == null) 24 | return "\"\""; 25 | if (value instanceof Double) { 26 | if ((((Double) value).isInfinite()) || (((Double) value).isNaN())) { 27 | return "null"; 28 | } 29 | return value.toString(); 30 | } 31 | 32 | if (value instanceof Float) { 33 | if ((((Float) value).isInfinite()) || (((Float) value).isNaN())) { 34 | return "null"; 35 | } 36 | return value.toString(); 37 | } 38 | 39 | if (value instanceof Number) { 40 | return value.toString(); 41 | } 42 | if (value instanceof Boolean) { 43 | return value.toString(); 44 | } 45 | 46 | if (value instanceof String) { 47 | if (MCheck.isNull(value)) { 48 | return "\"\" "; 49 | } 50 | if ("null".equals(value)) { 51 | return "\"\""; 52 | } 53 | return "\"" + JSONTool.escape((String) value) + "\""; 54 | } 55 | 56 | 57 | 58 | 59 | return value.toString(); 60 | } 61 | 62 | public static MRecord parseJson(String json) { 63 | MRecord reMap = new MRecord(); 64 | String strs[] = json.replace("{", "").replace("}", "").replace("\"", "").split(","); 65 | String tempStr[] = null; 66 | for (String str : strs) { 67 | //2012-11-15:如果是http://格式,则只split第一个:号 68 | if(str.matches("^\\w*:\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$")||str.contains("http://")){//避免把时间格式 yyyy-mm-dd hh:mm:ss中的hh:mm:ss拆分 69 | String s1=str.substring(0,str.indexOf(":")); 70 | String s2=str.substring(str.indexOf(":")+1); 71 | reMap.set(s1, s2); 72 | }else{ 73 | tempStr = str.split(":"); 74 | if (tempStr.length > 1) { 75 | reMap.set(tempStr[0], tempStr[1]); 76 | } 77 | } 78 | 79 | } 80 | return reMap; 81 | } 82 | public static List parseList(String json){ 83 | List lst=new ArrayList(); 84 | String ss[] = json.replace("[", "").replace("]", "").replace("\"", "").split("},"); 85 | if(!MCheck.isNull(ss)){ 86 | for(String s:ss){ 87 | MRecord record=JSONObj.parseJson(s); 88 | lst.add(record); 89 | } 90 | } 91 | return lst; 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/com/jzero/core/MInit.java: -------------------------------------------------------------------------------- 1 | package com.jzero.core; 2 | 3 | import javax.servlet.http.Cookie; 4 | import javax.servlet.http.HttpServletRequest; 5 | import javax.servlet.http.HttpServletResponse; 6 | import javax.servlet.http.HttpSession; 7 | 8 | import com.jzero.render.MB; 9 | import com.jzero.token.MToken; 10 | import com.jzero.util.MPro; 11 | import com.jzero.util.Msg; 12 | 13 | public class MInit{ 14 | private static MPro config = null; 15 | private MR mr = null; 16 | private MRouter router = null; 17 | private MURI uri = null; 18 | private MToken token = null; 19 | private HttpServletRequest request; 20 | private HttpServletResponse response; 21 | private MB mb=null; 22 | 23 | // --------------------------------------- 24 | private final static ThreadLocal contexts = new ThreadLocal(); 25 | static{ 26 | config = MPro.me().load_file(Msg.CONFIG).load_file(Msg.DB_CONFIG).load_file(Msg.DB_CONFIG).load_file(Msg.ROUTE_CONFIG).load_file(Msg.OTHER_CONFIG); 27 | } 28 | public static MInit begin(HttpServletRequest req, HttpServletResponse res) { 29 | MInit init = new MInit(); 30 | init.request = req; 31 | init.response = res; 32 | init.response.setCharacterEncoding("UTF-8"); 33 | init.session = req.getSession(false); 34 | init.cookies=req.getCookies(); 35 | init.mr = MR.init(init); 36 | init.token = MToken.init(init); 37 | init.uri = MURI.init(init); 38 | init.router = MRouter.init(init); 39 | init.mb=new MB(); 40 | contexts.set(init); 41 | return init; 42 | } 43 | public static MInit get(){ 44 | return contexts.get(); 45 | } 46 | public void end(){ 47 | this.request=null; 48 | this.response=null; 49 | this.session=null; 50 | this.cookies=null; 51 | 52 | this.mr=null; 53 | this.token=null; 54 | this.uri=null; 55 | this.router=null; 56 | this.mb=null; 57 | contexts.remove(); 58 | } 59 | 60 | public MB getMb() { 61 | return mb; 62 | } 63 | 64 | private HttpSession session; 65 | private Cookie[] cookies; 66 | 67 | public HttpSession getSession() { 68 | return session; 69 | } 70 | public Cookie[] getCookie(){ 71 | return cookies; 72 | } 73 | public String uri(){ 74 | return request.getRequestURI(); 75 | } 76 | 77 | // ------------------------------------------------- 78 | 79 | public MToken getToken() { 80 | return token; 81 | } 82 | 83 | public MR getMr() { 84 | return mr; 85 | } 86 | 87 | public MRouter getRouter() { 88 | return router; 89 | } 90 | 91 | public MURI getURI() { 92 | return uri; 93 | } 94 | 95 | public MPro getConfig() { 96 | return config; 97 | } 98 | 99 | public HttpServletRequest request() { 100 | return request; 101 | } 102 | 103 | public HttpServletResponse response() { 104 | return response; 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/com/jzero/upload/MDown.java: -------------------------------------------------------------------------------- 1 | package com.jzero.upload; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.DataInputStream; 5 | import java.io.DataOutputStream; 6 | import java.io.FileOutputStream; 7 | import java.io.InputStreamReader; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.net.URLConnection; 11 | 12 | import com.jzero.util.MCheck; 13 | 14 | public class MDown { 15 | 16 | /** 17 | * 下载远程文件 18 | * 19 | * @param photoUrl 20 | * 文件路径 21 | * @param fileName 22 | * 下载到本地的路径 23 | * @return 是否成功 24 | * @throws Exception 25 | */ 26 | public static boolean saveUrlAs(String photoUrl, String fileName) throws Exception { 27 | URL url = new URL(photoUrl); 28 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 29 | DataOutputStream out =null; 30 | DataInputStream in =null; 31 | boolean isOk=false; 32 | try{ 33 | out = new DataOutputStream(new FileOutputStream(fileName)); 34 | if(!MCheck.isNull(connection)){ 35 | in = new DataInputStream(connection.getInputStream()); 36 | byte[] buffer = new byte[4096]; 37 | int count = 0; 38 | while ((count = in.read(buffer)) > 0) { 39 | out.write(buffer, 0, count); 40 | } 41 | isOk=true; 42 | } 43 | }finally{ 44 | if(out!=null){ 45 | out.close(); 46 | } 47 | if(in!=null){ 48 | in.close(); 49 | } 50 | } 51 | return isOk; 52 | } 53 | 54 | /** 55 | * 获取远程文件的内容(兼容HTTP与FTP) 56 | * 57 | * @param urlString 58 | * 文件路径 59 | * @return 文件内容 60 | * @throws Exception 61 | */ 62 | public static String getDocumentAt(String urlString) throws Exception { 63 | StringBuffer document = new StringBuffer(); 64 | URL url = new URL(urlString); 65 | URLConnection conn = url.openConnection(); 66 | BufferedReader reader =null; 67 | try{ 68 | reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 69 | String line = null; 70 | while ((line = reader.readLine()) != null) { 71 | document.append(line + "\n"); 72 | } 73 | }finally{ 74 | if(reader!=null){ 75 | reader.close(); 76 | } 77 | } 78 | return document.toString(); 79 | } 80 | 81 | /** 82 | * 83 | * @param args 84 | * @throws Exception 85 | */ 86 | public static void main(String[] args) throws Exception { 87 | String photoUrl = "http://192.168.1.110:8090/ddsx/g3resource/video/c74e5e9cca2847b7578c11d2674c8d55.flv"; 88 | String fileName = photoUrl.substring(photoUrl.lastIndexOf("/")); 89 | String filePath = "c:/"; 90 | System.out.println(getDocumentAt(photoUrl)); 91 | boolean flag = saveUrlAs(photoUrl, filePath + fileName); 92 | System.out.println("Run ok!\n Get URL file " + flag); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | [Dd]ebug/ 46 | [Rr]elease/ 47 | *_i.c 48 | *_p.c 49 | *.ilk 50 | *.scc 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.vspscc 64 | .builds 65 | *.dotCover 66 | 67 | ## TODO: If you have NuGet Package Restore enabled, uncomment this 68 | #packages/ 69 | 70 | # Visual C++ cache files 71 | ipch/ 72 | *.aps 73 | *.ncb 74 | *.opensdf 75 | *.sdf 76 | 77 | # Visual Studio profiler 78 | *.psess 79 | *.vsp 80 | 81 | # ReSharper is a .NET coding add-in 82 | _ReSharper* 83 | 84 | # Installshield output folder 85 | [Ee]xpress 86 | 87 | # DocProject is a documentation generator add-in 88 | DocProject/buildhelp/ 89 | DocProject/Help/*.HxT 90 | DocProject/Help/*.HxC 91 | DocProject/Help/*.hhc 92 | DocProject/Help/*.hhk 93 | DocProject/Help/*.hhp 94 | DocProject/Help/Html2 95 | DocProject/Help/html 96 | 97 | # Click-Once directory 98 | publish 99 | 100 | # Others 101 | [Bb]in 102 | [Oo]bj 103 | sql 104 | TestResults 105 | *.Cache 106 | ClientBin 107 | stylecop.* 108 | ~$* 109 | *.dbmdl 110 | Generated_Code #added for RIA/Silverlight projects 111 | 112 | # Backup & report files from converting an old project file to a newer 113 | # Visual Studio version. Backup files are not needed, because we have git ;-) 114 | _UpgradeReport_Files/ 115 | Backup*/ 116 | UpgradeLog*.XML 117 | 118 | 119 | 120 | ############ 121 | ## Windows 122 | ############ 123 | 124 | # Windows image file caches 125 | Thumbs.db 126 | 127 | # Folder config file 128 | Desktop.ini 129 | 130 | 131 | ############# 132 | ## Python 133 | ############# 134 | 135 | *.py[co] 136 | 137 | # Packages 138 | *.egg 139 | *.egg-info 140 | dist 141 | build 142 | eggs 143 | parts 144 | bin 145 | var 146 | sdist 147 | develop-eggs 148 | .installed.cfg 149 | 150 | # Installer logs 151 | pip-log.txt 152 | 153 | # Unit test / coverage reports 154 | .coverage 155 | .tox 156 | 157 | #Translations 158 | *.mo 159 | 160 | #Mr Developer 161 | .mr.developer.cfg 162 | 163 | # Mac crap 164 | .DS_Store 165 | -------------------------------------------------------------------------------- /src/com/jzero/util/Msg.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.util; 3 | /** 2012-10-3 */ 4 | public class Msg { 5 | //--配置文件 6 | public static String CONFIG = "config.properties"; 7 | public static String DB_CONFIG = "database.properties"; 8 | public static String ROUTE_CONFIG = "routes.properties"; 9 | public static String OTHER_CONFIG = "other.properties"; 10 | 11 | //--传出到页面的指定值 12 | public static String OUT_DATAS = "OUT_DATAS"; //输出到新增或修改页面的值 13 | public static String LIST_DATAS = "LIST_DATAS"; //输出到新增或修改的列表值 14 | public static String OBJECT = "OBJECT"; //输出到修改页面的对象值 15 | public static String ORDER_STR = "ORDER_STR"; //隐藏字段,排序名称 16 | public static String FIND_STR = "FIND_STR"; //隐藏字段,查询名称 17 | public static String SELECT_DATAS = "SELECT_DATAS";//检索处,共同的下拉框数据 18 | public static String SHOW_COMM = "SHOW_COMM"; //是否显示共同检索信息 19 | public static String SHOW_TIME = "SHOW_TIME"; //是否显示时间检索信息 20 | public static String SHOW_KIND = "SHOW_KIND"; 21 | public static String SHOW_ADD = "SHOW_ADD"; //是否显示增加按键 22 | public static String SHOW_BACK = "SHOW_BACK"; //是否显示返回按钮 23 | public static String ADD_URI = "ADD_URI"; //增加地址信息 24 | public static String SAVE_URI = "SAVE_URI"; //更新的地址信息 25 | public static String FIND_URI = "FIND_URI"; //查询地址信息 26 | 27 | //--提示信息 28 | public static String MESSAGE = "MESSAGE"; //提示信息 29 | 30 | //--修改 31 | public static String MODIFY_SUCCESS = "更新成功."; 32 | public static String MODIFY_ERROR = "更新失败,请检查是否已修改属性值。"; 33 | public static String BATCH_MODIFY_SUCCESS = "批量操作成功."; 34 | 35 | //--审核 36 | public static String AUDIT_SUCCESS = "审核成功."; 37 | public static String AUDIT_ERROR = "审核失败."; 38 | public static String BATCH_AUDIT_SUCCESS = "批量审核成功."; 39 | 40 | //--删除 41 | public static String DELETE_SUCCESS = "删除成功."; 42 | public static String BATCH_DELETE_SUCCESS = "批量删除成功."; 43 | public static String DELETE_ERROR = "删除时发生错误.请清理一下缓存."; 44 | 45 | //--新增 46 | public static String INSERT_SUCCESS = "新增成功"; 47 | public static String INSERT_ERROR = "新增时发生错误,请清理缓存再试一次."; 48 | 49 | //--保存 50 | public static String SAVE_SUCCESS = "操作成功."; 51 | 52 | 53 | //--登录信息 54 | public static String USER_PASS_ERROR = "用户名或密码错误,请重新输入"; 55 | public static String USER_IS_STOP = "当前用户状态已停用,已禁止登录,请联系管理员."; 56 | 57 | 58 | 59 | public static String USER_NAME = "super_user"; 60 | /** 61 | * 验证码为空 62 | */ 63 | public static final String AUTH_NULL = "验证码是空值,请输入验证码."; 64 | /** 65 | * 验证码错误 66 | */ 67 | public static final String AUTH_ERROR = "验证码错误,请重新输入."; 68 | 69 | 70 | //常量信息 71 | public static final String CON_FILE = "filename"; //文件上传时使用到  2012-11-3 72 | public static final String CON_IMG = "imgname"; //图片上传时使用到  2012-11-3 73 | public static final String CON_MUL_IMG = "mulimg"; //多上传时使用到  2012-11-3 74 | } 75 | -------------------------------------------------------------------------------- /src/com/jzero/cache/CacheManager.java: -------------------------------------------------------------------------------- 1 | package com.jzero.cache; 2 | 3 | import java.util.Date; 4 | import java.util.Map; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | 7 | public class CacheManager { 8 | private CacheManager() { 9 | } 10 | 11 | private static CacheManager instanct = new CacheManager(); 12 | private static Map cacheMap = new ConcurrentHashMap(); 13 | 14 | public static CacheManager me() { 15 | return instanct; 16 | } 17 | 18 | public Map getMap() { 19 | return cacheMap; 20 | } 21 | 22 | /** 23 | * returns cache item from hashmap 24 | * 25 | * @param key 26 | * @return Cache 27 | */ 28 | private Cache getCache(String key) { 29 | return cacheMap.get(key); 30 | } 31 | 32 | /** 33 | * Looks at the hashmap if a cache item exists or not 34 | * 35 | * @param key 36 | * @return Cache 37 | */ 38 | private boolean hasCache(String key) { 39 | return cacheMap.containsKey(key); 40 | } 41 | 42 | /** 43 | * Invalidates all cache 44 | */ 45 | public void invalidateAll() { 46 | cacheMap.clear(); 47 | } 48 | 49 | /** 50 | * Invalidates a single cache item 51 | * 52 | * @param key 53 | */ 54 | public void invalidate(String key) { 55 | cacheMap.remove(key); 56 | } 57 | 58 | /** 59 | * Adds new item to cache hashmap 60 | * 61 | * @param key 62 | * @return Cache 63 | */ 64 | private void putCache(String key, Cache object) { 65 | cacheMap.put(key, object); 66 | } 67 | public int getSize() { 68 | return cacheMap.size(); 69 | } 70 | /** 71 | * Reads a cache item's content 72 | * 73 | * @param key 74 | * @return 75 | */ 76 | public Cache getContent(String key) { 77 | if (hasCache(key)) { 78 | Cache cache = getCache(key); 79 | if (cache.isExpired()) { 80 | return null; 81 | } 82 | if (cacheExpired(cache)) { 83 | cache.setExpired(true); 84 | } 85 | return cache; 86 | } else { 87 | return null; 88 | } 89 | } 90 | 91 | /** 92 | * 93 | * @param key 94 | * @param content 95 | * @param ttl 96 | */ 97 | public void putContent(String key, Object content, long ttl) { 98 | Cache cache = new Cache(); 99 | cache.setKey(key); 100 | cache.setValue(content); 101 | cache.setTimeOut(ttl * 1000 + new Date().getTime()); 102 | cache.setExpired(false); 103 | putCache(key, cache); 104 | } 105 | 106 | /** @modelguid {172828D6-3AB2-46C4-96E2-E72B34264031} */ 107 | private boolean cacheExpired(Cache cache) { 108 | if (cache == null) { 109 | return false; 110 | } 111 | long milisNow = new Date().getTime(); 112 | long milisExpire = cache.getTimeOut(); 113 | if (milisExpire < 0) { // Cache never expires 114 | return false; 115 | } else if (milisNow >= milisExpire) { 116 | return true; 117 | } else { 118 | return false; 119 | } 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /src/com/jzero/db/core/CMySQL.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.core; 2 | 3 | import java.util.List; 4 | 5 | import com.jzero.core.MReport; 6 | import com.jzero.db.cache.MCache; 7 | import com.jzero.db.utility.MysqlDb; 8 | import com.jzero.util.MCheck; 9 | import com.jzero.util.MRecord; 10 | import com.jzero.util.MSee; 11 | import com.jzero.util.MSee.IAtom; 12 | 13 | /** 14 | * 2012-10-3: wangujqw@gmail.com 15 | */ 16 | public class CMySQL extends CBase { 17 | 18 | public List pager(String table, String where,String field, int current,int pageSize, Object... params) { 19 | final String sql = MysqlDb.getIns().get_pager_sql(table, where,field, current,pageSize, params); 20 | List data = null; 21 | if (MCache.me().isEnabled()) { 22 | data = MCache.me().read(sql); 23 | } 24 | if(MCheck.isNull(data)){ 25 | data=select(sql); 26 | }else { 27 | MSee.ok_sql(new IAtom() { 28 | public void run() throws Exception { 29 | MReport.doFileReport(sql); 30 | } 31 | }, is_dev()); 32 | } 33 | return data; 34 | } 35 | 36 | public List pager_sql(String sql, int current, int pageSize,Object... params) { 37 | final StringBuffer sql_bf = new StringBuffer(sql); 38 | sql_bf.append(" LIMIT ").append(current).append(" , ").append(pageSize); 39 | List data = null; 40 | if (MCache.me().isEnabled()) { 41 | data = MCache.me().read(sql_bf.toString()); 42 | } 43 | if(MCheck.isNull(data)){ 44 | data=select(sql_bf.toString()); 45 | }else { 46 | MSee.ok_sql(new IAtom() { 47 | public void run() throws Exception { 48 | MReport.doFileReport(sql_bf.toString()); 49 | } 50 | }, is_dev()); 51 | } 52 | return data; 53 | } 54 | 55 | @Override 56 | public MRecord select_one(String table, String where, String field, boolean cache,Object... params) { 57 | final StringBuffer sql_bf = new StringBuffer("SELECT "); 58 | if ("*".equals(field) || MCheck.isNull(field)) {sql_bf.append(" * "); 59 | } else {sql_bf.append(field);} 60 | sql_bf.append(" FROM ").append(table); 61 | if (!MCheck.isNull(where)) { // 不为空,则有where 语句 62 | sql_bf.append(" WHERE 1=1 ").append(where); 63 | } 64 | 65 | // sql_bf.append(" order by id desc ");//} else { 66 | if (!MCheck.isNull(params)) { 67 | sql_bf.append(" ").append(params[0]); 68 | } 69 | sql_bf.append(" limit 1"); 70 | if(cache){ 71 | List data = null;//select(sql_bf.toString()); 72 | if (MCache.me().isEnabled()) { 73 | data = MCache.me().read(sql_bf.toString()); 74 | } 75 | if(MCheck.isNull(data)){ 76 | data=select(sql_bf.toString()); 77 | }else { 78 | MSee.ok_sql(new IAtom() { 79 | public void run() throws Exception { 80 | MReport.doFileReport(sql_bf.toString()); 81 | } 82 | }, is_dev()); 83 | } 84 | 85 | return MCheck.isNull(data)?null:data.get(0); 86 | }else{ 87 | List data = select(sql_bf.toString()); 88 | return MCheck.isNull(data)?null:data.get(0); 89 | } 90 | } 91 | 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/com/jzero/core/MReport.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.core; 3 | 4 | import java.io.File; 5 | 6 | import com.jzero.db.cache.MCache; 7 | import com.jzero.util.MCheck; 8 | import com.jzero.util.MDate; 9 | 10 | /** 11 | * 2012-10-3: 参照JFinal,用于将当前操作显示到控制台,需要借助AOP注解完成 12 | * wangujqw@gmail.com 13 | */ 14 | public class MReport { 15 | public static final void doSQLReport(String sql,Object... uris){ 16 | StringBuilder sb = new StringBuilder("\nJZero SQL report ###### ").append(MDate.get_ymd_hms()).append(" ##########################\n"); 17 | sb.append("sql=> :").append(sql).append("\n"); 18 | 19 | if(!MCheck.isNull(uris)){ 20 | sb.append("UrlPara : ").append("\n"); 21 | for(Object str:uris){ 22 | sb.append("\t \t \t \t uri : ").append(str).append("\n"); 23 | } 24 | } 25 | sb.append("######################################################################\n"); 26 | System.out.print(sb.toString()); 27 | } 28 | public static final void doFileReport(String sql){ 29 | File file=MCache.me().get_path(sql); 30 | StringBuilder sb = new StringBuilder("\nJZero File report ###### ").append(MDate.get_ymd_hms()).append(" ##########################\n"); 31 | sb.append("正在读取缓存文件=>").append(file.getName()).append("\n"); 32 | sb.append("sql=> :").append(sql).append("\n"); 33 | sb.append("#######################################################################\n"); 34 | System.out.print(sb.toString()); 35 | } 36 | public static final void doErrorReport(String path,String controller,String method,String... uris) { 37 | StringBuilder sb = new StringBuilder("\nJZero NOT FIND ACTION report-------- ").append(MDate.get_ymd_hms()).append(" ------------------------------\n"); 38 | sb.append("Package :").append(path); 39 | sb.append("\nController : ").append(controller).append(".java"); 40 | sb.append("\nMethod : ").append(method).append("()").append("\n"); 41 | sb.append("\ntarget : ").append(MInit.get().uri()+"\n"); 42 | if(!MCheck.isNull(uris)){ 43 | sb.append("UrlPara : ").append("\n"); 44 | for(String str:uris){ 45 | sb.append("\t \t \t \t uri : ").append(str).append("\n"); 46 | } 47 | } 48 | 49 | sb.append("--------------------------------------------------------------------------------\n"); 50 | System.out.print(sb.toString()); 51 | } 52 | public static final void doReport(String path,String controller,String method,String... uris) { 53 | StringBuilder sb = new StringBuilder("\nJZero action report -------- ").append(MDate.get_ymd_hms()).append(" ------------------------------\n"); 54 | sb.append("Package :").append(path); 55 | sb.append("\nController : ").append(controller).append(".java"); 56 | sb.append("\nMethod : ").append(method).append("()").append("\n"); 57 | sb.append("\ntarget : ").append(MInit.get().uri()+"\n"); 58 | if(!MCheck.isNull(uris)){ 59 | sb.append("UrlPara : ").append("\n"); 60 | for(String str:uris){ 61 | sb.append("\t uri : ").append(str).append("\n"); 62 | } 63 | } 64 | sb.append("--------------------------------------------------------------------------------\n"); 65 | System.out.print(sb.toString()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/com/jzero/util/MImage.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.awt.Color; 4 | import java.awt.Font; 5 | import java.awt.Graphics; 6 | import java.awt.image.BufferedImage; 7 | import java.io.IOException; 8 | import java.util.Random; 9 | import javax.imageio.ImageIO; 10 | import javax.servlet.ServletException; 11 | import javax.servlet.ServletOutputStream; 12 | import javax.servlet.http.HttpServlet; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import javax.servlet.http.HttpSession; 16 | 17 | public class MImage extends HttpServlet { 18 | private static final long serialVersionUID = 1L; 19 | 20 | public void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ 21 | processRequest(request,response); 22 | } 23 | protected void processRequest(HttpServletRequest request, 24 | HttpServletResponse response) throws ServletException, IOException { 25 | response.setContentType("image/jpeg"); 26 | response.setHeader("Pragma", "No-cache"); 27 | response.setHeader("Cache-Control", "no-cache"); 28 | response.setDateHeader("Expires", 0L); 29 | HttpSession session = request.getSession(); 30 | 31 | int width = 60; 32 | int height = 20; 33 | BufferedImage image = new BufferedImage(width, height, 1); 34 | 35 | Graphics g = image.getGraphics(); 36 | 37 | Random random = new Random(); 38 | 39 | g.setColor(getRandColor(200, 250)); 40 | g.fillRect(0, 0, width, height); 41 | 42 | g.setFont(new Font("Times New Roman", 0, 18)); 43 | 44 | g.setColor(getRandColor(160, 200)); 45 | for (int i = 0; i < 155; ++i) { 46 | int x = random.nextInt(width); 47 | int y = random.nextInt(height); 48 | int xl = random.nextInt(12); 49 | int yl = random.nextInt(12); 50 | g.drawLine(x, y, x + xl, y + yl); 51 | } 52 | 53 | String sRand = ""; 54 | for (int i = 0; i < 4; ++i) { 55 | String rand = String.valueOf(random.nextInt(10)); 56 | sRand = sRand + rand; 57 | 58 | g.setColor(new Color(20 + random.nextInt(110), 20 + random 59 | .nextInt(110), 20 + random.nextInt(110))); 60 | g.drawString(rand, 13 * i + 6, 16); 61 | } 62 | 63 | session.setAttribute("rand", sRand); 64 | 65 | g.dispose(); 66 | ServletOutputStream responseOutputStream = response.getOutputStream(); 67 | 68 | ImageIO.write(image, "JPEG", responseOutputStream); 69 | 70 | responseOutputStream.flush(); 71 | responseOutputStream.close(); 72 | } 73 | 74 | Color getRandColor(int fc, int bc) { 75 | Random random = new Random(); 76 | if (fc > 255) 77 | fc = 255; 78 | if (bc > 255) 79 | bc = 255; 80 | int r = fc + random.nextInt(bc - fc); 81 | int g = fc + random.nextInt(bc - fc); 82 | int b = fc + random.nextInt(bc - fc); 83 | return new Color(r, g, b); 84 | } 85 | 86 | protected void doGet(HttpServletRequest request, 87 | HttpServletResponse response) throws ServletException, IOException { 88 | processRequest(request, response); 89 | } 90 | 91 | protected void doPost(HttpServletRequest request, 92 | HttpServletResponse response) throws ServletException, IOException { 93 | processRequest(request, response); 94 | } 95 | 96 | public String getServletInfo() { 97 | return "Short description"; 98 | } 99 | } -------------------------------------------------------------------------------- /src/com/jzero/cache/C.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.cache; 3 | 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import com.jzero.log.Log; 8 | import com.jzero.util.MCheck; 9 | import com.jzero.util.MPrint; 10 | import com.jzero.util.MPro; 11 | import com.jzero.util.MRecord; 12 | 13 | /** 14 | * 2012-10-7: 缓存管理类 15 | * wangujqw@gmail.com 16 | */ 17 | public class C { 18 | 19 | /** 20 | * 设置缓存 2011-11-17,设置缓存时间为三分钟 21 | */ 22 | public static void setCache(List lst, String cacheKey) { 23 | try { 24 | String cache_time=MPro.me().getStr("cache_time"); 25 | int time=MCheck.isNull(cache_time)?3:Integer.parseInt(cache_time); 26 | CacheManager.me().putContent(cacheKey, lst, time * 60); 27 | } catch (Exception e) { 28 | Log.me().write_error(e); 29 | } 30 | } 31 | public static void setCache(Object obj,String cacheKey){ 32 | try { 33 | String cache_time=MPro.me().getStr("cache_time"); 34 | int time=MCheck.isNull(cache_time)?3:Integer.parseInt(cache_time); 35 | CacheManager.me().putContent(cacheKey, obj, time * 60); 36 | } catch (Exception e) { 37 | Log.me().write_error(e); 38 | } 39 | } 40 | 41 | /** 42 | * 43 | * @param lst 缓存的列表内容 44 | * @param cacheKey 缓存的主键 45 | * @param min 时间,分为单位 46 | */ 47 | public static void setCache(List lst, String cacheKey,int min) {// min 分钟  48 | try { 49 | CacheManager.me().putContent(cacheKey, lst, min * 60); 50 | } catch (Exception e) { 51 | Log.me().write_error(e); 52 | } 53 | } 54 | public static void setCache(Object obj, String cacheKey,int min) {// min 分钟  55 | try { 56 | CacheManager.me().putContent(cacheKey, obj, min * 60); 57 | } catch (Exception e) { 58 | Log.me().write_error(e); 59 | } 60 | } 61 | /** 62 | * 63 | * @param cacheKey 读取缓存 64 | * @return 65 | */ 66 | @SuppressWarnings("unchecked") 67 | public static List getCache(String cacheKey) { 68 | try { 69 | Cache cache=CacheManager.me().getContent(cacheKey); 70 | return MCheck.isNull(cache)?null:(List)cache.getValue(); 71 | } catch (Exception e) { 72 | Log.me().write_error(e); 73 | } 74 | return null; 75 | } 76 | public static Object getCacheObj(String cacheKey) { 77 | try { 78 | Cache cache=CacheManager.me().getContent(cacheKey); 79 | return MCheck.isNull(cache)?null:cache.getValue(); 80 | } catch (Exception e) { 81 | Log.me().write_error(e); 82 | } 83 | return null; 84 | } 85 | //删除 86 | public static void removeCache(String cacheKey) { 87 | try { 88 | CacheManager.me().invalidate(cacheKey); 89 | } catch (Exception e) { 90 | Log.me().write_error(e); 91 | } 92 | } 93 | public static Map get(){ 94 | return CacheManager.me().getMap(); 95 | } 96 | public static void main(String[] args) throws InterruptedException { 97 | MPrint.print(CacheManager.me().toString()); 98 | C.setCache("A", "a"); 99 | C.setCache("B", "b"); 100 | C.setCache("C", "c"); 101 | C.setCache("D", "d"); 102 | C.setCache("E", "e"); 103 | C.setCache("F", "f"); 104 | C.setCache("G", "g"); 105 | MPrint.print(CacheManager.me().toString()); 106 | Thread.sleep(5000*100); 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/com/jzero/db/cache/MFile.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.cache; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileReader; 8 | import java.io.FileWriter; 9 | import java.io.IOException; 10 | import java.util.HashMap; 11 | import java.util.List; 12 | import java.util.Map; 13 | 14 | import com.jzero.json.JSONObj; 15 | import com.jzero.log.Log; 16 | import com.jzero.log.LogEnum; 17 | import com.jzero.util.MCheck; 18 | import com.jzero.util.MPrint; 19 | import com.jzero.util.MRecord; 20 | 21 | /** 22 | * 2012-10-3: wangujqw@gmail.com 23 | */ 24 | public class MFile { 25 | private static Map content = new HashMap(); 26 | 27 | public static BufferedWriter getWriter(File file_name, boolean isAppend) { 28 | try { 29 | return file_name.exists() ? new BufferedWriter(new FileWriter( 30 | file_name, isAppend)) : null; 31 | } catch (IOException e) { 32 | Log.me().write_error(e); 33 | } 34 | return null; 35 | } 36 | 37 | public static BufferedReader getReader(File file_name) { 38 | try { 39 | return new BufferedReader(new FileReader(file_name)); 40 | } catch (FileNotFoundException e) { 41 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 42 | } 43 | return null; 44 | } 45 | 46 | public static void write(File file_name, List lst) { 47 | BufferedWriter w = getWriter(file_name, false); 48 | try { 49 | if (!MCheck.isNull(w)) { 50 | w.write(JSONObj.toJSONString(lst)); 51 | } 52 | } catch (IOException e) { 53 | Log.me().write_error(e); 54 | } finally { 55 | try { 56 | if (!MCheck.isNull(w)) { 57 | w.flush(); 58 | w.close(); 59 | } 60 | } catch (IOException e) { 61 | Log.me().write_error(e); 62 | } 63 | } 64 | } 65 | 66 | private static String getStr(File file_name) { 67 | StringBuffer sb = new StringBuffer(); 68 | BufferedReader br = getReader(file_name); 69 | try { 70 | // char c[]=new char[1024];fsdf 71 | if (!MCheck.isNull(br)) { 72 | String line = br.readLine(); 73 | while (!MCheck.isNull(line)) { 74 | sb.append(line.trim()); 75 | line = br.readLine(); 76 | } 77 | content.put(file_name, sb); 78 | } 79 | } catch (IOException e) { 80 | Log.me().write_error(e); 81 | } finally { 82 | try { 83 | if (!MCheck.isNull(br)) { 84 | br.close(); 85 | } 86 | } catch (IOException e) { 87 | Log.me().write_error(e); 88 | } 89 | } 90 | return sb.toString(); 91 | } 92 | 93 | public static List read(File file_name) { 94 | return MCheck.isNull(file_name) ? null : JSONObj 95 | .parseList(getStr(file_name)); 96 | } 97 | 98 | // 创建目录 99 | public static File createDir(String dir_name) { 100 | File file = new File(dir_name); 101 | if (!file.exists()) { 102 | file.mkdirs(); 103 | } 104 | return file; 105 | } 106 | 107 | // 创建文件 108 | public static File createFile(String dir_name, String file_name) { 109 | File file = createDir(dir_name); 110 | file = new File(file, file_name); 111 | if (!file.exists()) { 112 | try { 113 | file.createNewFile(); 114 | } catch (Exception e) { 115 | MPrint.print(e.getMessage()); 116 | } 117 | } 118 | return file; 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/com/jzero/json/JSONTool.java: -------------------------------------------------------------------------------- 1 | package com.jzero.json; 2 | 3 | import java.util.Iterator; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | 8 | import com.jzero.util.MCheck; 9 | import com.jzero.util.MRecord; 10 | 11 | /** 12 | * --- 2012-5-8 --- 13 | * 来源于json-simple: http://code.google.com/p/json-simple/ 14 | */ 15 | @SuppressWarnings("unchecked") 16 | public class JSONTool { 17 | 18 | 19 | public static String toJSONString(List list) { 20 | if (list == null) 21 | return "null"; 22 | 23 | boolean first = true; 24 | StringBuffer sb = new StringBuffer(); 25 | Iterator iter = list.iterator(); 26 | 27 | sb.append('['); 28 | while (iter.hasNext()) { 29 | if (first) 30 | first = false; 31 | else 32 | sb.append(','); 33 | 34 | Object value = iter.next(); 35 | if (value == null) { 36 | sb.append("null"); 37 | continue; 38 | } 39 | sb.append(JSONObj.toJSONString(value)); 40 | } 41 | sb.append(']'); 42 | return sb.toString().trim(); 43 | } 44 | 45 | public static String toJSONString(MRecord record) { 46 | if (record == null) 47 | return "null"; 48 | 49 | StringBuffer sb = new StringBuffer(); 50 | boolean first = true; 51 | Iterator> iter = record.entrySet().iterator(); 52 | 53 | sb.append('{'); 54 | while (iter.hasNext()) { 55 | if (first) 56 | first = false; 57 | else 58 | sb.append(','); 59 | Map.Entry entry = iter.next(); 60 | String name=String.valueOf(entry.getKey()); 61 | Object value=entry.getValue(); 62 | toJSONString(name.toLowerCase(),value, sb); 63 | } 64 | sb.append('}'); 65 | return sb.toString(); 66 | } 67 | 68 | private static String toJSONString(String key, Object value, StringBuffer sb) { 69 | sb.append('\"'); 70 | if (key == null) 71 | sb.append("null"); 72 | else 73 | escape(key, sb); 74 | sb.append('\"').append(':'); 75 | 76 | sb.append(JSONObj.toJSONString(value)); 77 | 78 | return sb.toString(); 79 | } 80 | public static String escape(String s){ 81 | if(MCheck.isNull(s)) 82 | return ""; 83 | StringBuffer sb = new StringBuffer(); 84 | escape(s, sb); 85 | return sb.toString(); 86 | } 87 | static void escape(String s, StringBuffer sb) { 88 | for (int i = 0; i < s.length(); i++) { 89 | char ch = s.charAt(i); 90 | switch (ch) { 91 | case '"': 92 | sb.append("\""); 93 | break; 94 | case '\\': 95 | sb.append("\\\\"); 96 | break; 97 | case '\b': 98 | sb.append("\\b"); 99 | break; 100 | case '\f': 101 | sb.append("\\f"); 102 | break; 103 | case '\n': 104 | sb.append("\\n"); 105 | break; 106 | case '\r': 107 | sb.append("\\r"); 108 | break; 109 | case '\t': 110 | sb.append("\\t"); 111 | break; 112 | // case '/': 113 | // sb.append("\\/"); 114 | // break; 115 | default: 116 | // Reference: http://www.unicode.org/versions/Unicode5.1.0/ 117 | if ((ch >= '\u0000' && ch <= '\u001F') 118 | || (ch >= '\u007F' && ch <= '\u009F') 119 | || (ch >= '\u2000' && ch <= '\u20FF')) { 120 | String ss = Integer.toHexString(ch); 121 | sb.append("\\u"); 122 | for (int k = 0; k < 4 - ss.length(); k++) { 123 | sb.append('0'); 124 | } 125 | sb.append(ss.toUpperCase()); 126 | } else { 127 | sb.append(ch); 128 | } 129 | } 130 | }// for 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/com/jzero/util/MSee.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.util.List; 4 | 5 | import com.jzero.log.Log; 6 | 7 | /** 8 | * 秒表 9 | * 10 | * @author zozoh(zozohtnt@gmail.com) 11 | */ 12 | public class MSee { 13 | 14 | private long from; 15 | private long to; 16 | 17 | public static MSee begin() { 18 | MSee sw = new MSee(); 19 | sw.start(); 20 | return sw; 21 | } 22 | 23 | public static MSee create() { 24 | return new MSee(); 25 | } 26 | 27 | public static MSee run(Runnable atom) { 28 | MSee sw = begin(); 29 | atom.run(); 30 | sw.stop(); 31 | return sw; 32 | } 33 | 34 | public long start() { 35 | from = System.currentTimeMillis(); 36 | return from; 37 | } 38 | 39 | public long stop() { 40 | to = System.currentTimeMillis(); 41 | return to; 42 | } 43 | 44 | public long getDuration() { 45 | return to - from; 46 | } 47 | 48 | public long getStartTime() { 49 | return from; 50 | } 51 | 52 | public long getEndTime() { 53 | return to; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return String.format("Total: %dms : [%s]=>[%s]", this.getDuration(), 59 | new java.sql.Timestamp(from).toString(), 60 | new java.sql.Timestamp(to).toString()); 61 | } 62 | 63 | public static void ok_time(IAtom atom, boolean boolRun) { 64 | MSee watch = null; 65 | if (boolRun) { 66 | watch = MSee.begin(); 67 | } 68 | try { 69 | atom.run(); 70 | } catch (Exception e) { 71 | Log.me().write_error(e); 72 | } 73 | if (boolRun) { 74 | watch.stop(); 75 | MPrint.print(watch.toString()); 76 | } 77 | } 78 | public static List ok_time(IAtom2 atom, boolean boolRun) { 79 | MSee watch = null; 80 | List datas=null; 81 | if (boolRun) { 82 | watch = MSee.begin(); 83 | } 84 | try { 85 | datas=atom.run(); 86 | } catch (Exception e) { 87 | Log.me().write_error(e); 88 | } 89 | if (boolRun) { 90 | watch.stop(); 91 | MPrint.print(watch.toString()); 92 | } 93 | return datas; 94 | } 95 | public static void ok_time(IAtom3 atom, boolean boolRun,final List datas) { 96 | MSee watch = null; 97 | if (boolRun) { 98 | watch = MSee.begin(); 99 | } 100 | try { 101 | atom.run(datas); 102 | } catch (Exception e) { 103 | Log.me().write_error(e); 104 | } 105 | if (boolRun) { 106 | watch.stop(); 107 | MPrint.print(watch.toString()); 108 | } 109 | } 110 | public static int ok_time(IAtom4 atom, boolean boolRun) { 111 | MSee watch = null; 112 | int i=0; 113 | if (boolRun) { 114 | watch = MSee.begin(); 115 | } 116 | try { 117 | i=atom.run(); 118 | } catch (Exception e) { 119 | Log.me().write_error(e); 120 | } 121 | if (boolRun) { 122 | watch.stop(); 123 | MPrint.print(watch.toString()); 124 | } 125 | return i; 126 | } 127 | public static void ok_sql(IAtom atom, boolean boolRun) { 128 | if (boolRun) { 129 | try { 130 | atom.run(); 131 | } catch (Exception e) { 132 | Log.me().write_error(e); 133 | } 134 | } 135 | } 136 | 137 | public static void main(String[] args) throws Exception { 138 | 139 | } 140 | 141 | public interface IAtom { 142 | public void run() throws Exception ; 143 | } 144 | public interface IAtom2{ 145 | public List run() throws Exception ; 146 | } 147 | public interface IAtom3{ 148 | public void run(List datas) throws Exception; 149 | } 150 | public interface IAtom4{ 151 | public int run() throws Exception; 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /视图操作: -------------------------------------------------------------------------------- 1 | 1、index.jsp 首页面 2 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 3 | <%@ page import="com.jzero.util.*,com.jzero.tag.*,com.jzero.core.*"%> 4 | <%=T.js("js/My97DatePicker/WdatePicker.js") %> 5 | 6 | 7 | 8 | <%=T.form_open("","delForm") %> 9 | <%=T.table_list(5,"友情链接")%> 10 | <%=T.tr()%> 11 | <%=T.td("center",T.a_checkbox(),"5%") %> 12 | <%=T.td("15%","网站名称") %> 13 | <%=T.td("30%","网站地址") %> 14 | <%=T.td("30%","描述") %> 15 | <%=T.td("center","操作","15%") %> 16 | <%=T.tr_close() %> 17 | <% List lst=MR.me().getAttr(Msg.LIST_DATAS);if(!MCheck.isNull(lst)){for(MRecord row:lst){ %> 18 | <%=T.tr() %> 19 | <%=T.td("center",T.a_checkbox(row.getStr("id")),"5%") %> 20 | <%=T.td(T.a_view(row.getStr("id"),row.getStr("webname")))%> 21 | <%=T.td(T.a(row.getStr("website"))) %> 22 | <%=T.td(row.getStr("content")) %> 23 | <%=T.td_c("center") %> 24 | <%=T.a_edit(row.getStr("id")) %> 25 | <%=T.a_del(row.getStr("id")) %> 26 | <%=T.td_close() %> 27 | <%=T.tr_close() %> 28 | <% }}%> 29 | <%=T.form_close() %> 30 | <%=T.pager(5) %> 31 | <%=T.table_close() %> 32 | <%=T.end()%> 33 | 34 | 35 | 36 | 2、新增页面 37 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 38 | <%@ page import="com.jzero.util.*,com.jzero.tag.T,com.jzero.core.*"%> 39 | 40 | 41 | 42 | <%=T.add_table() %> 43 | <%=T.tr() %><%=T.td_l("20%","网站名称","webname") %><%=T.td() %><%=T.input_must_style("webname","width:280px")%><%=T.td_close() %><%=T.tr_close() %> 44 | <%=T.tr() %><%=T.td_l("网站地址","website") %><%=T.td() %><%=T.input_must_style("website","http://","width:280px")%><%=T.td_close() %><%=T.tr_close() %> 45 | <%=T.tr() %><%=T.td_l("网站描述","content") %><%=T.td(T.textarea_kind_no("content",320)) %><%=T.tr_close() %> 46 | <%=T.tr_space() %> 47 | <%=T. table_close_form() %> 48 | <%=T.alert() %> 49 | <%=T.kind_js("content") %> 50 | <%=T.end() %> 51 | 52 | 53 | 3、修改页面 54 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 55 | <%@ page import="com.jzero.util.*,com.jzero.tag.T,com.jzero.core.*"%> 56 | <%=T.js("js/My97DatePicker/WdatePicker.js") %> 57 | <%@include file="/comm/js/wdate.jsp" %> 58 | 59 | 60 | 61 | <% MRecord row=MR.me().getAttr(Msg.OBJECT); %> 62 | <%=T.edit_table() %> 63 | <%=T.hidden_id(row.getStr("id")) %> 64 | <%=T.tr() %><%=T.td_l("20%","网站名称","webname") %><%=T.td() %><%=T.input_must_style("webname",row.getStr("webname"),"width:280px")%><%=T.td_close() %><%=T.tr_close() %> 65 | <%=T.tr() %><%=T.td_l("网站地址","website") %><%=T.td() %><%=T.input_must_style("website",row.getStr("website"),"width:280px")%><%=T.td_close() %><%=T.tr_close() %> 66 | <%=T.tr() %><%=T.td_l("网站描述","content") %><%=T.td(T.textarea_kind_no("content",row.getStr("content"),320)) %><%=T.tr_close() %> 67 | <%=T.tr_space() %> 68 | <%=T. table_close_form() %> 69 | <%=T.kind_js("content") %> 70 | <%=T.end() %> 71 | 72 | 73 | 4、查看页面 74 | <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 75 | <%@ page import="com.jzero.util.*,com.jzero.tag.T,com.jzero.core.*"%> 76 | <%@include file="/comm/jsp/view_top.jsp" %> 77 | <%=T.view_table() %> 78 | <%=T.tr() %><%=T.td_l("20%","网站名称","webname") %><%=T.td(obj.getStr("webname")) %><%=T.tr_close() %> 79 | <%=T.tr() %><%=T.td_l("网站地址","website") %><%=T.td(T.a(obj.getStr("website"))) %><%=T.tr_close() %> 80 | <%=T.tr() %><%=T.td_l("网站描述","content") %><%=T.td(obj.getStr("content")) %><%=T.tr_close() %> 81 | <%=T.tr_space(2) %> 82 | <%=T. table_close_form() %> 83 | <%=T.end() %> 84 | -------------------------------------------------------------------------------- /src/com/jzero/util/MPro.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | import java.net.URLDecoder; 10 | import java.util.Properties; 11 | @SuppressWarnings("unchecked") 12 | public class MPro { 13 | 14 | private Properties properties = new Properties(); 15 | private static MPro mpro=new MPro(); 16 | private InputStream inputFile; 17 | private OutputStream outputStream; 18 | private String filename = null; 19 | 20 | public static MPro me() { 21 | return mpro; 22 | } 23 | public void printProperties(){ 24 | properties.list(System.out); 25 | } 26 | 27 | public MPro load_file(String fileName) { 28 | loadPro(fileName); 29 | this.filename = fileName; 30 | return this; 31 | } 32 | 33 | private void loadPro(String fileName) { 34 | try { 35 | inputFile = getInputStream(fileName); 36 | if(!MCheck.isNull(inputFile)){ 37 | properties.load(inputFile); 38 | 39 | if(getBool("show_prop")){ 40 | MPrint.print(fileName); 41 | properties.list(System.out); 42 | } 43 | inputFile.close(); 44 | } 45 | } catch (IOException ex) { 46 | ex.printStackTrace(); 47 | // Log.me().write_log(LogEnum.ERROR, ex.getMessage()); 48 | } 49 | } 50 | private InputStream getInputStream(String fileName) { 51 | String path=null; 52 | try { 53 | path = MPath.me().getRootClassPath() + "/" + fileName; 54 | return new FileInputStream(path); 55 | } catch (IOException e) { 56 | e.printStackTrace(); 57 | MPrint.print("加载文件失败"+path); 58 | // Log.me().write_error(e); 59 | } 60 | return null; 61 | } 62 | 63 | private OutputStream getOutputStream(String fileName) throws Exception { 64 | return new FileOutputStream(new File(getfilePath(fileName))); 65 | } 66 | private String getfilePath(String filename){ 67 | return MPath.me().getWebInfPath()+"classes/"+filename; 68 | } 69 | 70 | public Object getObj(String k) { 71 | return properties == null ? null : properties.get(k); 72 | } 73 | 74 | public String getStr(String k) { 75 | return MCheck.isNull(getObj(k)) ? "" : getObj(k).toString(); 76 | } 77 | 78 | public boolean getBool(String k) { 79 | return MCheck.isNull(getStr(k)) ? false : Boolean.valueOf(getStr(k)); 80 | } 81 | 82 | public int getInt(String k) { 83 | return MCheck.isNull(getStr(k)) ? 0 : Integer.parseInt(getStr(k)); 84 | } 85 | 86 | public void setValue(String name, String value) { 87 | if (MCheck.isNull(properties)) { 88 | MPrint.print("pri is null!!"); 89 | } else { 90 | try { 91 | outputStream = getOutputStream(filename); 92 | outputStream = getOutputStream(filename); 93 | properties.setProperty(name, value); 94 | properties.store(outputStream,"JZero"); 95 | outputStream.flush(); 96 | outputStream.close(); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } 100 | } 101 | } 102 | /** 103 | * 保存到指定的文件中,test 104 | */ 105 | public void setValue_file(String filename,String name, String value) { 106 | if (MCheck.isNull(properties)) { 107 | MPrint.print("pri is null!!"); 108 | } else { 109 | try { 110 | outputStream = getOutputStream(filename); 111 | outputStream = getOutputStream(filename); 112 | properties.setProperty(name, value); 113 | properties.store(outputStream,"JZero"); 114 | outputStream.flush(); 115 | outputStream.close(); 116 | } catch (Exception e) { 117 | e.printStackTrace(); 118 | } 119 | } 120 | } 121 | 122 | @SuppressWarnings( { "deprecation"}) 123 | public static String getPath(String packName, Class cls) { 124 | String currentPath = cls.getResource("/" + packName).toString(); 125 | currentPath = currentPath.substring(6); 126 | return URLDecoder.decode(currentPath); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/com/jzero/db/back/MysqlBack.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.back; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.io.OutputStreamWriter; 9 | 10 | import com.jzero.util.MCheck; 11 | import com.jzero.util.MDate; 12 | import com.jzero.util.MEncrypt; 13 | import com.jzero.util.MPath; 14 | import com.jzero.util.MPro; 15 | import com.jzero.util.MRecord; 16 | import com.jzero.util.MTool; 17 | 18 | /** 19 | * 2012-10-24: wangujqw@gmail.com 20 | */ 21 | public class MysqlBack implements MBackup { 22 | 23 | public MRecord backup() { 24 | MRecord record = new MRecord(); 25 | MPro pros = MPro.me(); 26 | String user = MEncrypt.decrypt(MPro.me().getStr("username")); 27 | String _temp_pass = MPro.me().getStr("password"); 28 | String pwd = MCheck.isNull(_temp_pass) ? "" : MEncrypt.decrypt(_temp_pass); 29 | String hostname = pros.getStr("hostname"); 30 | String database = pros.getStr("database"); 31 | String back_file = MPath.me().getSrcPath() + "/back/"; 32 | // String mysqlpaths = pros.getStr("mysql_path"); 33 | String mysqlpaths=MPath.me().getWebInfPath()+"classes/"; 34 | String backName = MDate.get_ymd_hms_join() + ".sql"; 35 | record.set("name", backName); 36 | File backupath = new File(back_file); 37 | if (!backupath.exists()) { 38 | backupath.mkdir(); 39 | } 40 | try { 41 | StringBuffer sb = new StringBuffer(); 42 | sb.append(mysqlpaths).append("mysqldump.exe -h ").append(hostname) 43 | .append(" -u").append(user).append(" -p").append(pwd) 44 | .append(" ").append(database); 45 | Process p = Runtime.getRuntime().exec(sb.toString()); 46 | copy(p, new File(back_file, backName)); 47 | record.set("size", MTool.formart_bytes(new File(back_file, backName))); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | return record; 52 | 53 | } 54 | 55 | 56 | private void copy(Process p, File dst) { 57 | // 设置导出编码为utf-8。这里必须是utf-8 58 | // 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行 59 | BufferedReader br = null; 60 | OutputStreamWriter writer = null; 61 | try { 62 | // 设置输出流编码为utf-8。这里必须是utf-8,否则从流中读入的是乱码 63 | String inStr; 64 | StringBuffer sb = new StringBuffer(""); 65 | // 组合控制台输出信息字符串 66 | br = new BufferedReader(new InputStreamReader(p.getInputStream(), 67 | "utf-8")); 68 | while ((inStr = br.readLine()) != null) { 69 | sb.append(inStr + "\r\n"); 70 | } 71 | // 要用来做导入用的sql目标文件: 72 | writer = new OutputStreamWriter(new FileOutputStream(dst), "utf-8"); 73 | writer.write(sb.toString()); 74 | writer.flush(); 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | } finally { 78 | try { 79 | if(!MCheck.isNull(br)){br.close();} 80 | if(!MCheck.isNull(br)){writer.close();} 81 | } catch (Exception e) { 82 | e.printStackTrace(); 83 | } 84 | } 85 | } 86 | 87 | public void load(String filename) { 88 | String mysqlpaths = MPro.me().getStr("mysql_path"); 89 | String user = MEncrypt.decrypt(MPro.me().getStr("username")); 90 | String _temp_pass = MPro.me().getStr("password"); 91 | String pwd = MCheck.isNull(_temp_pass) ? "" : MEncrypt.decrypt(_temp_pass); 92 | String back_file = MPath.me().getSrcPath() + "/back"; 93 | String filepath = back_file + filename; // 备份的路径地址 94 | 95 | // 新建数据库finacing 96 | String stmt1 = mysqlpaths + " mysqladmin -u " + user + " -p" + pwd 97 | + " create finacing"; // -p后面加的是你的密码 98 | String stmt2 = "mysql -u " + user + " -p" + pwd + " finacing < " 99 | + filepath; 100 | String[] cmd = { "cmd", "/c", stmt2 }; 101 | try { 102 | Runtime.getRuntime().exec(stmt1); 103 | Runtime.getRuntime().exec(cmd); 104 | System.out.println("数据已从 " + filepath + " 导入到数据库中"); 105 | } catch (IOException e) { 106 | e.printStackTrace(); 107 | } 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/com/jzero/core/MURI.java: -------------------------------------------------------------------------------- 1 | package com.jzero.core; 2 | 3 | import java.util.regex.Pattern; 4 | 5 | import com.jzero.util.MCheck; 6 | import com.jzero.util.MPrint; 7 | import com.jzero.util.MTool; 8 | 9 | /** 10 | * 2012-10-3: 参照CI URI ,解析URI 11 | * wangujqw@gmail.com 12 | */ 13 | public class MURI { 14 | private String SLASH = "/"; 15 | 16 | // 返回的参数 17 | private String[] uri_strs; 18 | 19 | private Pattern p = null; 20 | public static MURI me() { 21 | return MInit.get().getURI(); 22 | } 23 | public static MURI init(MInit init){ 24 | MURI uri=new MURI(); 25 | uri.p=Pattern.compile(init.getConfig().getStr("permitted_uri_chars")); 26 | return uri; 27 | } 28 | 29 | public String seg_str(int index) { 30 | return MCheck.isNull(getUri_strs()) ? null : getUri_strs().length > index ? MTool.UTF8(index_uri(index)) :null ; 31 | } 32 | 33 | public String seg_str(int index, String defaultValue) { 34 | return MCheck.isNull(getUri_strs()) ? defaultValue: getUri_strs().length>index?MTool.UTF8(index_uri(index)):null; 35 | } 36 | public String seg_str(int index,String[] uris){ 37 | return MCheck.isNull(uris)?null:uris.length>index?index_uri(index,uris):null; 38 | } 39 | public int seg_int(int index) { 40 | return MCheck.isNull(getUri_strs()) ? null :getUri_strs().length>index?Integer.parseInt(index_uri(index)):null ; 41 | } 42 | public int seg_int(int index,String[] uris){ 43 | return MCheck.isNull(uris)?null:getUri_strs().length>index?Integer.parseInt(index_uri(index,uris)):null; 44 | } 45 | 46 | public int seg_int(int index, int defaultValue) { 47 | return MCheck.isNull(getUri_strs()) ? defaultValue : getUri_strs().length>index?Integer.parseInt(index_uri(index)):null; 48 | } 49 | 50 | private String index_uri(int index){ 51 | String value=getUri_strs()[index]; 52 | if(!p.matcher(value).matches()){ 53 | MInit.get().getMb().getTextRender("The URI you submitted has disallowed characters.=>"+value); 54 | } 55 | return value; 56 | } 57 | private String index_uri(int index,String[] uris){ 58 | String value=uris[index]; 59 | if(!p.matcher(value).matches()){ 60 | MInit.get().getMb().getTextRender("The URI you submitted has disallowed characters."); 61 | } 62 | return value; 63 | } 64 | /** 65 | * http://localhost:8080/JZero/News/index/t1/t2/t3 66 | * /JZero/News/index/t1/t2/t3 在过滤器中可以传递值过来 67 | * @param uri 68 | */ 69 | public String[] parse(String uri) { 70 | // setUri_string(uri); 71 | if (!MCheck.isNull(uri)) { 72 | if (uri.contains("http")) { 73 | uri_strs = parseURL(uri); 74 | } else { 75 | uri_strs = parseURI(uri); 76 | } 77 | } 78 | return uri_strs; 79 | } 80 | 81 | 82 | // ->/JZero/News(0)/index(1)/t1(2)/t2(3)/t3(4) 83 | private String[] parseURI(String uri) { 84 | String uri_strs[]=null; 85 | if(!MCheck.isNull(uri)){ 86 | String proName=MInit.get().getMr().getProject(); 87 | if(!MCheck.isNull(proName)){ 88 | uri_strs = uri.replace(proName, "").replaceFirst("/", "").split(SLASH); 89 | }else{ 90 | uri_strs=uri.replaceFirst("/", "").split(SLASH); 91 | } 92 | } 93 | return uri_strs; 94 | } 95 | public static void main(String[] args) { 96 | String string="/index/download"; 97 | if(!MCheck.isNull(string)){ 98 | String[] uri_strs=string.replaceFirst("/", "").split("/"); 99 | for(String s:uri_strs){ 100 | MPrint.print(s); 101 | } 102 | } 103 | } 104 | 105 | // ->http://localhost:8080/JZero/News/index/t1/t2/t3 106 | private String[] parseURL(String uri) { 107 | String uri_strs[]=null; 108 | if(!MCheck.isNull(uri)){ 109 | String proName=MInit.get().getMr().getProject(); 110 | if(!MCheck.isNull(proName)){ 111 | uri_strs = uri.replace(proName, "").replaceFirst("/", "").split(SLASH); 112 | }else{ 113 | uri_strs=uri.replaceFirst("/", "").split(SLASH); 114 | } 115 | } 116 | return uri_strs; 117 | } 118 | 119 | // public String getUri_string() { 120 | // return uri_string; 121 | // } 122 | 123 | public String[] getUri_strs() { 124 | return uri_strs; 125 | } 126 | 127 | public void setUri_strs(String[] uriStrs) { 128 | uri_strs = uriStrs; 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /src/com/jzero/util/MCnt.java: -------------------------------------------------------------------------------- 1 | /** 2 | * --- 2011-10-25 --- 3 | * --- Administrator --- 4 | * MyCnt.java : 主要用于生成where语句 5 | */ 6 | package com.jzero.util; 7 | 8 | public final class MCnt { 9 | 10 | private static StringBuffer sb = new StringBuffer(); 11 | private static MCnt cnt=new MCnt(); 12 | public MCnt() { 13 | sb.setLength(0);//清除 14 | } 15 | 16 | public static MCnt me(){ 17 | return cnt; 18 | } 19 | 20 | public void clear() { 21 | sb.delete(0, sb.length()); 22 | } 23 | 24 | /** 25 | * 第一次 拼装成 key=value 或者 key>=value这种格式 AND 26 | */ 27 | public MCnt first(String key, MEnum symbols, Object value) { 28 | if (symbols.getValue().equals("LIKE")) { 29 | value = "%" + value + "%"; 30 | } 31 | sb.append(" ").append(key).append(" ").append(MEnum.get(symbols)) 32 | .append(" '").append(value).append("' "); 33 | return this; 34 | } 35 | public MCnt first_eq(String key,Object value){ 36 | return first(key,MEnum.EQ,value); 37 | } 38 | 39 | public MCnt in(String key,Object value){ 40 | if(sb==null){ 41 | sb = new StringBuffer(); 42 | } 43 | sb.append(" ").append(key).append(" ").append(MEnum.IN).append(" ( ").append(value).append(" )"); 44 | return this; 45 | } 46 | 47 | public MCnt like(String key, Object value) { 48 | sb.append(" AND ").append(key).append(" LIKE '%").append(value).append( 49 | "%' "); 50 | return this; 51 | } 52 | 53 | /** 54 | *除了第一次,在每次的前面加上 and 语句 55 | */ 56 | public MCnt and(String key, MEnum symbols, Object value) { 57 | sb.append(" AND ").append(key).append(" ").append(MEnum.get(symbols)) 58 | .append(" '").append(value).append("' "); 59 | return this; 60 | } 61 | public MCnt and_eq(String key,Object value){ 62 | return and(key, MEnum.EQ, value); 63 | } 64 | 65 | public MCnt or(String key, MEnum symbols, Object value) { 66 | sb.append(" OR ").append(key).append(" ").append(MEnum.get(symbols)) 67 | .append(" '").append(value).append("' "); 68 | return this; 69 | } 70 | /** 71 | * 解析成 select * from xx where 1=1 and x1=x and (x2=x or x3=x) 72 | */ 73 | public MCnt and_in(final MCnt mCnt){ 74 | sb.append(" AND (").append(mCnt.toStr()).append(")"); 75 | return this; 76 | } 77 | public MCnt or_in(final MCnt mCnt){ 78 | sb.append(" OR (").append(mCnt.toStr()).append(" ) "); 79 | return this; 80 | } 81 | public static void main(String[] args) { 82 | String where=MCnt.me().and_eq("1", 1).or_in(MCnt.me().first_eq("one", 1).or_eq("two", 1)).toStr(); 83 | MPrint.print(where); 84 | } 85 | public MCnt or_eq(String key,Object value){ 86 | return or(key, MEnum.EQ, value); 87 | } 88 | 89 | /** 90 | *除了第一次,在每次的前面加上 and 语句 91 | */ 92 | public MCnt set(String key, MEnum symbols, Object value) { 93 | sb.append(" , ").append(key).append(" ").append(MEnum.get(symbols)) 94 | .append(" '").append(value).append("' "); 95 | return this; 96 | } 97 | public MCnt first_set_eq(String key, Object value) { 98 | sb.append(" , ").append(key).append(" ").append(MEnum.EQ).append(value); 99 | return this; 100 | } 101 | /** 102 | * 2011-11-5,用于between 103 | */ 104 | public MCnt between(String key, String begin, String end) { 105 | sb.append(" ").append(key).append(" ").append(MEnum.get(MEnum.BETWEEN)) 106 | .append(" '").append(begin).append("' ").append( 107 | MEnum.get(MEnum.AND)).append(" '").append(end).append( 108 | "' "); 109 | return this; 110 | } 111 | 112 | /** 113 | *2011-11-11 NOT BETWEEN; 114 | */ 115 | public MCnt not_between(String key, String begin, String end) { 116 | sb.append(" ").append(key).append(" ").append(MEnum.get(MEnum.NOT)) 117 | .append(" ").append(MEnum.get(MEnum.BETWEEN)).append(" '") 118 | .append(begin).append("' ").append(MEnum.get(MEnum.AND)) 119 | .append(" '").append(end).append("' "); 120 | return this; 121 | } 122 | 123 | public String toStr() { 124 | String toSb = sb.toString(); 125 | clear(); 126 | return toSb; 127 | } 128 | 129 | @Override 130 | public String toString() { 131 | String toSb = sb.toString(); 132 | clear(); 133 | return toSb; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/com/jzero/util/MEncrypt.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.security.SecureRandom; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.SecretKey; 7 | import javax.crypto.SecretKeyFactory; 8 | import javax.crypto.spec.DESKeySpec; 9 | 10 | /** 11 | * 字符串工具集合 12 | */ 13 | public class MEncrypt { 14 | 15 | private static final String PASSWORD_CRYPT_KEY = "ICPassword"; 16 | private final static String DES = "DES"; 17 | 18 | /** 19 | * 加密 20 | * 21 | * @param src 22 | * 数据源 23 | * @param key 24 | * 密钥,长度必须是8的倍数 25 | * @return 返回加密后的数据 26 | * @throws Exception 27 | */ 28 | private static byte[] encrypt(byte[] src, byte[] key) throws Exception { 29 | // DES算法要求有一个可信任的随机数源 30 | SecureRandom sr = new SecureRandom(); 31 | // 从原始密匙数据创建DESKeySpec对象 32 | DESKeySpec dks = new DESKeySpec(key); 33 | // 创建一个密匙工厂,然后用它把DESKeySpec转换成 34 | // 一个SecretKey对象 35 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); 36 | SecretKey securekey = keyFactory.generateSecret(dks); 37 | // Cipher对象实际完成加密操作 38 | Cipher cipher = Cipher.getInstance(DES); 39 | // 用密匙初始化Cipher对象 40 | cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); 41 | // 现在,获取数据并加密 42 | // 正式执行加密操作 43 | return cipher.doFinal(src); 44 | } 45 | 46 | /** 47 | * 解密 48 | * 49 | * @param src 50 | * 数据源 51 | * @param key 52 | * 密钥,长度必须是8的倍数 53 | * @return 返回解密后的原始数据 54 | * @throws Exception 55 | */ 56 | private static byte[] decrypt(byte[] src, byte[] key) throws Exception { 57 | // DES算法要求有一个可信任的随机数源 58 | SecureRandom sr = new SecureRandom(); 59 | // 从原始密匙数据创建一个DESKeySpec对象 60 | DESKeySpec dks = new DESKeySpec(key); 61 | // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成 62 | // 一个SecretKey对象 63 | SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); 64 | SecretKey securekey = keyFactory.generateSecret(dks); 65 | // Cipher对象实际完成解密操作 66 | Cipher cipher = Cipher.getInstance(DES); 67 | // 用密匙初始化Cipher对象 68 | cipher.init(Cipher.DECRYPT_MODE, securekey, sr); 69 | // 现在,获取数据并解密 70 | // 正式执行解密操作 71 | return cipher.doFinal(src); 72 | } 73 | 74 | /** 75 | * 密码解密 76 | * 77 | * @param data 78 | * @return 79 | * @throws Exception 80 | */ 81 | public final static String decrypt(String data) { 82 | try { 83 | return new String(decrypt(hex2byte(data.getBytes()),PASSWORD_CRYPT_KEY.getBytes())); 84 | } catch (Exception e) { 85 | } 86 | return null; 87 | } 88 | 89 | /** 90 | * 密码加密 91 | * 92 | * @param password 93 | * @return 94 | * @throws Exception 95 | */ 96 | public final static String encrypt(String password) { 97 | try { 98 | String strc = password; 99 | strc = new String(strc.getBytes("GB2312")); 100 | return byte2hex(encrypt(password.getBytes(), PASSWORD_CRYPT_KEY.getBytes())); 101 | // return 102 | // byte2hex(encrypt(strc.getBytes(),PASSWORD_CRYPT_KEY.getBytes())); 103 | } catch (Exception e) { 104 | } 105 | return null; 106 | } 107 | 108 | private static String byte2hex(byte[] b) { 109 | 110 | String hs = ""; 111 | 112 | String stmp = ""; 113 | 114 | for (int n = 0; n < b.length; n++) { 115 | 116 | stmp = (java.lang.Integer.toHexString(b[n] & 0XFF)); 117 | 118 | if (stmp.length() == 1) 119 | 120 | hs = hs + "0" + stmp; 121 | 122 | else 123 | 124 | hs = hs + stmp; 125 | 126 | } 127 | 128 | return hs.toUpperCase(); 129 | 130 | } 131 | 132 | public static byte[] hex2byte(byte[] b) { 133 | 134 | if ((b.length % 2) != 0) 135 | 136 | throw new IllegalArgumentException("长度不是偶数"); 137 | 138 | byte[] b2 = new byte[b.length / 2]; 139 | 140 | for (int n = 0; n < b.length; n += 2) { 141 | 142 | String item = new String(b, n, 2); 143 | 144 | b2[n / 2] = (byte) Integer.parseInt(item, 16); 145 | 146 | } 147 | 148 | return b2; 149 | } 150 | public static void main(String[] args) { 151 | String n1=encrypt("root"); 152 | String n2=encrypt("guilinsoft"); 153 | MPrint.print(n1+","+n2); 154 | MPrint.print(decrypt(null)); 155 | MPrint.print(decrypt(n2)); 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /src/com/jzero/db/utility/MssqlDb.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.utility; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import com.jzero.db.core.M; 7 | import com.jzero.util.MCheck; 8 | import com.jzero.util.MRecord; 9 | import com.jzero.util.MySQL; 10 | 11 | 12 | public final class MssqlDb implements MFieldDb { 13 | private static MFieldDb db=new MssqlDb(); 14 | private MssqlDb(){} 15 | public List getFieldForTable(String tableName) { 16 | return M.me().sql(MySQL.MSSQL_FIELD, tableName); 17 | } 18 | 19 | /** 20 | * 得到数据库中的所有的表 21 | */ 22 | public List getAllTable() { 23 | return M.me().sql(MySQL.MSSQL_TABLE); 24 | } 25 | 26 | /** 27 | * defaultname格式为:display_xxx 28 | * 暂定义可输入项为: display:显示此字段, 29 | * text:文本框 30 | * date:时间 31 | * datetime:时间分秒 32 | * select(怎样传递进来?): 33 | * int:只能录入整数 34 | */ 35 | public List getCommentAndFieldName(String tableName) { 36 | List inlistMap = getFieldForTable(tableName); 37 | List outList = new LinkedList(); 38 | MRecord tempMap = null; 39 | 40 | for (MRecord r : inlistMap) { 41 | String defaultName =r.getStr("defaultname"); 42 | if(checkIsDisplay(defaultName)){ 43 | tempMap = new MRecord(); 44 | tempMap.set("field",r.get("fieldname")); 45 | tempMap.set("comment", r.get("commentname")); 46 | outList.add(tempMap); 47 | } 48 | } 49 | return outList; 50 | } 51 | /** 52 | * 检查默认字段为:display字段,如果字段为display为返回true,如果字段类型为display_xxx,返回true,否则返回false; 53 | */ 54 | private boolean checkIsDisplay(String defaultName){ 55 | if(!MCheck.isNull(defaultName)){//不为空 56 | if ("display".equalsIgnoreCase(defaultName)) {// 只显示display的字段 57 | return true; 58 | } 59 | String objs[]=defaultName.split("_");//eg:display_xx_dd 60 | if(objs.length>0){ 61 | if(objs[0].equals(defaultName)){ 62 | return true; 63 | } 64 | } 65 | } 66 | return false; 67 | } 68 | public List getDefaultAndFieldName(String tableName) { 69 | List inlistMap = getFieldForTable(tableName); 70 | List outList = new LinkedList(); 71 | MRecord tempMap = null; 72 | 73 | for (MRecord r : inlistMap) { 74 | String comment = r.getStr("commentname"); 75 | if (!MCheck.isNull(comment)) {// 过滤掉没有注释的字段 76 | tempMap = new MRecord(); 77 | tempMap.set("field", r.get("fieldname")); 78 | tempMap.set("comment", comment); 79 | outList.add(tempMap); 80 | } 81 | } 82 | return outList; 83 | } 84 | 85 | public List getSelectField(String tableName) { 86 | List inlistMap = getFieldForTable(tableName); 87 | List outList = new LinkedList(); 88 | MRecord tempMap = null; 89 | 90 | for (MRecord r : inlistMap) { 91 | String defaultName =r.get("defaultname"); 92 | if(checkIsDisplay(defaultName)){ 93 | tempMap=getTypeAndLenthByDefault(defaultName,r.get("length")); 94 | outList.add(tempMap); 95 | } 96 | } 97 | return outList; 98 | } 99 | //返回 类型与长度,格式:display_xx 100 | private MRecord getTypeAndLenthByDefault(String defaultName,Object length) { 101 | MRecord tempMap = new MRecord(); 102 | String objs[]=defaultName.split("_"); 103 | if(objs.length>1){ 104 | tempMap.set("type", objs[1]); 105 | } 106 | tempMap.set("length",length); 107 | return tempMap; 108 | 109 | } 110 | public static MFieldDb getIns() { 111 | return db; 112 | } 113 | /** 114 | *返回分页界面 current:当前第几页 pageSize:每页显示的数量,MSSQL暂时还未测试 115 | */ 116 | public String get_pager_sql(String table, String where,String field,int current, int pageSize, Object... obj) { 117 | StringBuffer sql_bf = new StringBuffer("SELECT TOP ").append(pageSize).append(" * FROM ").append(table) 118 | .append(" WHERE id NOT IN (SELECT TOP ").append(current*pageSize).append(" id FROM ").append(table) 119 | .append(" ORDER BY ID DESC )"); 120 | if (!MCheck.isNull(where)) { // 不为空,则有where 语句 121 | sql_bf.append(" AND ").append(where); 122 | } 123 | if (MCheck.isNull(obj)) { 124 | sql_bf.append(" order by id desc"); 125 | } else { 126 | sql_bf.append(" ").append(obj); 127 | } 128 | return sql_bf.toString(); 129 | } 130 | 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/com/jzero/token/MToken.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.token; 3 | 4 | import com.jzero.core.MInit; 5 | import com.jzero.log.Log; 6 | import com.jzero.util.MCheck; 7 | import com.jzero.util.MCookie; 8 | import com.jzero.util.MDate; 9 | import com.jzero.util.MEncrypt; 10 | import com.jzero.util.MPro; 11 | 12 | /** 13 | * 2012-10-6:防止从别的页面提交,参考于CI->Security.php 14 | * wangujqw@gmail.com 15 | */ 16 | public class MToken { 17 | 18 | public static MToken me(){ return MInit.get().getToken();} 19 | 20 | private String csrf_hash; //加密后的值 21 | private int csrf_expire; //存活时间(秒) 22 | private String csrf_toke_name="jzero_csrf_token"; //保存的名称 23 | private String csrf_cookie_name="jzero_csrf_token"; //保存在cookie中的名称 24 | private boolean protection; 25 | private boolean verify; 26 | 27 | 28 | public static MToken init(MInit minit){ 29 | MToken token=new MToken(); 30 | token.setCsrf_cookie_name(minit.getConfig().getStr("csrf_cookie_name")); 31 | token.setCsrf_toke_name(minit.getConfig().getStr("csrf_token_name")); 32 | token.setCsrf_expire(minit.getConfig().getInt("csrf_expire")); 33 | token.setProtection(minit.getConfig().getBool("csrf_protection")); 34 | token.setVerify(false); 35 | return token; 36 | } 37 | //验证 38 | public void csrf_verify(){ 39 | if(!isVerify()){ 40 | // Do the tokens exist in both the _POST and _COOKIE arrays? 41 | String token_name=MInit.get().getMr().getPara(getCsrf_toke_name()); 42 | String cookie_name=MCookie.me().getCookie(getCsrf_cookie_name()); 43 | if(MCheck.isNull(token_name)||MCheck.isNull(cookie_name)){ 44 | csrf_show_error(); 45 | } 46 | else if(!token_name.equals(cookie_name)){ 47 | csrf_show_error(); 48 | }else{ 49 | MCookie.me().removeCookie(getCsrf_cookie_name()); 50 | setCsrf_hash(null); 51 | csrf_set_hash(); 52 | setVerify(true); 53 | } 54 | } 55 | } 56 | public void csrf_verify(Object object){ 57 | if(!isVerify()){ 58 | // Do the tokens exist in both the _POST and _COOKIE arrays? 59 | String cookie_name=MCookie.me().getCookie(getCsrf_cookie_name()); 60 | if(MCheck.isNull(object)||MCheck.isNull(cookie_name)){ 61 | csrf_show_error(); 62 | } 63 | if(!object.equals(cookie_name)){ 64 | csrf_show_error(); 65 | } 66 | MCookie.me().removeCookie(getCsrf_cookie_name()); 67 | setCsrf_hash(null); 68 | csrf_set_hash(); 69 | setVerify(true); 70 | } 71 | } 72 | private void csrf_show_error(){ 73 | MInit.get().getMb().getTextRender("The action you have requested is not allowed.").render(); 74 | } 75 | public String csrf_set_hash(){ 76 | String csrf_hash=getCsrf_hash(); 77 | if(MCheck.isNull(csrf_hash)){ 78 | //从cookie中取,判断是否为空 79 | csrf_hash=MCookie.me().getCookie(getCsrf_cookie_name()); 80 | if(MCheck.isNull(csrf_hash)){ 81 | csrf_hash=MEncrypt.encrypt(MDate.get_ymd_hms()); 82 | }else{ 83 | setCsrf_hash(csrf_hash); 84 | } 85 | csrf_set_cookie(csrf_hash); 86 | } 87 | 88 | return csrf_hash; 89 | } 90 | public MToken csrf_set_cookie(String hash){ 91 | int expire=MDate.get_now_second()+getCsrf_expire(); 92 | MCookie.me().setCookie(getCsrf_cookie_name(), hash,expire,MPro.me().getStr("cookie_path")); 93 | Log.me().write_debug("CRSF cookie set"); 94 | return this; 95 | } 96 | 97 | 98 | public String getCsrf_hash() { 99 | return csrf_hash; 100 | } 101 | 102 | 103 | public void setCsrf_hash(String csrfHash) { 104 | csrf_hash = csrfHash; 105 | } 106 | 107 | public int getCsrf_expire() { 108 | return csrf_expire; 109 | } 110 | 111 | public void setCsrf_expire(int csrfExpire) { 112 | csrf_expire = csrfExpire; 113 | } 114 | 115 | public String getCsrf_toke_name() { 116 | return csrf_toke_name; 117 | } 118 | 119 | public void setCsrf_toke_name(String csrfTokeName) { 120 | csrf_toke_name = csrfTokeName; 121 | } 122 | 123 | public String getCsrf_cookie_name() { 124 | return csrf_cookie_name; 125 | } 126 | 127 | public void setCsrf_cookie_name(String csrfCookieName) { 128 | csrf_cookie_name = csrfCookieName; 129 | } 130 | 131 | public boolean isProtection() { 132 | return protection; 133 | } 134 | 135 | public void setProtection(boolean protection) { 136 | this.protection = protection; 137 | } 138 | public boolean isVerify() { 139 | return verify; 140 | } 141 | public void setVerify(boolean verify) { 142 | this.verify = verify; 143 | } 144 | 145 | 146 | 147 | } 148 | -------------------------------------------------------------------------------- /src/com/jzero/util/MDate.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.TimeZone; 8 | 9 | import com.jzero.log.Log; 10 | import com.jzero.log.LogEnum; 11 | 12 | /** 2012-10-3 */ 13 | public class MDate { 14 | 15 | public static SimpleDateFormat getSimpleDateFormat(String pattStr) { 16 | SimpleDateFormat sdf = new SimpleDateFormat(pattStr); 17 | sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); 18 | return sdf; 19 | } 20 | 21 | public static String get_ymd_hms() { 22 | return getSimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(newDate()); 23 | } 24 | public static String get_ymd_hms_join() { 25 | return getSimpleDateFormat("yyyyMMddHHmmss").format(newDate()); 26 | } 27 | public static String get_ymd() { 28 | return getSimpleDateFormat("yyyy-MM-dd").format(newDate()); 29 | } 30 | 31 | public static String get_year() { 32 | return getSimpleDateFormat("yyyy").format(newDate()); 33 | } 34 | 35 | public static String get_month() { 36 | return getSimpleDateFormat("MM").format(newDate()); 37 | } 38 | 39 | public static String get_day() { 40 | return getSimpleDateFormat("dd").format(newDate()); 41 | } 42 | 43 | public static String get_ymd_hm() { 44 | return getSimpleDateFormat("yyyy-MM-dd HH:mm").format(newDate()); 45 | } 46 | 47 | public static String get_after_minute(int minute) { 48 | SimpleDateFormat sdf = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 49 | Calendar afterTime = Calendar.getInstance(); 50 | afterTime.add(12, minute); 51 | afterTime.set(13, 0); 52 | return sdf.format(afterTime.getTime()); 53 | } 54 | 55 | // 当前系统前10分钟 56 | public static Date get_pre_Ten_min() { 57 | Calendar cal = Calendar.getInstance(); 58 | cal.add(Calendar.SECOND, Calendar.SECOND - 10); 59 | return cal.getTime(); 60 | } 61 | 62 | // 指定多少分钟后的时间 63 | public static Date get_after_minute_date(int minute) { 64 | Calendar afterTime = Calendar.getInstance(); 65 | afterTime.add(Calendar.MINUTE, minute); 66 | return afterTime.getTime(); 67 | } 68 | 69 | // 指定多少毫秒后的时间 70 | public static Date get_after_milliscond(int scond) { 71 | Calendar afterTime = Calendar.getInstance(); 72 | afterTime.add(Calendar.MILLISECOND, scond); 73 | return afterTime.getTime(); 74 | } 75 | 76 | public static String get_ym() { 77 | return getSimpleDateFormat("yyyy-MM").format(newDate()); 78 | } 79 | 80 | public static java.util.Date newDate() { 81 | return new java.util.Date(); 82 | } 83 | 84 | public static java.util.Date toYMD(String str) { 85 | try { 86 | return getSimpleDateFormat("yyyy-MM-dd").parse(str); 87 | } catch (ParseException e) { 88 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 89 | } 90 | return newDate(); 91 | } 92 | 93 | public static java.util.Date toYMD_HMS(String str) { 94 | try { 95 | return getSimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str); 96 | } catch (ParseException e) { 97 | Log.me().write_log(LogEnum.ERROR, e.getMessage()); 98 | } 99 | return newDate(); 100 | } 101 | 102 | public static String get_max_day(Object time) { 103 | if (!(MCheck.isNull(time))) { 104 | String[] str = time.toString().split("-"); 105 | if (str.length != 2) { 106 | return time.toString(); 107 | } 108 | Calendar cal = Calendar.getInstance(); 109 | cal.set(1, Integer.parseInt(str[0])); 110 | cal.set(2, Integer.parseInt(str[1]) - 1); 111 | int maxDate = cal.getActualMaximum(5); 112 | return time + "-" + maxDate; 113 | } 114 | return ""; 115 | } 116 | 117 | public static Object get_min_day(Object time) { 118 | if (!(MCheck.isNull(time))) { 119 | String[] str = time.toString().split("-"); 120 | if (str.length != 2) { 121 | return time; 122 | } 123 | return time + "-" + "01"; 124 | } 125 | return ""; 126 | } 127 | 128 | public static Object get_min_day() { 129 | return get_min_day(get_ym()); 130 | } 131 | 132 | public static String get_max_day() { 133 | return get_max_day(get_ym()); 134 | } 135 | 136 | public static String[] split_ym(Object time) { 137 | return MCheck.isNull(time)?null:time.toString().split("-"); 138 | } 139 | public static int get_now_second(){ 140 | return (int) (System.currentTimeMillis()/1000L); 141 | } 142 | public static void main(String[] args) { 143 | MPrint.print(System.currentTimeMillis()/1000L); 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /src/com/jzero/util/MCookie.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.util; 3 | 4 | import javax.servlet.http.Cookie; 5 | 6 | import com.jzero.core.MInit; 7 | 8 | /** 2012-10-3 */ 9 | public class MCookie { 10 | 11 | private static MCookie cookie=new MCookie(); 12 | 13 | private MCookie(){} 14 | public static MCookie me(){ 15 | return cookie; 16 | } 17 | /** 18 | * Get cookie value by cookie name. 19 | */ 20 | public String getCookie(String name, String defaultValue) { 21 | Cookie cookie = getCookieObject(name); 22 | return cookie != null ? cookie.getValue() : defaultValue; 23 | } 24 | 25 | /** 26 | * Get cookie value by cookie name. 27 | */ 28 | public String getCookie(String name) { 29 | return getCookie(name, null); 30 | } 31 | 32 | /** 33 | * Get cookie value by cookie name and convert to Integer. 34 | */ 35 | public Integer getCookieToInt(String name) { 36 | String result = getCookie(name); 37 | return result != null ? Integer.parseInt(result) : null; 38 | } 39 | 40 | /** 41 | * Get cookie value by cookie name and convert to Integer. 42 | */ 43 | public Integer getCookieToInt(String name, Integer defaultValue) { 44 | String result = getCookie(name); 45 | return result != null ? Integer.parseInt(result) : defaultValue; 46 | } 47 | 48 | /** 49 | * Get cookie value by cookie name and convert to Long. 50 | */ 51 | public Long getCookieToLong(String name) { 52 | String result = getCookie(name); 53 | return result != null ? Long.parseLong(result) : null; 54 | } 55 | 56 | /** 57 | * Get cookie value by cookie name and convert to Long. 58 | */ 59 | public Long getCookieToLong(String name, Long defaultValue) { 60 | String result = getCookie(name); 61 | return result != null ? Long.parseLong(result) : defaultValue; 62 | } 63 | 64 | /** 65 | * Get cookie object by cookie name. 66 | */ 67 | public Cookie getCookieObject(String name) { 68 | Cookie[] cookies = MInit.get().getCookie(); 69 | if (cookies != null) 70 | for (Cookie cookie : cookies) 71 | if (cookie.getName().equals(name)) 72 | return cookie; 73 | return null; 74 | } 75 | 76 | /** 77 | * Get all cookie objects. 78 | */ 79 | public Cookie[] getCookieObjects() { 80 | Cookie[] result = MInit.get().getCookie(); 81 | return result != null ? result : new Cookie[0]; 82 | } 83 | 84 | /** 85 | * Set Cookie to response. 86 | */ 87 | public MCookie setCookie(Cookie cookie) { 88 | MInit.get().response().addCookie(cookie); 89 | return this; 90 | } 91 | 92 | /** 93 | * Set Cookie to response. 94 | * @param name cookie name 95 | * @param value cookie value 96 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 97 | * @param path see Cookie.setPath(String) 98 | */ 99 | public MCookie setCookie(String name, String value, int maxAgeInSeconds, String path) { 100 | setCookie(name, value, maxAgeInSeconds, path, null); 101 | return this; 102 | } 103 | 104 | /** 105 | * Set Cookie to response. 106 | * @param name cookie name 107 | * @param value cookie value 108 | * @param maxAgeInSeconds -1: clear cookie when close browser. 0: clear cookie immediately. n>0 : max age in n seconds. 109 | * @param path see Cookie.setPath(String) 110 | * @param domain the domain name within which this cookie is visible; form is according to RFC 2109 111 | */ 112 | public MCookie setCookie(String name, String value, int maxAgeInSeconds, String path, String domain) { 113 | Cookie cookie = new Cookie(name, value); 114 | if (!MCheck.isNull(domain)) 115 | cookie.setDomain(domain); 116 | cookie.setMaxAge(maxAgeInSeconds); 117 | cookie.setPath(path); 118 | MInit.get().response().addCookie(cookie); 119 | return this; 120 | } 121 | 122 | /** 123 | * Set Cookie with path = "/". 124 | */ 125 | public MCookie setCookie(String name, String value, int maxAgeInSeconds) { 126 | setCookie(name, value, maxAgeInSeconds, "/", null); 127 | return this; 128 | } 129 | 130 | /** 131 | * Remove Cookie with path = "/". 132 | */ 133 | public MCookie removeCookie(String name) { 134 | setCookie(name, null, 0, "/", null); 135 | return this; 136 | } 137 | 138 | /** 139 | * Remove Cookie. 140 | */ 141 | public MCookie removeCookie(String name, String path) { 142 | setCookie(name, null, 0, path, null); 143 | return this; 144 | } 145 | 146 | /** 147 | * Remove Cookie. 148 | */ 149 | public MCookie removeCookie(String name, String path, String domain) { 150 | setCookie(name, null, 0, path, domain); 151 | return this; 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/com/jzero/db/core/CSqlite.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.core; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.sql.Statement; 8 | import java.util.List; 9 | 10 | import com.jzero.core.MReport; 11 | import com.jzero.db.cache.MCache; 12 | import com.jzero.db.utility.MSqlite; 13 | import com.jzero.util.MCheck; 14 | import com.jzero.util.MRecord; 15 | import com.jzero.util.MSee; 16 | import com.jzero.util.MSee.IAtom; 17 | 18 | public class CSqlite extends CBase { 19 | 20 | @Override 21 | public List pager(String table, String where, String field, 22 | int current, int pageSize, Object... params) { 23 | final String sql = MSqlite.getIns().get_pager_sql(table, where,field, current,pageSize, params); 24 | List data = null; 25 | if (MCache.me().isEnabled()) { 26 | data = MCache.me().read(sql); 27 | } 28 | if(MCheck.isNull(data)){ 29 | data=select(sql); 30 | }else { 31 | MSee.ok_sql(new IAtom() { 32 | public void run() throws Exception { 33 | MReport.doFileReport(sql); 34 | } 35 | }, is_dev()); 36 | } 37 | return data; 38 | } 39 | /** 40 | * 2013-3-15:根mysql一致,因为他们的分页都为limit操作 41 | */ 42 | @Override 43 | public List pager_sql(String sql, int current, int pageSize, 44 | Object... params) { 45 | final StringBuffer sql_bf = new StringBuffer(sql); 46 | sql_bf.append(" LIMIT ").append(current).append(" , ").append(pageSize); 47 | List data = null; 48 | if (MCache.me().isEnabled()) { 49 | data = MCache.me().read(sql_bf.toString()); 50 | } 51 | if(MCheck.isNull(data)){ 52 | data=select(sql_bf.toString()); 53 | }else { 54 | MSee.ok_sql(new IAtom() { 55 | public void run() throws Exception { 56 | MReport.doFileReport(sql_bf.toString()); 57 | } 58 | }, is_dev()); 59 | } 60 | return data; 61 | } 62 | /** 63 | * 2013-3-15:根mysql一致,因为他们的分页都为limit操作 64 | */ 65 | @Override 66 | public MRecord select_one(String table, String where, String field, 67 | boolean cache, Object... params) { 68 | final StringBuffer sql_bf = new StringBuffer("SELECT "); 69 | if ("*".equals(field) || MCheck.isNull(field)) {sql_bf.append(" * "); 70 | } else {sql_bf.append(field);} 71 | sql_bf.append(" FROM ").append(table); 72 | if (!MCheck.isNull(where)) { // 不为空,则有where 语句 73 | sql_bf.append(" WHERE 1=1 ").append(where); 74 | } 75 | if (!MCheck.isNull(params)) { 76 | sql_bf.append(" ").append(params[0]); 77 | } 78 | sql_bf.append(" limit 1"); 79 | if(cache){ 80 | List data = null; 81 | if (MCache.me().isEnabled()) { 82 | data = MCache.me().read(sql_bf.toString()); 83 | } 84 | if(MCheck.isNull(data)){ 85 | data=select(sql_bf.toString()); 86 | }else { 87 | MSee.ok_sql(new IAtom() { 88 | public void run() throws Exception { 89 | MReport.doFileReport(sql_bf.toString()); 90 | } 91 | }, is_dev()); 92 | } 93 | 94 | return MCheck.isNull(data)?null:data.get(0); 95 | }else{ 96 | List data = select(sql_bf.toString()); 97 | return MCheck.isNull(data)?null:data.get(0); 98 | } 99 | } 100 | public static void main(String[] args) { 101 | Connection connection = null; 102 | try{ 103 | Class.forName("org.sqlite.JDBC"); 104 | connection = DriverManager.getConnection("jdbc:sqlite:sample.db"); 105 | Statement statement = connection.createStatement(); 106 | statement.setQueryTimeout(30); // set timeout to 30 sec. 107 | statement.executeUpdate("drop table if exists person"); 108 | statement.executeUpdate("create table person (id integer, name string)"); 109 | statement.executeUpdate("insert into person values(1, 'leo')"); 110 | statement.executeUpdate("insert into person values(2, 'yui')"); 111 | statement.executeUpdate("backup to backup.db"); 112 | ResultSet rs = statement.executeQuery("select * from person"); 113 | while(rs.next()){ 114 | // read the result set 115 | System.out.println("name = " + rs.getString("name")); 116 | System.out.println("id = " + rs.getInt("id")); 117 | } 118 | }catch(Exception e){ 119 | System.err.println(e.getMessage()); 120 | } 121 | finally{ 122 | try{ 123 | if(connection != null) 124 | connection.close(); 125 | }catch(SQLException e){ 126 | System.err.println(e); 127 | } 128 | } 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /src/com/jzero/db/cache/MCache.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.db.cache; 3 | 4 | import java.io.File; 5 | import java.util.List; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | 9 | import com.jzero.core.MInit; 10 | import com.jzero.core.MURI; 11 | import com.jzero.log.Log; 12 | import com.jzero.util.MCheck; 13 | import com.jzero.util.MMD5; 14 | import com.jzero.util.MPath; 15 | import com.jzero.util.MPrint; 16 | import com.jzero.util.MPro; 17 | import com.jzero.util.MRecord; 18 | 19 | /** 20 | * 2012-10-3 ,参照CI,将查询出来的结果缓存到文件目录下 21 | */ 22 | public class MCache implements ICache{ 23 | private boolean enabled; 24 | private static MCache cache=new MCache(); 25 | private static boolean isload=false; 26 | private MCache(){} 27 | 28 | public static MCache me(){ 29 | return cache; 30 | } 31 | public void init(){ 32 | setEnabled(MPro.me().getBool("cache_on")); 33 | isload=true; 34 | } 35 | public File get_path(String sql) { 36 | File file=null; 37 | if(!isload){init();} 38 | if(isEnabled()){//开启了缓存,现在创建目录 39 | String filename=get_file_name(sql); 40 | /** 41 | * 当客户端发送Socket连接服务器,需要返回数据时,使用MInit.get()取不到数据,则直接保存到一个文件中 42 | */ 43 | String cache_file = MPath.me().getSrcPath() + "/cache"; 44 | MInit init=MInit.get(); 45 | if(MCheck.isNull(init)){//终端发送指令 46 | file=MFile.createFile(cache_file+"/"+"socket",filename);//File.separator 47 | }else{ 48 | MURI uri=MInit.get().getURI(); 49 | String controler=MCheck.isNull(uri)?MInit.get().getRouter().getDefault_controller():uri.seg_str(0); 50 | controler=MCheck.isNull(controler)?MInit.get().getRouter().getDefault_controller():controler; 51 | file=MFile.createFile(cache_file+"/"+controler.toLowerCase(),filename);//File.separator 52 | } 53 | } 54 | return file; 55 | } 56 | public void write(String sql, List lst) { 57 | File file=get_path(sql); 58 | if(!MCheck.isNull(file)){//不为空,则写入 59 | WriteThread thread=new WriteThread(file, lst); 60 | try { 61 | pool.submit(thread).get(); 62 | } catch (Exception e) { 63 | MPrint.print(" Write file Error "); 64 | Log.me().write_error(e); 65 | } 66 | } 67 | } 68 | private class WriteThread extends Thread{ 69 | private final File file; 70 | private final List lst; 71 | public WriteThread(File file,List lst){ 72 | this.file=file; 73 | this.lst=lst; 74 | } 75 | @Override 76 | public void run() { 77 | MFile.write(file, lst); 78 | } 79 | 80 | } 81 | 82 | public void delete(String sql) { 83 | File file=get_path(sql); 84 | if(!MCheck.isNull(file)){ 85 | file.delete(); 86 | } 87 | } 88 | private String get_file_name(String sql){ 89 | String file_name=MMD5.toMD5(sql);//MEncrypt.encrypt(sql); 90 | return file_name.length()>258?file_name.substring(0,258):file_name; //2012-10-11,当长度为288时,createFile时就会抛出异常:文件名、目录名或卷标语法不正确 91 | } 92 | private static ExecutorService pool=Executors.newCachedThreadPool(); 93 | public void delete_all() { 94 | String controler=MInit.get().getURI().seg_str(0); 95 | String cache_file = MPath.me().getWebRoot() + "cache"; 96 | controler=MCheck.isNull(controler)?MInit.get().getRouter().getDefault_controller():controler; 97 | String path=cache_file+"/"+controler;//File.separator 98 | DelThread thread=new DelThread(path); 99 | try { 100 | pool.submit(thread).get(); 101 | } catch (Exception e) { 102 | Log.me().write_error(e); 103 | } 104 | } 105 | public void deleta_all_cache(){ 106 | String path = MPath.me().getWebRoot() + "cache"; 107 | DelThread thread=new DelThread(path); 108 | try { 109 | pool.submit(thread).get(); 110 | } catch (Exception e) { 111 | Log.me().write_error(e); 112 | } 113 | } 114 | private class DelThread extends Thread{ 115 | private final String del_path; 116 | public DelThread(String path){ 117 | this.del_path=path; 118 | } 119 | @Override 120 | public void run() { 121 | delete_file(del_path); 122 | } 123 | } 124 | public void delete_file(String file_path){ 125 | File file=new File(file_path); 126 | if(file.exists()){ 127 | File[] files=file.listFiles(); 128 | for(File f:files){ 129 | if(f.isDirectory()){ 130 | delete_file(f.getAbsolutePath()); 131 | }else{ 132 | boolean bool=f.delete(); 133 | MPrint.print("["+bool+"]clear cache file : "+f.getName()); 134 | } 135 | } 136 | } 137 | } 138 | public List read(String sql) { 139 | File file=get_path(sql); 140 | return MFile.read(file); 141 | } 142 | 143 | 144 | public boolean isEnabled() { 145 | init(); 146 | return enabled; 147 | } 148 | public void setEnabled(boolean enabled) { 149 | this.enabled = enabled; 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/com/jzero/log/Log.java: -------------------------------------------------------------------------------- 1 | package com.jzero.log; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.PrintWriter; 7 | import java.io.StringWriter; 8 | 9 | import com.jzero.db.cache.MFile; 10 | import com.jzero.util.MCheck; 11 | import com.jzero.util.MDate; 12 | import com.jzero.util.MPath; 13 | import com.jzero.util.MPro; 14 | import com.jzero.util.Msg; 15 | 16 | public final class Log { 17 | 18 | private boolean enabled; 19 | private String level; 20 | private static BufferedWriter write = null; 21 | private static Log log = new Log(); 22 | private static StringBuffer sb = new StringBuffer(); 23 | private static boolean is_load = false; 24 | private boolean reload;// 如果为true,则每次都加载 25 | 26 | private Log() { 27 | } 28 | 29 | public static Log me() { 30 | return log; 31 | } 32 | 33 | public void init() { 34 | MPro pro = MPro.me().load_file(Msg.CONFIG); 35 | setEnabled(pro.getBool("log_enabled")); 36 | setLevel(pro.getStr("log_level")); 37 | setReload(pro.getBool("log_reload")); 38 | if (isReload()) { 39 | is_load = false; 40 | } else { 41 | is_load = true; 42 | } 43 | } 44 | 45 | 46 | private void clear(StringBuffer ss) { 47 | if(!MCheck.isNull(ss)){ 48 | ss.delete(0, ss.length()); 49 | } 50 | } 51 | public void write_log(LogEnum level, Exception e) { 52 | write_log(level, e.getMessage()); 53 | } 54 | 55 | public void write_error(Exception e) { 56 | clear(sb); 57 | StringWriter trace = new StringWriter(); 58 | e.printStackTrace(new PrintWriter(trace)); 59 | write_log(LogEnum.ERROR,trace.toString()); 60 | // StackTraceElement[] elements= e.fillInStackTrace().getStackTrace(); 61 | // for(StackTraceElement row:elements){ 62 | // if(!MCheck.isNull(row.getFileName())){ 63 | // if(row.getFileName().equals(getClass().getSimpleName()+".java")){ 64 | // continue; 65 | // } 66 | // sb.append("\n ERROR INFO : "+e) 67 | // .append("\t").append(" =>").append(row.getFileName()).append(".").append(row.getClassName()).append(".").append(row.getLineNumber()); 68 | // } 69 | // } 70 | // write_log(LogEnum.ERROR,sb.toString()); 71 | } 72 | 73 | public void write_debug(String msg) { 74 | write_log(LogEnum.DEBUG, msg); 75 | } 76 | 77 | public void write_info(String msg) { 78 | write_log(LogEnum.INFO, msg); 79 | } 80 | /** 81 | * 直接写入日记文件 82 | */ 83 | public void write(String msg){ 84 | String log_file = MPath.me().getWebInfPath() + "log"; 85 | String log_file_name = MDate.get_ymd() + ".txt"; 86 | File file = MFile.createFile(log_file, log_file_name); 87 | try { 88 | write = MFile.getWriter(file, true); 89 | write.append(MDate.get_ymd_hms() + ": "+ msg + "\n"); 90 | } catch (IOException e) { 91 | try { 92 | write.append(MDate.get_ymd_hms() + ": "+ e.getMessage() + "\n"); 93 | } catch (IOException e1) { 94 | } 95 | } finally { 96 | try { 97 | write.flush(); 98 | write.close(); 99 | } catch (IOException e) { 100 | try { 101 | write.append(MDate.get_ymd_hms() + "『" + level+ "』: " + e.getMessage() + "\n"); 102 | } catch (IOException e1) { 103 | } 104 | } 105 | } 106 | } 107 | public void write_log(LogEnum level, String msg) { 108 | if (!is_load) { 109 | init(); 110 | } 111 | // 如果开启了,则写入文件 112 | if (isEnabled()) { 113 | boolean bool = bool_log(level); 114 | if (bool) { 115 | String log_file = MPath.me().getWebInfPath() + "log"; 116 | String log_file_name = MDate.get_ymd() + ".txt"; 117 | File file = MFile.createFile(log_file, log_file_name); 118 | try { 119 | write = MFile.getWriter(file, true); 120 | write.append(MDate.get_ymd_hms() + "[" + level + "]: " 121 | + msg + "\n"); 122 | } catch (IOException e) { 123 | try { 124 | write.append(MDate.get_ymd_hms() + "『" + level + "』: " 125 | + e.getMessage() + "\n"); 126 | } catch (IOException e1) { 127 | } 128 | } finally { 129 | try { 130 | write.flush(); 131 | write.close(); 132 | } catch (IOException e) { 133 | try { 134 | write.append(MDate.get_ymd_hms() + "『" + level 135 | + "』: " + e.getMessage() + "\n"); 136 | } catch (IOException e1) { 137 | } 138 | } 139 | 140 | } 141 | } 142 | 143 | } 144 | } 145 | 146 | /** 147 | * 1、如果日记级别为空或者NONE,则不记录内容 2、如果日记的内容与配置文件内容一致时写入日记 3、如果是ALL,则全部显示 148 | */ 149 | private boolean bool_log(LogEnum level) { 150 | return getLevel().equals(LogEnum.ALL.toString()) ? true : MCheck 151 | .isNull(getLevel()) 152 | || getLevel().equals(LogEnum.NONE) ? false : level.toString() 153 | .equals(getLevel()) ? true : false; 154 | } 155 | 156 | public boolean isEnabled() { 157 | return enabled; 158 | } 159 | 160 | public String getLevel() { 161 | return level; 162 | } 163 | 164 | public void setLevel(String level) { 165 | this.level = level; 166 | } 167 | 168 | public void setEnabled(boolean enabled) { 169 | this.enabled = enabled; 170 | } 171 | 172 | public boolean isReload() { 173 | return reload; 174 | } 175 | 176 | public void setReload(boolean reload) { 177 | this.reload = reload; 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/com/jzero/filter/JFilter.java: -------------------------------------------------------------------------------- 1 | package com.jzero.filter; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.Arrays; 6 | import java.util.List; 7 | 8 | import javax.servlet.Filter; 9 | import javax.servlet.FilterChain; 10 | import javax.servlet.FilterConfig; 11 | import javax.servlet.ServletException; 12 | import javax.servlet.ServletRequest; 13 | import javax.servlet.ServletResponse; 14 | import javax.servlet.http.HttpServletRequest; 15 | import javax.servlet.http.HttpServletResponse; 16 | 17 | import com.jzero.core.MInit; 18 | import com.jzero.core.MR; 19 | import com.jzero.core.MRouter; 20 | import com.jzero.log.Log; 21 | import com.jzero.render.MB; 22 | import com.jzero.render.MRender; 23 | import com.jzero.util.MCheck; 24 | import com.jzero.util.MPrint; 25 | import com.jzero.util.MTool; 26 | 27 | public class JFilter implements Filter{ 28 | // private String cachetime; 29 | public void init(FilterConfig filter) throws ServletException { 30 | // this.cachetime = filter.getInitParameter("cache"); 31 | } 32 | 33 | public void doFilter(ServletRequest req, ServletResponse resq, 34 | FilterChain chain) throws IOException, ServletException { 35 | HttpServletRequest request = (HttpServletRequest) req; 36 | HttpServletResponse response = (HttpServletResponse) resq; 37 | resq.setContentType("text/html;charset=utf-8"); 38 | req.setCharacterEncoding("UTF-8"); 39 | resq.setCharacterEncoding("utf-8"); 40 | MInit init=MInit.begin(request, response); 41 | String target=init.uri(); 42 | boolean[] isHandled = { false };// 为什么用数组呢?因为如果用boolean,则不能返回值,如果用数据,则可以返回数组的值 43 | try { 44 | handle(request, response, target, isHandled); 45 | } catch (Exception e) { 46 | Log.me().write_error(e); 47 | MB.me().getJspRender(MRouter.me().getDefault_view()); 48 | // init.getMb().getError500Render().setContext(request, response).render(); 49 | }finally{ 50 | if (isHandled[0] == false){ 51 | if(target.lastIndexOf(".")!=-1){ 52 | String extension =target.substring(target.lastIndexOf("."));//判断后辍名 53 | if(extension.equals(".asp")||extension.equals(".php")){ 54 | if(target.contains("upload_json.jsp")){//kinditor上传时使用到 2012-11-21 extension.equals(".jsp")|| 55 | chain.doFilter(request, response); 56 | }else{ 57 | MPrint.print("试图运行>>"+target+",遭到拒绝.!"); 58 | } 59 | }else{ 60 | if(cache_path.contains(target)){ 61 | response.setHeader("Cache-Control","max-age="+3600); //HTTP 1.1 62 | }else{ 63 | response.setHeader("Cache-Control","no-cache"); 64 | response.setHeader("Pragma","no-cache"); //HTTP 1.0 65 | response.setDateHeader ("Expires", 0 ); 66 | } 67 | chain.doFilter(request, response); 68 | } 69 | } 70 | } 71 | if(!MCheck.isNull(init)){ 72 | init.end(); 73 | } 74 | } 75 | 76 | } 77 | //放行的后辍名 78 | private final static String[] static_ext ={ 79 | "csv","js","css","jpg","png","gif",".html","ico","swf","mp4","com","doc","xls","pdf","ppt","gz","gtar","rar","tar","tgz","zip","mp3","jpeg","jpe","tif","html","txt","jsp","rm","rmvb","flv","mpeg","mov","mtv","avi","3gp","amv","dmv" 80 | }; 81 | //放行的包名 82 | private final static String[] static_packer={ 83 | "upload","js","css","images","swf","other" 84 | }; 85 | private static List allow=Arrays.asList(static_ext); 86 | private static List allow_packer=Arrays.asList(static_packer); 87 | 88 | private static List cache_path=new ArrayList(500); 89 | private boolean checkCachePath(String target){ 90 | return cache_path.contains(target)?true:false; 91 | } 92 | public final void handle(HttpServletRequest request, 93 | HttpServletResponse response, String target, boolean[] isHandled){ 94 | if(checkCachePath(target)){//如果缓存中已经包含,则直接调用 95 | return; 96 | }else{ 97 | if (target.indexOf(".") != -1) {// 如果包含有.的一律放行,像.js,.css,.jpg// 2012-10-8,来源于JFinal 98 | String extension =target.substring(target.lastIndexOf(".")+1);//判断后辍名 99 | if(allow.contains(extension)||extension.contains("com")){//如果包含指定的项目,是放行,eg http://glchy.gotoip1.com/ 100 | cache_path.add(target); 101 | return ; 102 | } 103 | } 104 | String projectName=MR.me().getProject(); 105 | String target_path=MCheck.isNull(projectName)?target:target.replaceFirst(projectName, "");// /xxx/xx 106 | target_path=target_path.replaceFirst("/", ""); 107 | String packags=MCheck.isNull(target_path)?"":target_path.contains("/")?target_path.substring(0, target_path.indexOf("/")):target_path; 108 | //过滤了指定的文件包名:2012-11-23 109 | if(allow_packer.contains(packags)){//以斜线开头 110 | cache_path.add(target); 111 | return; 112 | } 113 | isHandled[0] = true; 114 | MInit mInit =MInit.get(); 115 | String[] uri_s=mInit.getURI().parse(target); 116 | mInit.getRouter().run(uri_s);//路由器调用 117 | MRender render =mInit.getMb().getRender();//返回的界面 118 | if (MCheck.isNull(render.getView()) && render.isJsp()) { 119 | String viewPath = MTool.get_path()+"/"+ mInit.getRouter().getMethod() + ".jsp"; 120 | render.setContext(request, response,viewPath).render(); 121 | } else { 122 | render.setContext(request, response).render(); 123 | } 124 | } 125 | } 126 | 127 | public void destroy() { 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/com/jzero/util/MPath.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.net.JarURLConnection; 7 | import java.net.URL; 8 | import java.util.Enumeration; 9 | import java.util.Properties; 10 | import java.util.jar.JarEntry; 11 | import java.util.jar.JarFile; 12 | @SuppressWarnings("unchecked") 13 | public class MPath { 14 | private MPath() { 15 | } 16 | 17 | private static MPath path = new MPath(); 18 | 19 | public static MPath me() { 20 | return path; 21 | } 22 | 23 | public String getWebClassesPath() { 24 | return getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 25 | } 26 | 27 | /** 28 | * App Run: /F:/demo/wzybcx/WebRoot/WEB-INF/lib/myjar.jar 29 | * 30 | * 页面加载 /D:/Program Files/Apache Software Foundation/Tomcat 31 | * 6.0/webapps/wzybcx/WEB-INF/lib/myjar.jar 32 | * 33 | * @return 34 | */ 35 | public String getSrcPath() { 36 | String path = getWebClassesPath(); 37 | if (path.indexOf("WEB-INF") > 0) { 38 | path = path.substring(0, path.indexOf("WEB-INF")); 39 | } 40 | path = new File(path).getAbsolutePath(); 41 | return path; 42 | } 43 | 44 | public String getWebInfPath() { 45 | String path = getWebClassesPath(); 46 | if (path.indexOf("WEB-INF") > 0) { 47 | path = path.substring(0, path.indexOf("WEB-INF") + 8); 48 | } 49 | return path; 50 | } 51 | 52 | public String getWebRoot() { 53 | String path = getWebClassesPath(); 54 | // MPrint.print(MPath.me().getWebClassesPath());///D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/JZero/WEB-INF/classes/com/jzero/util/MPath.class 55 | // MPrint.print(MPath.me().getWebInfPath());///D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/JZero/WEB-INF/ 56 | // MPrint.print(MPath.me().getPath(MPath.class));//D:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\JZero\WEB-INF\classes\com\jzero\log 57 | // MPrint.print(MPath.me().getRootClassPath());//->D:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\JZero\WEB-INF\classes 58 | // MPrint.print(MPath.me().getSrcPath()); 59 | if (path.indexOf("WEB-INF") > 0) { 60 | path = path.substring(0, path.indexOf("WEB-INF")); 61 | } 62 | return path; 63 | } 64 | 65 | private static String webRootPath; 66 | 67 | 68 | 69 | public String getPath(Class clazz) { 70 | String path = clazz.getResource("/").getPath(); 71 | return new File(path).getAbsolutePath().replaceAll("%20", " "); 72 | } 73 | 74 | public String getPath(Object object) { 75 | String path = object.getClass().getResource("").getPath(); 76 | return new File(path).getAbsolutePath(); 77 | } 78 | 79 | public String getRootClassPath() { 80 | String path = MPath.class.getClassLoader().getResource("").getPath(); 81 | path= new File(path).getAbsolutePath(); 82 | return path.replaceAll("%20", " "); 83 | } 84 | 85 | public String getPackagePath(Object object) { 86 | Package p = object.getClass().getPackage(); 87 | return p != null ? p.getName().replaceAll("\\.", "/") : ""; 88 | } 89 | 90 | public Properties getFileFromJar(String file) throws Exception { 91 | String dirPath = file; //jar中的目录名称 92 | URL url = this.getClass().getClassLoader().getResource(dirPath);//加载 93 | String urlStr = url.toString(); 94 | String jarPath = urlStr.substring(0, urlStr.indexOf("!/") + 2); //将jar文件读取出来 95 | URL jarURL = new URL(jarPath); 96 | JarURLConnection jarCon = (JarURLConnection) jarURL.openConnection(); //对jar文件进行加载 97 | JarFile jarFile = jarCon.getJarFile(); 98 | Enumeration jarEntrys = jarFile.entries(); //得到该jar文件下的所有目录文件 99 | Properties props = new Properties(); 100 | while (jarEntrys.hasMoreElements()) { 101 | JarEntry entry = jarEntrys.nextElement(); 102 | // 简单的判断路径,如果想做到想Spring,Ant-Style格式的路径匹配需要用到正则。 103 | String name = entry.getName(); 104 | MPrint.print("scan "+name); 105 | if (name.startsWith(dirPath) && !entry.isDirectory()) { //如果名称与dirpath相等,说明找到了当前文件,则进行加载 开始读取文件内容 106 | InputStream is = this.getClass().getClassLoader().getResourceAsStream(name); 107 | props.load(is); 108 | } 109 | } 110 | return props; 111 | } 112 | 113 | public String getWebRootPath() { 114 | if (webRootPath == null) 115 | webRootPath = detectWebRootPath(); 116 | return webRootPath; 117 | } 118 | 119 | public void setWebRootPath(String webRootPath) { 120 | if (webRootPath.endsWith(File.separator)) 121 | webRootPath = webRootPath.substring(0, webRootPath.length() - 1); 122 | MPath.webRootPath = webRootPath; 123 | } 124 | 125 | private String detectWebRootPath() { 126 | try { 127 | String path = MPath.class.getResource("/").getFile(); 128 | return new File(path).getParentFile().getParentFile() 129 | .getCanonicalPath(); 130 | } catch (IOException e) { 131 | throw new RuntimeException(e); 132 | } 133 | } 134 | public static void main(String[] args) throws Exception { 135 | MPath.me().setWebRootPath("/"); 136 | MPrint.print(MPath.me().getWebRoot());///D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/JZero/ 137 | MPrint.print(MPath.me().getWebClassesPath());///D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/JZero/WEB-INF/classes/com/jzero/util/MPath.class 138 | MPrint.print(MPath.me().getWebInfPath());///D:/Program Files/Apache Software Foundation/Tomcat 6.0/webapps/JZero/WEB-INF/ 139 | MPrint.print(MPath.me().getPath(MPath.class));//D:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\JZero\WEB-INF\classes\com\jzero\log 140 | MPrint.print(MPath.me().getRootClassPath());//->D:\Program%20Files\Apache%20Software%20Foundation\Tomcat%206.0\webapps\JZero\WEB-INF\classes 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /src/com/jzero/db/utility/MysqlDb.java: -------------------------------------------------------------------------------- 1 | package com.jzero.db.utility; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | 6 | import com.jzero.core.MReport; 7 | import com.jzero.db.cache.MCache; 8 | import com.jzero.db.core.M; 9 | import com.jzero.util.MCheck; 10 | import com.jzero.util.MRecord; 11 | import com.jzero.util.MSee; 12 | import com.jzero.util.MySQL; 13 | import com.jzero.util.MSee.IAtom; 14 | 15 | /** 16 | * --- 2012-4-9 --- 17 | * --- Administrator --- 18 | * MysqlDb.java :操作mysql操作 19 | */ 20 | public final class MysqlDb implements MFieldDb { 21 | private MysqlDb(){} 22 | private static MFieldDb db=new MysqlDb(); 23 | 24 | public List getAllTable() { 25 | List inlistMap = M.me().sql(MySQL.MYSQL_TABLE); 26 | List outList = new LinkedList(); 27 | MRecord tempMap = null; 28 | for (MRecord r : inlistMap) { 29 | tempMap = new MRecord(); 30 | tempMap.set("tablename",r.get("name")); 31 | tempMap.set("commentfield", r.get("comment")); 32 | outList.add(tempMap); 33 | } 34 | return outList; 35 | } 36 | 37 | public List getFieldForTable(String tableName) { 38 | final String sql=MySQL.MYSQL_FIELD+tableName; 39 | List data = null; 40 | if (MCache.me().isEnabled()) { 41 | data = MCache.me().read(sql); 42 | } 43 | if(MCheck.isNull(data)){ 44 | data=M.me().sql(MySQL.MYSQL_FIELD+tableName); 45 | }else { 46 | MSee.ok_sql(new IAtom() { 47 | public void run() throws Exception { 48 | MReport.doFileReport(sql); 49 | } 50 | }, MCache.me().isEnabled()); 51 | } 52 | return data; 53 | } 54 | /** 55 | * defaultname格式为:display_xxx 56 | * 暂定义可输入项为: display:显示此字段, 57 | * text:文本框 58 | * date:时间 59 | * datetime:时间分秒 60 | * select(怎样传递进来?): 61 | * int:只能录入整数 62 | */ 63 | public List getCommentAndFieldName(String tableName) { 64 | List inlistMap = getFieldForTable(tableName); 65 | List outList = new LinkedList(); 66 | MRecord tempMap = null; 67 | 68 | for (MRecord r : inlistMap) { 69 | String defaultName =r.getStr("default"); 70 | if (checkIsDisplay(defaultName)) { 71 | tempMap = new MRecord(); 72 | tempMap.set("field", r.get("field")); 73 | tempMap.set("comment", r.get("comment")); 74 | outList.add(tempMap); 75 | } 76 | } 77 | return outList; 78 | } 79 | 80 | 81 | 82 | /** 83 | * 检查默认字段为:display字段, 84 | * 如果字段为display为返回true,如果字段类型为display_xxx,返回true,否则返回false 85 | * ; 86 | */ 87 | private boolean checkIsDisplay(String defaultName) { 88 | if (!MCheck.isNull(defaultName)) {// 不为空 89 | if ("display".equalsIgnoreCase(defaultName)) {// 只显示display的字段 90 | return true; 91 | } 92 | String objs[] = defaultName.split("_");// eg:display_xx_dd 93 | if (objs.length > 0) { 94 | if (objs[0].equals("display")) { 95 | return true; 96 | } 97 | } 98 | } 99 | return false; 100 | } 101 | 102 | public List getDefaultAndFieldName(String tableName) { 103 | List inlistMap = getFieldForTable(tableName); 104 | List outList = new LinkedList(); 105 | MRecord tempMap = null; 106 | 107 | for (MRecord r : inlistMap) { 108 | String comment = r.get("comment"); 109 | if (!MCheck.isNull(comment)) {// 过滤掉没有注释的字段 110 | tempMap = new MRecord(); 111 | tempMap.set("field", r.get("field")); 112 | tempMap.set("comment", comment); 113 | outList.add(tempMap); 114 | } 115 | } 116 | return outList; 117 | } 118 | 119 | public List getSelectField(String tableName) { 120 | List inlistMap = getFieldForTable(tableName); 121 | List outList = new LinkedList(); 122 | MRecord tempMap = null; 123 | 124 | for (MRecord r : inlistMap) { 125 | String defaultName = r.getStr("default"); 126 | if (checkIsDisplay(defaultName)) { 127 | tempMap = getTypeAndLenthByDefault(r.getStr("type")); 128 | outList.add(tempMap); 129 | } 130 | } 131 | return outList; 132 | } 133 | 134 | // mysql返回的类型为Type:int(11) Or datetime 135 | private MRecord getTypeAndLenthByDefault(String type) { 136 | MRecord tempMap = new MRecord(); 137 | if (type.contains("(")) {// 有长度,eg:varchar(50); 138 | tempMap.set("type", type.substring(0, type.indexOf("(")));// varchar 139 | tempMap.set("length", type.substring(type.indexOf("(") + 1, type.lastIndexOf(")")));// 50 140 | } else {// 无长度,eg:datetime 141 | tempMap.set("type", type); 142 | tempMap.set("length", 0); 143 | } 144 | return tempMap; 145 | 146 | } 147 | 148 | public String get_pager_sql(String table, String where,String field, int current, 149 | int pageSize, Object... obj) { 150 | StringBuffer sql_bf = new StringBuffer(); 151 | if(MCheck.isNull(field)){ 152 | sql_bf.append(" SELECT * FROM ").append(table); 153 | }else{ 154 | sql_bf.append(" SELECT ").append(field).append(" FROM ").append(table); 155 | } 156 | if (!MCheck.isNull(where)) { // 不为空,则有where 语句 157 | sql_bf.append(" WHERE 1=1 ").append(where); 158 | } 159 | if (!MCheck.isNull(obj)) { 160 | sql_bf.append(" ").append(obj[0]); 161 | //sql_bf.append(" order by id desc"); 162 | } 163 | current=current<0?0:current; 164 | sql_bf.append(" LIMIT ").append(current).append(" , ").append(pageSize); 165 | return sql_bf.toString(); 166 | } 167 | public static MFieldDb getIns() { 168 | return db; 169 | } 170 | // public static void main(String[] args) { 171 | // String str = "int(11)"; 172 | // PrintUtil.print(str.contains("(")); 173 | // PrintUtil.print(str.substring(0, str.indexOf("("))); 174 | // PrintUtil.print(str.substring(str.indexOf("(") + 1, str 175 | // .lastIndexOf(")"))); 176 | // } 177 | 178 | 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/com/jzero/util/MDividPage.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import com.jzero.core.MR; 4 | import com.jzero.core.MRouter; 5 | import com.jzero.core.MURI; 6 | 7 | public class MDividPage { 8 | private static int STEP = 3;// 偏移量,即显示2x3+1=7个 9 | private static int LEFT_NUM = 0;// 左界限 10 | private static int RIGHT_NUM = 0;// 右界限 11 | 12 | /** 13 | * 14 | * @param currentPage 15 | * 当前页数 16 | * @param pageSize 17 | * 每页显示数量 18 | * @param totalSize 19 | * 总记录数 20 | * @return links 21 | */ 22 | public static String getPageLink(int currentPage, int pageSize,int totalSize, int step,Integer page_seg) { 23 | /** get totalPage **/ 24 | STEP = step; 25 | 26 | /** get totalPage **/ 27 | int totalPage = (totalSize % pageSize == 0) ? (totalSize / pageSize): (totalSize / pageSize + 1); 28 | String links = ""; 29 | 30 | if (currentPage > totalPage) 31 | currentPage = totalPage; 32 | if (currentPage < 1) 33 | currentPage = 1; 34 | 35 | /** 总页数大于1时候才进行分页处理 **/ 36 | if (totalPage > 1) 37 | links += MDividPage.setLink(currentPage, totalPage, 38 | totalSize,page_seg)+ 39 | MDividPage.setScript(); 40 | 41 | return links; 42 | } 43 | 44 | /** 45 | * 获取url链接 46 | * localhost/pro/controller(0)/method(1)/order_str/find_str/page 47 | * @return url 48 | */ 49 | public static String getUrl(Integer page_seg){ 50 | String path=MTool.get_path(); 51 | int level=MTool.get_level(); 52 | int begin_seg=level==1?2:3; 53 | String method=MRouter.me().getMethod(); 54 | if(MCheck.isNull(method)){ method="find";} 55 | 56 | String order=MTool.decode(MURI.me().seg_str(begin_seg)); 57 | String find_str=MTool.decode(MURI.me().seg_str(begin_seg+1)); 58 | order=MCheck.isNull(order)?MR.me().getAttrForStr(Msg.ORDER_STR):order; 59 | find_str=MCheck.isNull(find_str)?MR.me().getAttrForStr(Msg.FIND_STR):find_str; 60 | return MTool.getBase()+path+"/"+method+"/"+order+"/"+find_str; 61 | } 62 | public static String getUrl(){ 63 | return getUrl(2); 64 | } 65 | 66 | /** 67 | * 处理数字链接的左右边界值 68 | * 69 | * @param currentPage 70 | * @param totalPage 71 | */ 72 | public static void setBounds(int currentPage, int totalPage) { 73 | if (currentPage - STEP < 1) { 74 | LEFT_NUM = 1; 75 | } else { 76 | LEFT_NUM = currentPage - STEP; 77 | } 78 | if (currentPage + STEP > totalPage) { 79 | RIGHT_NUM = totalPage; 80 | } else { 81 | RIGHT_NUM = currentPage + STEP; 82 | } 83 | 84 | /** 如果页数大于(2xSTEP+1),但是显示少于(2xSTEP+1),则强制显示(2xSTEP+1) **/ 85 | if (totalPage <= 2 * STEP + 1) { 86 | LEFT_NUM = 1; 87 | RIGHT_NUM = totalPage; 88 | } else { 89 | if (2 * STEP + 1 <= totalPage) { 90 | if (RIGHT_NUM < 2 * STEP + 1) { 91 | RIGHT_NUM = 2 * STEP + 1; 92 | } 93 | } 94 | if (totalPage - 2 * STEP > 0) { 95 | if (LEFT_NUM > totalPage - 2 * STEP) { 96 | LEFT_NUM = totalPage - 2 * STEP; 97 | } 98 | } 99 | } 100 | } 101 | 102 | public static String setLink(int currentPage, int totalPage, int totalSize,Integer page_seg) { 103 | 104 | /** 处理链接 **/ 105 | String url = getUrl(page_seg); 106 | 107 | String links2 = "
    "; 108 | 109 | /** 显示分页信息 **/ 110 | links2 += "
  • 页码:" 113 | + currentPage + "/" + totalPage + "
  • "; 114 | 115 | /** 采用数字方式显示链接 **/ 116 | 117 | /** 处理首页与上页 **/ 118 | if (currentPage == 1) { 119 | links2 += "
  • «首页
  • "; 120 | links2 += "
  • ‹上页
  • "; 121 | } else { 122 | links2 += ""; 124 | links2 += ""; 129 | } 130 | 131 | /** 获取左右边界值 **/ 132 | setBounds(currentPage, totalPage); 133 | 134 | /** 处理中间页 **/ 135 | for (int i = LEFT_NUM; i <= RIGHT_NUM; i++) { 136 | if (i != currentPage) 137 | links2 += "
  • " + i + "
  • "; 139 | else 140 | links2 += "
  • " 141 | + i + "
  • "; 142 | } 143 | 144 | /** 处理下页与末页 **/ 145 | if (currentPage == totalPage) { 146 | links2 += "
  • 下页›
  • "; 147 | links2 += "
  • 末页»
  • "; 148 | } else { 149 | // links2+=""; 150 | // links2+=""; 151 | links2 += ""; 152 | links2 += ""; 153 | } 154 | 155 | /** 添加跳转框 **/ 156 | // links2 += "
  • "; 158 | // links2 += "
  • "; 160 | 161 | // links2 += "
  • 总记录:(" 162 | // + totalSize + ")条数据
  • "; 163 | 164 | links2 += "
"; 165 | links2 += "
"; 166 | return links2; 167 | } 168 | 169 | public static String setScript() { 170 | String script = ""; 171 | 172 | return script; 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/com/jzero/i18n/I18N.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.i18n; 3 | 4 | import java.util.Enumeration; 5 | import java.util.Locale; 6 | import java.util.MissingResourceException; 7 | import java.util.ResourceBundle; 8 | import java.util.concurrent.ConcurrentHashMap; 9 | import java.util.concurrent.ConcurrentMap; 10 | 11 | import com.jzero.util.MPro; 12 | import com.jzero.util.Msg; 13 | 14 | 15 | /** 16 | * 2012-10-4: from JFinal 17 | * wangujqw@gmail.com 18 | */ 19 | public class I18N { 20 | 21 | private static String baseName; 22 | private static Locale defaultLocale = Locale.getDefault(); 23 | private static int i18nMaxAgeOfCookie=600; 24 | private static final NullResourceBundle NULL_RESOURCE_BUNDLE = new NullResourceBundle(); 25 | private static final ConcurrentMap bundlesMap = new ConcurrentHashMap(); 26 | private static final MPro pro=MPro.me().load_file(Msg.CONFIG); 27 | private static volatile I18N me; 28 | 29 | private I18N() { 30 | } 31 | 32 | public static I18N me() { 33 | if (me == null) { 34 | synchronized (I18N.class) { 35 | me = new I18N(); 36 | } 37 | } 38 | return me; 39 | } 40 | 41 | public static void init(String baseName, Locale defaultLocale) { 42 | I18N.baseName = baseName; 43 | if (defaultLocale != null) 44 | I18N.defaultLocale = defaultLocale; 45 | I18N.i18nMaxAgeOfCookie = pro.getInt("DEFAULT_I18N_MAX_AGE_OF_COOKIE"); 46 | } 47 | 48 | public static Locale getDefaultLocale() { 49 | return defaultLocale; 50 | } 51 | 52 | final static public int getI18nMaxAgeOfCookie() { 53 | return i18nMaxAgeOfCookie; 54 | } 55 | 56 | private static ResourceBundle getResourceBundle(Locale locale) { 57 | String resourceBundleKey = getresourceBundleKey(locale); 58 | ResourceBundle resourceBundle = bundlesMap.get(resourceBundleKey); 59 | if (resourceBundle == null) { 60 | try { 61 | resourceBundle = ResourceBundle.getBundle(baseName, locale); 62 | bundlesMap.put(resourceBundleKey, resourceBundle); 63 | } 64 | catch (MissingResourceException e) { 65 | resourceBundle = NULL_RESOURCE_BUNDLE; 66 | } 67 | } 68 | return resourceBundle; 69 | } 70 | 71 | /** 72 | * 将来只改这里就可以了: resourceBundleKey的生成规则 73 | */ 74 | private static String getresourceBundleKey(Locale locale) { 75 | return baseName + locale.toString(); 76 | } 77 | 78 | public static String getText(String key) { 79 | return getResourceBundle(defaultLocale).getString(key); 80 | } 81 | 82 | public static String getText(String key, String defaultValue) { 83 | String result = getResourceBundle(defaultLocale).getString(key); 84 | return result != null ? result : defaultValue; 85 | } 86 | 87 | public static String getText(String key, Locale locale) { 88 | return getResourceBundle(locale).getString(key); 89 | } 90 | 91 | public static String getText(String key, String defaultValue, Locale locale) { 92 | String result = getResourceBundle(locale).getString(key); 93 | return result != null ? result : defaultValue; 94 | } 95 | 96 | // public static Locale localeFromString(String localeStr, Locale defaultLocale) { 97 | public static Locale localeFromString(String localeStr) { 98 | if ((localeStr == null) || (localeStr.trim().length() == 0) || ("_".equals(localeStr))) { 99 | // return (defaultLocale != null) ? defaultLocale : Locale.getDefault(); // 原实现被注掉 100 | return defaultLocale; 101 | } 102 | 103 | int index = localeStr.indexOf('_'); 104 | if (index < 0) { 105 | return new Locale(localeStr); 106 | } 107 | 108 | String language = localeStr.substring(0, index); 109 | if (index == localeStr.length()) { 110 | return new Locale(language); 111 | } 112 | 113 | localeStr = localeStr.substring(index + 1); 114 | index = localeStr.indexOf('_'); 115 | if (index < 0) { 116 | return new Locale(language, localeStr); 117 | } 118 | 119 | String country = localeStr.substring(0, index); 120 | if (index == localeStr.length()) { 121 | return new Locale(language, country); 122 | } 123 | 124 | localeStr = localeStr.substring(index + 1); 125 | return new Locale(language, country, localeStr); 126 | } 127 | 128 | private static class NullResourceBundle extends ResourceBundle { 129 | public Enumeration getKeys() { 130 | return null; // dummy 131 | } 132 | protected Object handleGetObject(String key) { 133 | return null; // dummy 134 | } 135 | } 136 | 137 | // 可惜的是使用Local可以被 new 出来, 造成了无法判断相等,后来测试,可以使用 equals方法来判断是否相等 138 | public static void main(String[] args) { 139 | // Locale.getDefault(); 140 | // Locale en = Locale.US; 141 | // Locale us = Locale.US; 142 | // System.out.println(l.toString()); 143 | // System.out.println(en == us); 144 | // System.out.println(en.equals(us)); 145 | 146 | // 下面的 taiwan.getLanguage()值仍为 zh,所以可以确定i18n实现有缺陷,即 language不能唯一确定Local对象 147 | // 造成了无法通过 language不好还原 148 | System.out.println(Locale.CHINESE.getLanguage()); 149 | System.out.println(Locale.CHINA.getLanguage()); 150 | System.out.println(Locale.SIMPLIFIED_CHINESE.getLanguage()); 151 | System.out.println(Locale.TRADITIONAL_CHINESE.getLanguage()); 152 | System.out.println(Locale.TAIWAN.getLanguage()); 153 | 154 | Locale shoudong = new Locale("en"); 155 | System.out.println(shoudong.getLanguage().equals(Locale.US.getLanguage())); 156 | System.out.println(shoudong.getLanguage().equals(Locale.ENGLISH.getLanguage())); 157 | System.out.println(shoudong.getLanguage().equals(Locale.CANADA.getLanguage())); 158 | System.out.println(shoudong.getLanguage().equals(Locale.UK.getLanguage())); 159 | System.out.println(shoudong.getLanguage().equals(Locale.CANADA_FRENCH.getLanguage())); 160 | } 161 | } -------------------------------------------------------------------------------- /src/com/jzero/util/MMD5.java: -------------------------------------------------------------------------------- 1 | package com.jzero.util; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | public class MMD5 { 7 | 8 | // MD5加码。32位 9 | private static String MD5(String inStr) { 10 | MessageDigest md5 = null; 11 | try { 12 | md5 = MessageDigest.getInstance("MD5"); 13 | } catch (Exception e) { 14 | System.out.println(e.toString()); 15 | e.printStackTrace(); 16 | return ""; 17 | } 18 | char[] charArray = inStr.toCharArray(); 19 | byte[] byteArray = new byte[charArray.length]; 20 | 21 | for (int i = 0; i < charArray.length; i++) 22 | byteArray[i] = (byte) charArray[i]; 23 | 24 | byte[] md5Bytes = md5.digest(byteArray); 25 | 26 | StringBuffer hexValue = new StringBuffer(); 27 | 28 | for (int i = 0; i < md5Bytes.length; i++) { 29 | int val = ((int) md5Bytes[i]) & 0xff; 30 | if (val < 16) 31 | hexValue.append("0"); 32 | hexValue.append(Integer.toHexString(val)); 33 | } 34 | 35 | return hexValue.toString(); 36 | } 37 | 38 | // 可逆的加密算法 39 | private static String KL(String inStr) { 40 | char[] a = double_str(inStr).toCharArray(); 41 | for (int i = 0; i < a.length; i++) { 42 | a[i] = (char) (a[i] ^ 't'); 43 | } 44 | String s = new String(a); 45 | return s; 46 | } 47 | 48 | private static String double_str(String str) { 49 | return str + str; 50 | } 51 | 52 | // 加密后解密 53 | private static String JM(String inStr) { 54 | char[] a = inStr.toCharArray(); 55 | for (int i = 0; i < a.length; i++) { 56 | a[i] = (char) (a[i] ^ 't'); 57 | } 58 | String k = new String(a); 59 | return k.substring(0, k.length() / 2); 60 | } 61 | 62 | public static String StrToMD5(String str) { 63 | return KL(str); 64 | } 65 | 66 | public static String toMD5(String str) { 67 | return MD5(str); 68 | } 69 | 70 | public static String toMD5ByJAVA(String plainText) { 71 | StringBuffer buf = new StringBuffer(""); 72 | try { 73 | MessageDigest md = MessageDigest.getInstance("MD5"); 74 | md.update(plainText.getBytes()); 75 | byte messageDigest[] = md.digest(); 76 | for (int i = 0; i < messageDigest.length; i++) { 77 | buf.append(Integer.toHexString(0xFF & messageDigest[i])); 78 | } 79 | } catch (NoSuchAlgorithmException e) { 80 | e.printStackTrace(); 81 | } 82 | return buf.toString(); 83 | } 84 | 85 | public static String MD5ToStr(String str) { 86 | return JM(str); 87 | } 88 | public static void test(){ 89 | String username="Mufasa"; 90 | String realm="testrealm@host.com"; 91 | String nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"; 92 | String cnonce="0a4f113b"; 93 | String password="Circle Of Life"; 94 | String nc="00000001"; 95 | String method="GET"; 96 | String qop="auth"; 97 | String uri="/dir/index.html"; 98 | 99 | String secret = MMD5.toMD5ByJAVA(username + ":" + realm + ":" 100 | + password); 101 | String A2 = MMD5.toMD5ByJAVA(method + ":" + uri); 102 | String data = nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + A2;// +":"+opaque; 103 | String response = MMD5.toMD5ByJAVA(secret + ":" + data); 104 | MPrint.print(response); 105 | } 106 | public static void test2(){ 107 | String username="ebframe&99&0.5"; 108 | String realm="wdpf@service.cmcc.cn"; 109 | String nonce="906e924e1c519ccc073279f5421977e"; 110 | String cnonce="4a856905"; 111 | String password="a79352ec7f1946ebaaec2ceb3db64f98"; 112 | String nc="00001772"; 113 | String method="GET"; 114 | String qop="auth"; 115 | String uri="http://192.168.1.118:8080/WDPF/register?ua=ebframe&os=99&version=0.5"; 116 | // String client_response="7eca8854baaa6ed536e4db1135420d56"; 117 | 118 | String secret = MMD5.toMD5ByJAVA(username + ":" + realm + ":" 119 | + password); 120 | String A2 = MMD5.toMD5ByJAVA(method + ":" + uri); 121 | String data = nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + A2;// +":"+opaque; 122 | String response = MMD5.toMD5ByJAVA(secret + ":" + data); 123 | MPrint.print(response); 124 | } 125 | // // 测试主函数 126 | public static void main(String args[]) { 127 | test2(); 128 | // String name = "root"; 129 | // String pass = "guilinsoft"; 130 | // String m1 = toMD5(name); 131 | // String m2 = StrToMD5(pass); 132 | // MPrint.print(m1 + "," + m2); 133 | // MPrint.print(MD5ToStr(m1) + "," + MD5ToStr(m2)); 134 | // String username="ebframe&99&0.5"; 135 | // String realm="Wang"; 136 | // String nonce="6fabc387f9c42f6a4fd97c2c2f303485"; 137 | // String cnonce="4a856905"; 138 | // String password="a79352ec7f1946ebaaec2ceb3db64f98"; 139 | // password="826e7a57fd11ba10436a0d39723d676"; 140 | // String nc="00000001"; 141 | // String method="GET"; 142 | // String qop="auth"; 143 | // String 144 | // uri="http://192.168.1.118:8080/WDPF/register?ua=ebframe&os=99&version=0.5"; 145 | 146 | // String username = "ebframe&99&0.5"; 147 | // String realm = "wdpf@service.cmcc.cn"; 148 | // String nonce = "423fc0c1704c447fbc075d9ae57cd953"; 149 | // String cnonce = "4a856905"; 150 | // String password = "a79352ec7f1946ebaaec2ceb3db64f98"; 151 | // String nc = "00000001"; 152 | // String method = "GET"; 153 | // String qop = "auth"; 154 | // String uri = "http://lovepost-g3.com:28080/WDPF/register?ua=ebframe&os=99&version=0.5"; 155 | // 156 | // String secret = MMD5.toMD5ByJAVA(username + ":" + realm + ":" 157 | // + password); 158 | // String A2 = MMD5.toMD5ByJAVA(method + ":" + uri); 159 | // String data = nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + A2;// +":"+opaque; 160 | // String response = MMD5.toMD5ByJAVA(secret + ":" + data); 161 | // MPrint.print(response); 162 | // f6c1dfc763bf1344d00679511bf0cbbb 163 | 164 | // MPrint.print(MD5.toMD5("077301004a79352ec7f1946ebaaec2ceb3db64f98")); 165 | // 8d36d94a9035c60eb4928eea6adf42bf 166 | 167 | // String username="Mufasa"; 168 | // String realm="testrealm@host.com"; 169 | // String nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"; 170 | // String cnonce="0a4f113b"; 171 | // String password="Circle Of Life"; 172 | // String nc="00000001"; 173 | // String method="GET"; 174 | // String qop="auth"; 175 | // String uri="/dir/index.html"; 176 | // MPrint.print(MD5.toMD5("077301004:a79352ec7f1946ebaaec2ceb3db64f98")); 177 | } 178 | } -------------------------------------------------------------------------------- /src/com/jzero/upload/MFFmpeg.java: -------------------------------------------------------------------------------- 1 | package com.jzero.upload; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.InputStreamReader; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.regex.Matcher; 11 | import java.util.regex.Pattern; 12 | 13 | import com.jzero.util.MPrint; 14 | import com.jzero.util.MRecord; 15 | 16 | public class MFFmpeg { 17 | private String ffmpegPath; 18 | private static final String FILE_SEPARATOR = File.separator; 19 | public static MFFmpeg self = new MFFmpeg(); 20 | 21 | private MFFmpeg() { 22 | } 23 | 24 | public static MFFmpeg me() { 25 | return self; 26 | } 27 | 28 | public MFFmpeg init(String path) { 29 | this.ffmpegPath = path; 30 | return this; 31 | } 32 | 33 | private static boolean isSurpportedType(String type) { 34 | Pattern pattern = Pattern.compile( 35 | "(asx|asf|mpg|wmv|3gp|mp4|mov|avi|flv){1}$", 36 | Pattern.CASE_INSENSITIVE); 37 | Matcher matcher = pattern.matcher(type); 38 | return matcher.find(); 39 | } 40 | 41 | /** 42 | * 43 | * @param sourceFile 44 | * 将要被转换的目标文件 45 | * @param desctination 46 | * 转换之后文件的存放路径 ffmpeg commandLine: ffmpeg -y -i 47 | * /usr/local/bin/lh.mp4 -ab 56 -ar 22050 -b 500 -s 320x240 48 | * /usr/local/bin/lh.flv 49 | * @throws IOException 50 | */ 51 | public MRecord converToFlv(File sourceFile, String destination) { 52 | 53 | String fileName = sourceFile.getName(); 54 | String surffix = fileName.substring(fileName.lastIndexOf(".") + 1); 55 | if (!isSurpportedType(surffix)) 56 | throw new RuntimeException("unsurpported file type " + surffix); 57 | 58 | List cmdParam = new LinkedList(); 59 | cmdParam.add(ffmpegPath); 60 | cmdParam.add("-y"); 61 | cmdParam.add("-i"); 62 | cmdParam.add(sourceFile.getAbsolutePath()); 63 | cmdParam.add("-ab"); 64 | cmdParam.add("56"); 65 | cmdParam.add("-ar"); 66 | cmdParam.add("22050"); 67 | cmdParam.add("-b"); 68 | cmdParam.add("500"); 69 | cmdParam.add("-s"); 70 | cmdParam.add("320*240"); 71 | cmdParam.add(destination + FILE_SEPARATOR 72 | + fileName.substring(0, fileName.lastIndexOf(".")) + ".flv"); 73 | 74 | return execCmd(cmdParam); 75 | } 76 | 77 | /** 78 | * 79 | * 获取图片的第一帧 ffmpeg commandLine: ffmpeg -y -i /usr/local/bin/lh.3gp -vframes 80 | * 1 -r 1 -ac 1 -ab 2 -s 320x240 -f image2 /usr/local/bin/lh.jpg 81 | * 82 | * @param sourceFile 83 | * 源文件 84 | * @param destination 85 | * 目标文件 86 | * @param surfix 87 | * 要保存的图片格式:jpg,jpeg,gif 88 | * @throws IOException 89 | * @throws IOException 90 | */ 91 | public MRecord captureFirstFrame(File sourceFile, String destination) { 92 | return captureFirstFrame(sourceFile, destination, "jpg"); 93 | } 94 | 95 | public MRecord captureFirstFrame(File sourceFile, String destination, 96 | String surfix) { 97 | String fileName = sourceFile.getName(); 98 | String surffix = fileName.substring(fileName.lastIndexOf(".") + 1); 99 | if (!isSurpportedType(surffix)) 100 | throw new RuntimeException("unsurpported file type " + surffix); 101 | 102 | List cmd = new LinkedList(); 103 | cmd.add(ffmpegPath); 104 | cmd.add("-y"); 105 | cmd.add("-i"); 106 | cmd.add(sourceFile.getAbsolutePath()); 107 | cmd.add("-vframes"); 108 | cmd.add("1"); 109 | cmd.add("-r"); 110 | cmd.add("1"); 111 | cmd.add("-ac"); 112 | cmd.add("1"); 113 | cmd.add("-ab"); 114 | cmd.add("2"); 115 | cmd.add("-s"); 116 | cmd.add("56*56"); 117 | cmd.add("-f"); 118 | cmd.add("image2"); 119 | cmd.add(destination + FILE_SEPARATOR 120 | + fileName.substring(0, fileName.lastIndexOf(".")) + "." 121 | + surfix); 122 | 123 | return execCmd(cmd); 124 | } 125 | 126 | private MRecord execCmd(List cmd) { 127 | MRecord out = null; 128 | final ProcessBuilder pb = new ProcessBuilder(); 129 | pb.redirectErrorStream(true); 130 | pb.command(cmd); 131 | try { 132 | final Process p = pb.start(); 133 | InputStream in = p.getInputStream(); 134 | out = pattInfo(in); 135 | // 开启单独的线程来处理输入和输出流,避免缓冲区满导致线程阻塞. 136 | try { 137 | p.waitFor(); 138 | } catch (InterruptedException e) { 139 | e.printStackTrace(); 140 | Thread.currentThread().interrupt(); 141 | } 142 | p.getErrorStream().close(); 143 | } catch (IOException e) { 144 | e.printStackTrace(); 145 | } 146 | return out; 147 | } 148 | 149 | // 负责从返回信息中读取内容 150 | private String read(InputStream is) { 151 | BufferedReader br = null; 152 | StringBuffer sb = new StringBuffer(); 153 | try { 154 | br = new BufferedReader(new InputStreamReader(is), 500); 155 | 156 | String line = ""; 157 | while ((line = br.readLine()) != null) { 158 | // System.out.println(line); 159 | sb.append(line); 160 | } 161 | br.close(); 162 | } catch (Exception e) { 163 | } finally { 164 | try { 165 | if (br != null) 166 | br.close(); 167 | } catch (Exception e) { 168 | } 169 | } 170 | return sb.toString(); 171 | } 172 | 173 | // 负责从返回的内容中解析 174 | /** 175 | * Input #0, avi, from 'c:\join.avi': Duration: 00:00:10.68(时长), start: 176 | * 0.000000(开始时间), bitrate: 166 kb/s(码率) Stream #0:0: Video: msrle 177 | * ([1][0][0][0] / 0x0001)(编码格式), pal8(视频格式), 165x97(分辨率), 33.33 tbr, 33.33 178 | * tbn, 33.33 tbc Metadata: title : AVI6700.tmp.avi Video #1 179 | */ 180 | public MRecord pattInfo(InputStream is) { 181 | String info = read(is); 182 | MRecord out = new MRecord(); 183 | String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s"; 184 | Pattern pattern = Pattern.compile(regexDuration); 185 | Matcher m = pattern.matcher(info); 186 | if (m.find()) { 187 | out.set("timelen", getTimelen(m.group(1))).set("begintime", m.group(2)).set( 188 | "kb", m.group(3) + "kb/s"); 189 | } 190 | return out; 191 | } 192 | //格式:"00:00:10.68" 193 | private int getTimelen(String timelen){ 194 | int min=0; 195 | String strs[] = timelen.split(":"); 196 | if (strs[0].compareTo("0") > 0) { 197 | min+=Integer.valueOf(strs[0])*60*60;//秒 198 | } 199 | if(strs[1].compareTo("0")>0){ 200 | min+=Integer.valueOf(strs[1])*60; 201 | } 202 | if(strs[2].compareTo("0")>0){ 203 | min+=Math.round(Float.valueOf(strs[2])); 204 | } 205 | return min; 206 | } 207 | public static void main(String[] args) { 208 | // String ffmpegPath = "c:/ffmpeg.exe"; 209 | // File file = new File("c:/join.avi"); 210 | // MFFmpeg.me().init(ffmpegPath).captureFirstFrame(file, "c:/", "jpg"); 211 | String t = "00:00:10.68"; 212 | String strs[] = t.split(":"); 213 | int min=0; 214 | if (strs[0].compareTo("0") > 0) { 215 | min+=Integer.valueOf(strs[0])*60*60;//秒 216 | } 217 | if(strs[1].compareTo("0")>0){ 218 | min+=Integer.valueOf(strs[1])*60; 219 | } 220 | if(strs[2].compareTo("0")>0){ 221 | min+=Math.round(Float.valueOf(strs[2])); 222 | } 223 | MPrint.print(min); 224 | } 225 | 226 | } -------------------------------------------------------------------------------- /src/com/jzero/upload/MImageTools.java: -------------------------------------------------------------------------------- 1 | package com.jzero.upload; 2 | 3 | import java.io.*; 4 | import java.awt.*; 5 | import java.awt.image.*; 6 | import java.awt.Graphics; 7 | import java.awt.color.ColorSpace; 8 | import javax.imageio.ImageIO; 9 | 10 | import com.sun.image.codec.jpeg.JPEGCodec; 11 | import com.sun.image.codec.jpeg.JPEGImageEncoder; 12 | 13 | public class MImageTools { 14 | /** 15 | * 缩放图像 16 | * 17 | * @param srcImageFile 18 | * 源图像文件地址 19 | * @param result 20 | * 缩放后的图像地址 21 | * @param scale 22 | * 缩放比例 23 | * @param flag 24 | * 缩放选择:true 放大; false 缩小; 25 | */ 26 | public static void scale(File srcImageFile, String result, int scale, 27 | boolean flag) { 28 | try { 29 | BufferedImage src = ImageIO.read(srcImageFile); // 读入文件 30 | int width = src.getWidth(); // 得到源图宽 31 | int height = src.getHeight(); // 得到源图长 32 | if (flag) { 33 | // 放大 34 | width = width * scale; 35 | height = height * scale; 36 | } else { 37 | // 缩小 38 | width = width / scale; 39 | height = height / scale; 40 | } 41 | Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);//返回一个绽放版本,Image.SCALE_DEFAULT(使用默认的图像缩放算法。) 42 | BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);//表示一个图像,它具有合成整数像素的 8 位 RGB 颜色分量。 43 | Graphics g = tag.getGraphics(); 44 | g.drawImage(image, 0, 0, null); // 绘制缩小后的图 45 | g.dispose(); 46 | ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流 47 | } catch (IOException e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | /** 52 | * 指定大小 53 | */ 54 | public static void scale(File srcImageFile, String result, int width,int height) { 55 | try { 56 | BufferedImage src = ImageIO.read(srcImageFile); // 读入文件 57 | Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);//返回一个绽放版本,Image.SCALE_DEFAULT(使用默认的图像缩放算法。) 58 | BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);//表示一个图像,它具有合成整数像素的 8 位 RGB 颜色分量。 59 | Graphics g = tag.getGraphics(); 60 | g.drawImage(image, 0, 0, null); // 绘制缩小后的图 61 | g.dispose(); 62 | ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流 63 | } catch (IOException e) { 64 | e.printStackTrace(); 65 | } 66 | } 67 | 68 | /** 69 | * 图像切割 70 | * 71 | * @param srcImageFile 72 | * 源图像地址 73 | * @param descDir 74 | * 切片目标文件夹 75 | * @param destWidth 76 | * 目标切片宽度 77 | * @param destHeight 78 | * 目标切片高度 79 | */ 80 | public static void cut(String srcImageFile, String descDir, int destWidth, 81 | int destHeight) { 82 | try { 83 | Image img; 84 | ImageFilter cropFilter; 85 | // 读取源图像 86 | BufferedImage bi = ImageIO.read(new File(srcImageFile)); 87 | int srcWidth = bi.getHeight(); // 源图宽度 88 | int srcHeight = bi.getWidth(); // 源图高度 89 | if (srcWidth > destWidth && srcHeight > destHeight) { 90 | Image image = bi.getScaledInstance(srcWidth, srcHeight,Image.SCALE_DEFAULT); 91 | destWidth = 200; // 切片宽度 92 | destHeight = 150; // 切片高度 93 | int cols = 0; // 切片横向数量 94 | int rows = 0; // 切片纵向数量 95 | // 计算切片的横向和纵向数量 96 | if (srcWidth % destWidth == 0) { 97 | cols = srcWidth / destWidth; 98 | } else { 99 | cols = (int) Math.floor(srcWidth / destWidth) + 1; 100 | } 101 | if (srcHeight % destHeight == 0) { 102 | rows = srcHeight / destHeight; 103 | } else { 104 | rows = (int) Math.floor(srcHeight / destHeight) + 1; 105 | } 106 | // 循环建立切片 107 | // 改进的想法:是否可用多线程加快切割速度 108 | for (int i = 0; i < rows; i++) { 109 | for (int j = 0; j < cols; j++) { 110 | // 四个参数分别为图像起点坐标和宽高 111 | // 即: CropImageFilter(int x,int y,int width,int height) 112 | cropFilter = new CropImageFilter(j * 200, i * 150, 113 | destWidth, destHeight); 114 | img = Toolkit.getDefaultToolkit().createImage( 115 | new FilteredImageSource(image.getSource(), 116 | cropFilter)); 117 | BufferedImage tag = new BufferedImage(destWidth, 118 | destHeight, BufferedImage.TYPE_INT_RGB); 119 | Graphics g = tag.getGraphics(); 120 | g.drawImage(img, 0, 0, null); // 绘制缩小后的图 121 | g.dispose(); 122 | // 输出为文件 123 | ImageIO.write(tag, "JPEG", new File(descDir 124 | + "pre_map_" + i + "_" + j + ".jpg")); 125 | } 126 | } 127 | } 128 | } catch (Exception e) { 129 | e.printStackTrace(); 130 | } 131 | } 132 | 133 | /** */ 134 | /** 135 | * 图像类型转换 GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X) 136 | */ 137 | public static void convert(String source, String result) { 138 | try { 139 | File f = new File(source); 140 | f.canRead(); 141 | f.canWrite(); 142 | BufferedImage src = ImageIO.read(f); 143 | ImageIO.write(src, "JPG", new File(result)); 144 | } catch (Exception e) { 145 | // TODO Auto-generated catch block 146 | e.printStackTrace(); 147 | } 148 | } 149 | 150 | /** */ 151 | /** 152 | * 彩色转为黑白 153 | * 154 | * @param source 155 | * @param result 156 | */ 157 | public static void gray(String source, String result) { 158 | try { 159 | BufferedImage src = ImageIO.read(new File(source)); 160 | ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); 161 | ColorConvertOp op = new ColorConvertOp(cs, null); 162 | src = op.filter(src, null); 163 | ImageIO.write(src, "JPEG", new File(result)); 164 | } catch (IOException e) { 165 | e.printStackTrace(); 166 | } 167 | } 168 | /** 169 | * 加水印图片 170 | * 包含的属性有:String pressImg,水印图片;String targetImg,目标图片 171 | */ 172 | public void pressImage(String pressImg, String targetImg, 173 | int x, int y) { 174 | try { 175 | File file = new File(targetImg); 176 | Image src = ImageIO.read(file); 177 | int wideth = src.getWidth(null); 178 | int height = src.getHeight(null); 179 | BufferedImage image = new BufferedImage(wideth, height, 180 | BufferedImage.TYPE_INT_RGB); 181 | Graphics g = image.createGraphics(); 182 | g.drawImage(src, 0, 0, wideth, height, null); 183 | 184 | // 水印文件 185 | File _filebiao = new File(pressImg); 186 | Image src_biao = ImageIO.read(_filebiao); 187 | int wideth_biao = src_biao.getWidth(null); 188 | int height_biao = src_biao.getHeight(null); 189 | g.drawImage(src_biao, wideth - wideth_biao - x, height 190 | - height_biao - y, wideth_biao, height_biao, null); 191 | // / 192 | g.dispose(); 193 | FileOutputStream out = new FileOutputStream(targetImg); 194 | JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 195 | encoder.encode(image); 196 | out.close(); 197 | } catch (Exception e) { 198 | e.printStackTrace(); 199 | } 200 | } 201 | /** */ 202 | /** 203 | * @param args 204 | */ 205 | public static void main(String[] args) { 206 | String src="C:/1.jpg"; 207 | // scale(src,"C:/2.jpg", 2, false); 208 | cut(src,"C:/3.jpg",59,59); 209 | convert(src, "c:/4.jpg"); 210 | gray(src, "c:/5.jpg"); 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /src/com/jzero/core/MRouter.java: -------------------------------------------------------------------------------- 1 | package com.jzero.core; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import com.jzero.aop.Uncheck; 8 | import com.jzero.log.Log; 9 | import com.jzero.render.MB; 10 | import com.jzero.util.MCheck; 11 | import com.jzero.util.MSession; 12 | import com.jzero.util.MTool; 13 | 14 | /** 15 | * 2012-10-3: 参考CI Router ,路由功能 16 | * wangujqw@gmail.com 17 | */ 18 | @SuppressWarnings("unchecked") 19 | public class MRouter{ 20 | 21 | private String controller; 22 | private String method; 23 | private String directory; 24 | private String default_controller; 25 | private String default_method; 26 | private String controller_package; 27 | private String default_view; 28 | /** 29 | * 后面操作包名,用于区别前台操作,如果此时的后台SESSION为空,则跳出到登录页面 30 | * 2012-11-5 31 | */ 32 | private String backstage_package; 33 | private final static String DOT="."; 34 | private boolean dev; 35 | 36 | public static MRouter me(){return MInit.get().getRouter();} 37 | 38 | public static MRouter init(MInit init){ 39 | MRouter router=new MRouter(); 40 | router.setDefault_controller(init.getConfig().getStr("default_controller")); 41 | router.setDefault_method(init.getConfig().getStr("default_method")); 42 | router.setController_package(init.getConfig().getStr("controller_package")); 43 | router.setDev(init.getConfig().getBool("is_dev")); 44 | router.setBackstage_package(init.getConfig().getStr("backstage_package")); 45 | router.setDefault_view(init.getConfig().getStr("default_view")); 46 | return router; 47 | } 48 | 49 | public void run(String[] uri_s){ 50 | if(MCheck.isNull(uri_s)){ 51 | invoke_default(); 52 | }else{ 53 | invoke(uri_s); 54 | } 55 | } 56 | 57 | 58 | private void invoke_default() { 59 | String path=getController_package()+DOT+getDefault_controller(); 60 | Class c=null; 61 | try { 62 | c=Class.forName(path); 63 | setController(getDefault_controller()); 64 | } catch (ClassNotFoundException e) { 65 | Log.me().write_error(e); 66 | MReport.doErrorReport(path, getDefault_controller(), getDefault_method()); 67 | MInit.get().getMb().getTextRender("未找到["+path+"] ..").render(); 68 | } 69 | if(!MCheck.isNull(c)){ 70 | try { 71 | if(MCheck.isNull(getDefault_method())){ 72 | setDefault_method("index"); 73 | } 74 | Method m = c.getDeclaredMethod(getDefault_method()); 75 | Object obj = c.newInstance(); 76 | m.invoke(obj); 77 | setMethod(getDefault_method()); 78 | if(isDev()){ 79 | MReport.doReport(path, getDefault_controller(), getDefault_method()); 80 | } 81 | 82 | }catch (Exception e) { 83 | e.printStackTrace(); 84 | Log.me().write_error(e); 85 | if(isDev()){ 86 | MReport.doErrorReport(path, getDefault_controller(), getDefault_method()); 87 | } 88 | MInit.get().getMb().getTextRender("执行["+getDefault_controller()+"/"+getDefault_controller()+"] 出现错误").render(); 89 | } 90 | } 91 | } 92 | 93 | /** 94 | * 验证是否存在,只支持有二级目录 95 | * eg:一级目录为:com.gl.test 96 | * 二级目录为:com.gl.test.back 97 | * @param mInit 98 | */ 99 | 100 | private void invoke(String[] uris) { 101 | setController(MTool.firstCharToUpperCase(MURI.me().seg_str(0, uris)));//默认控制器路径 uris[0] 102 | String path=getController_package()+DOT+getController();//控制器名称 103 | Class c=null; 104 | try { 105 | 106 | c=Class.forName(path); 107 | setDirectory(MURI.me().seg_str(0, uris)); 108 | setMethod(MURI.me().seg_str(1, uris)); 109 | } catch (ClassNotFoundException e) { 110 | setController(MTool.firstCharToUpperCase(MURI.me().seg_str(1, uris)));//查询子页面中的控制器 111 | path=path.toLowerCase()+DOT+getController(); 112 | try { 113 | c=Class.forName(path); 114 | setDirectory(MURI.me().seg_str(0, uris)); 115 | setMethod(MURI.me().seg_str(2, uris)); 116 | } catch (ClassNotFoundException e1) { 117 | Log.me().write_error(e1); 118 | MReport.doErrorReport(path, getController(), getMethod(), uris); 119 | MInit.get().getMb().getTextRender("未找到["+path+"] ...").render(); 120 | } 121 | } 122 | 123 | //在这里判断当前SESSION是否为空 124 | if(!MCheck.isNull(c)){ 125 | boolean check_session=check_current_session_is_null(c); 126 | if(check_session){ 127 | try { 128 | if(MCheck.isNull(getMethod())){ 129 | setMethod("index"); 130 | } 131 | Method m = getMeCls(getController(), getMethod(), c); 132 | Object obj=getClsName(getController(), c); 133 | m.invoke(obj); 134 | if(isDev()){ 135 | MReport.doReport(path, getController(), getMethod(), uris); 136 | } 137 | }catch (Exception e) { 138 | Log.me().write_error(e); 139 | // MB.me().getJspRender(getDefault_view()); 140 | MInit.get().getMb().getTextRender("未找到["+path+"."+getMethod()+"]").render(); 141 | if(isDev()){ 142 | MReport.doErrorReport(path, getController(), getMethod(), uris); 143 | } 144 | } 145 | } 146 | } 147 | } 148 | //2012-11-13 149 | private boolean check_current_session_is_null(Class cls){ 150 | String dir=getDirectory(); 151 | if(getBackstage_package().contains(dir)){ 152 | //在这检测是否有NO_SESSION 标签 153 | Uncheck uncheck=(Uncheck) cls.getAnnotation(Uncheck.class); 154 | if(MCheck.isNull(uncheck)){//等于空,则说需要检测SESSION值 155 | if(MCheck.isNull(MSession.get())){ 156 | MB.me().getJspRender(getDefault_view()); 157 | return false; 158 | } 159 | } 160 | } 161 | return true; 162 | } 163 | private static Map cls=new HashMap();//存放类 164 | private static Map mcls=new HashMap();//存放方法 165 | private Object getClsName(String name,Class clsname) throws Exception{ 166 | if(cls.containsKey(name)){ 167 | return cls.get(name).newInstance(); 168 | } 169 | cls.put(name, clsname); 170 | return clsname.newInstance(); 171 | } 172 | private Method getMeCls(String controller,String method,Class c) throws Exception{ 173 | String key=controller+method; 174 | if(mcls.containsKey(key)){ 175 | return mcls.get(key); 176 | } 177 | Class cls_name; 178 | if(cls.containsKey(controller)){ 179 | cls_name=cls.get(controller);//从类容器中取出类名 180 | }else{ 181 | cls_name=c; 182 | } 183 | Method m =cls_name.getDeclaredMethod(method); 184 | mcls.put(key, m); 185 | return m; 186 | } 187 | public String getMethod() { 188 | return method; 189 | } 190 | 191 | public void setMethod(String method) { 192 | this.method = method; 193 | } 194 | 195 | public String getDirectory() { 196 | return directory; 197 | } 198 | 199 | public void setDirectory(String directory) { 200 | this.directory = directory; 201 | } 202 | 203 | public String getDefault_controller() { 204 | return default_controller; 205 | } 206 | 207 | public void setDefault_controller(String defaultController) { 208 | default_controller = defaultController; 209 | } 210 | 211 | public String getDefault_method() { 212 | return default_method; 213 | } 214 | 215 | public void setDefault_method(String defaultMethod) { 216 | default_method = defaultMethod; 217 | } 218 | 219 | public String getController_package() { 220 | return controller_package; 221 | } 222 | 223 | public void setController_package(String controllerPackage) { 224 | controller_package = controllerPackage; 225 | } 226 | 227 | public String getController() { 228 | return controller; 229 | } 230 | 231 | public void setController(String controller) { 232 | this.controller = controller; 233 | } 234 | 235 | 236 | public boolean isDev() { 237 | return dev; 238 | } 239 | 240 | 241 | public void setDev(boolean dev) { 242 | this.dev = dev; 243 | } 244 | 245 | 246 | public String getBackstage_package() { 247 | return backstage_package; 248 | } 249 | 250 | 251 | public void setBackstage_package(String backstagePackage) { 252 | backstage_package = backstagePackage; 253 | } 254 | 255 | public String getDefault_view() { 256 | return default_view; 257 | } 258 | 259 | public void setDefault_view(String defaultView) { 260 | default_view = defaultView; 261 | } 262 | 263 | } 264 | -------------------------------------------------------------------------------- /src/com/jzero/comm/MCommHelp.java: -------------------------------------------------------------------------------- 1 | 2 | package com.jzero.comm; 3 | 4 | import java.io.IOException; 5 | import java.io.PrintWriter; 6 | import java.util.List; 7 | 8 | import com.jzero.core.MR; 9 | import com.jzero.core.MURI; 10 | import com.jzero.db.utility.MysqlDb; 11 | import com.jzero.log.Log; 12 | import com.jzero.util.MCheck; 13 | import com.jzero.util.MCnt; 14 | import com.jzero.util.MDate; 15 | import com.jzero.util.MEnum; 16 | import com.jzero.util.MRecord; 17 | import com.jzero.util.MTool; 18 | import com.jzero.util.Msg; 19 | 20 | /** 21 | * 2012-10-7: MComm.java辅助类 22 | * wangujqw@gmail.com 23 | */ 24 | public class MCommHelp { 25 | /** 26 | * @param url welcome/list 27 | * @param msg js 弹出的信息 28 | */ 29 | public static void outHTML(String url,String msg) { 30 | outHTML_comm(msg, url); 31 | } 32 | public static void outHTML_dialog(String msg) { 33 | outHTML_comm(msg, null); 34 | } 35 | public static void outHTML(String msg){ 36 | PrintWriter printWriter; 37 | try { 38 | printWriter = MR.me().getResponse().getWriter(); 39 | printWriter.write(msg); 40 | printWriter.flush(); 41 | printWriter.close(); 42 | } catch (IOException e) { 43 | Log.me().write_error(e); 44 | } 45 | } 46 | private static void outHTML_comm(String msg,String url){ 47 | url=MR.me().getToURI(url); 48 | PrintWriter printWriter; 49 | try { 50 | printWriter = MR.me().getResponse().getWriter(); 51 | StringBuffer html=new StringBuffer("提示"); 52 | html.append("") 53 | .append("") 54 | .append("") 55 | .append(""); 61 | printWriter.write(html.toString()); 62 | printWriter.flush(); 63 | printWriter.close(); 64 | } catch (IOException e) { 65 | Log.me().write_error(e); 66 | } 67 | } 68 | /** 69 | * 读取display表字段值 70 | * @return 71 | */ 72 | private static List getDefaultField(String tableName){ 73 | return MysqlDb.getIns().getCommentAndFieldName(tableName); 74 | } 75 | /** 76 | * 解析find_str:/welcome(0)/find(1)/order_str(2)/find_str(3)字符串,存放格式为 cxzd(查询字段),cxnr(查询内容),begintime(开始时间),endtime(截止时间),select_name(选择的下拉框值) 77 | * @return 78 | */ 79 | private static MRecord getFindValueByURI(Integer index){ 80 | index=MCheck.isNull(index)?3:index; 81 | String find_v=MURI.me().seg_str(index); 82 | String select_nm=MR.me().getPara("select_name"); 83 | MRecord record=new MRecord(); 84 | record.set("select_name", select_nm); 85 | if(!MCheck.isNull(find_v)){ 86 | if("ALL".equalsIgnoreCase(find_v)){ // all,时执行 87 | record.set("cxzd", find_v,"ALL"); 88 | record.set("cxnr", null); 89 | }else{ 90 | String strs[]=find_v.split(","); 91 | String cxzd=strs[0]; 92 | if(cxzd.equalsIgnoreCase("ALL")){//all,'',2012-10-7,2012-10-7,未审核 93 | if(strs.length==4){//all,'',2012-10-7,2012-10-7 94 | record.set("btime", strs[2],MDate.get_min_day()); 95 | record.set("etime", strs[3],MDate.get_max_day()); 96 | } if(strs.length==5){////all,'',2012-10-7,2012-10-7,未审核 97 | record.set("btime", strs[2],MDate.get_min_day()); 98 | record.set("etime", strs[3],MDate.get_max_day()); 99 | record.set("select_name",strs[4]); 100 | } 101 | }else{ //bh,'001',2012-10-7,2012-10-7,未审核 102 | if(strs.length==4){ //bh,'001',2012-10-7,2012-10-7 103 | record.set("cxzd", strs[0],"ALL"); 104 | record.set("cxnr", MTool.UTF8(strs[1])); 105 | record.set("btime", strs[2],MDate.get_min_day()); 106 | record.set("etime", strs[3],MDate.get_max_day()); 107 | }else if(strs.length==5){ 108 | record.set("cxzd", strs[0],"ALL"); 109 | record.set("cxnr", MTool.UTF8(strs[1])); 110 | record.set("btime", strs[2],MDate.get_min_day()); 111 | record.set("etime", strs[3],MDate.get_max_day()); 112 | record.set("select_name",strs[4]); 113 | } 114 | } 115 | if(strs.length==2){ 116 | record.set("cxzd", strs[0]); 117 | record.set("cxnr", MTool.UTF8(strs[1])); 118 | } 119 | } 120 | }else{ 121 | record.set("cxzd", MR.me().getPara("cxzd"),"ALL"); 122 | record.set("cxnr", MR.me().getPara("cxnr")); 123 | record.set("btime",MR.me().getPara("btime"), MDate.get_year()+"-01-01");//, 124 | record.set("etime",MR.me().getPara("etime"),MDate.get_max_day());// 125 | } 126 | 127 | 128 | return record; 129 | } 130 | /** 131 | * 读取list 页面的共同信息(下拉框值,时间框) 132 | */ 133 | public static MRecord get_common_list_value(String tableName,Integer seq){ 134 | MRecord record=getFindValueByURI(seq); 135 | MR.me().setAttr(Msg.OBJECT, record); 136 | MR.me().setAttr(Msg.FIND_STR, record.get("cxzd")+","+record.get("cxnr")+","+record.getStr("btime")+","+record.getStr("etime")+","+record.getStr("select_name")); 137 | record.set("lst", getDefaultField(tableName)); 138 | return record; 139 | } 140 | public static void get_common_list_value(String tableName){ 141 | MRecord record= get_common_list_value(tableName, null); 142 | MR.me().setAttr(Msg.OBJECT, record); 143 | } 144 | /** 145 | * 146 | * @param timeField 时间字段 147 | * @param select_name 如果有下拉框,则是select 的名称 148 | * @param seq uri中的第几位 welcome(0)/index(1)/xx 149 | * @return 150 | */ 151 | public static String get_find_where(String timeField,String select_name,Integer seq){ 152 | MRecord record=getFindValueByURI(seq); 153 | MR.me().setAttr(Msg.FIND_STR, record.get("cxzd")+","+record.get("cxnr")+","+record.getStr("btime")+","+record.getStr("etime")+","+record.getStr("select_name")); 154 | return getWhereFieldByDefault(timeField,select_name,record); 155 | } 156 | public static String get_find_where(String timeField,String select_name){ 157 | return get_find_where(timeField,select_name, 3); 158 | } 159 | public static String get_find_where(String timeField){ 160 | return get_find_where(timeField,null, 3); 161 | } 162 | /** 163 | * @param select_name 列表页面进行检索的下拉字段,如,未审核,同意,已审核 164 | */ 165 | private static String getWhereFieldByDefault(String timeField,String select_name,MRecord record){ 166 | String where=""; 167 | if(!MCheck.isNull(timeField)){//列表页面没有时间检索 168 | where=getTimesByURI(timeField, record); 169 | } 170 | if(!MCheck.isNull(record)){ 171 | where+=getFieldLike(record.getStr("cxzd"), record.getStr("cznr")); 172 | where+=getSelectEQ(select_name,record.get("select_name")); 173 | } 174 | return where; 175 | 176 | } 177 | private static String getSelectEQ(String zt,Object select_name) { 178 | return !MCheck.isNull(select_name)&&!MCheck.isNull(zt)?MCnt.me().and(zt, MEnum.EQ, select_name).toStr():""; 179 | } 180 | 181 | private static String getFieldLike(String cxzd,String cxnr){ 182 | String where=""; 183 | if(MCheck.isNull(cxzd)){ 184 | cxzd=MR.me().getPara("cxzd"); 185 | } 186 | if(MCheck.isNull(cxnr)){ 187 | cxnr=MR.me().getPara("cxnr"); 188 | } 189 | if(!MCheck.isNull(cxzd)&&!MCheck.isNull(cxnr)&&!"ALL".equalsIgnoreCase(cxzd)){ 190 | where=MCnt.me().like(cxzd, cxnr).toStr(); 191 | } 192 | return where; 193 | 194 | } 195 | private static String getTimesByURI(String timeField,MRecord record){ 196 | String btime=MR.me().getPara("btime"); 197 | String etime=MR.me().getPara("etime"); 198 | if(MCheck.isNull(btime)&&MCheck.isNull(etime)&&!MCheck.isNull(record)){ 199 | btime=record.getStr("btime"); 200 | etime=record.getStr("etime"); 201 | } 202 | MCnt cnt=MCnt.me(); 203 | if(!MCheck.isNull(btime)){ 204 | cnt.and(timeField, MEnum.GT_E, btime); 205 | } 206 | if(!MCheck.isNull(etime)){ 207 | cnt.and(timeField, MEnum.LT_E, etime); 208 | } 209 | return cnt.toStr(); 210 | } 211 | /** 212 | * 213 | * @param orders 如果在list页面点击了排序, 则会替换掉原先的排序 214 | * @return 215 | */ 216 | public static Object[] getOrderBy(Integer seg,Object ...orders){ 217 | String order=MURI.me().seg_str(seg); 218 | if(!MCheck.isNull(order)){ 219 | String strs[]=order.split("_"); 220 | if(strs.length>1){ 221 | orders=new Object[]{"order by "+strs[0]+" "+strs[1]}; 222 | } 223 | } 224 | MR.me().setAttr(Msg.ORDER_STR,order); 225 | return orders; 226 | } 227 | } 228 | --------------------------------------------------------------------------------