shyboy0932

adb logcat 看看手机里发生了什么

手机连上,别着急,运行adb root;adb shell看看,如果手机上有权限管理的工具,应该要出现提示,允许它


adb logcat >a.txt

充电电压

一般蓄电池充电是采用两种方式,即恒压充电和恒流充电,专业常用的是恒流充电,普通充电是常用恒压充电,充电电压一般为电池电压的1.2倍,充电电流一般常用电池容量的10%,比如10Ah的电瓶,就用1A的电流来充,这是标准充电电流,如果想快速充电,充电电流不得大于电瓶容量的30%,否则容易使电瓶极板加速老化,降低电瓶的使用寿命。 充电时间:采用10%的充电方式,充电时间我10小时,常用30%的充电方式充电时间约为3个小时。 提示:充电电流越小,电池寿命越长,当然充电时间就越长。


[转]修改CAS实现控制某个用户在定义的时间内登录次数

原文

http://blog.csdn.net/zhurhyme/article/details/33386503   cas大全

在数据库增加字段  1.登录次数 2.登录失败时间(类型TimeStamp)

当一个用户进来认证的时候当登录失败的时候更新登录次数 和最后登录失败的时间。

主要是在登录成功或者失败的时候判断时间差是不是大于定义的时间,要数大于得话得更新登陆次数和失败时间。

成功的时候把登陆次数更新,而不更新登录错误时间

登录失败的时候把登陆次数更新为最大次数减一,把错误时间更新到当前。

 

具体在CAS中的实现

修改web-flow 验证路口:先修改配置文件cas-servlet.xml


[java] view plaincopy

  1. 把  

  2. <bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"  

  3.         p:centralAuthenticationService-ref="centralAuthenticationService"  

  4.         p:warnCookieGenerator-ref="warnCookieGenerator"/>  

  5. 改成:  

  6. <bean id="authenticationViaFormAction" class="flow.AuthenticationViaFormAction"  

  7.         p:centralAuthenticationService-ref="centralAuthenticationService"  

  8.         p:dataSource-ref = "casDataSource"//数据源  

  9.         p:warnCookieGenerator-ref="warnCookieGenerator"/>  


 

定义flow.AuthenticationViaFormAction类  原cas-server-core-3.3.3.jar中类


[java] view plaincopy

  1. package flow;  

  2.   

  3. import java.io.IOException;  

  4. import java.sql.Timestamp;  

  5. import java.util.ArrayList;  

  6. import java.util.List;  

  7. import java.util.Map;  

  8.   

  9. import javax.servlet.http.HttpServletRequest;  

  10. import javax.servlet.http.HttpServletResponse;  

  11. import javax.sql.DataSource;  

  12.   

  13. import org.inspektr.common.ioc.annotation.NotNull;  

  14. import org.jasig.cas.CentralAuthenticationService;  

  15. import org.jasig.cas.authentication.handler.AuthenticationException;  

  16. import org.jasig.cas.authentication.principal.Credentials;  

  17. import org.jasig.cas.authentication.principal.Service;  

  18. import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;  

  19. import org.jasig.cas.ticket.TicketException;  

  20. import org.jasig.cas.validation.UsernamePasswordCredentialsValidator;  

  21. import org.jasig.cas.web.bind.CredentialsBinder;  

  22. import org.jasig.cas.web.support.WebUtils;  

  23. import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;  

  24. import org.springframework.util.Assert;  

  25. import org.springframework.util.StringUtils;  

  26. import org.springframework.validation.DataBinder;  

  27. import org.springframework.validation.Errors;  

  28. import org.springframework.web.util.CookieGenerator;  

  29. import org.springframework.webflow.action.FormAction;  

  30. import org.springframework.webflow.execution.Event;  

  31. import org.springframework.webflow.execution.RequestContext;  

  32.   

  33.   

  34. public class AuthenticationViaFormAction extends FormAction  

  35. {  

  36.   private CredentialsBinder credentialsBinder;  

  37.   private SimpleJdbcTemplate jdbcTemplate;  

  38.   private DataSource dataSource;  

  39.   private static int TYPE1 =1;  

  40.   private static int TYPE2 = 2;  

  41.   

  42.   @NotNull  

  43.   private CentralAuthenticationService centralAuthenticationService;  

  44.   

  45.   @NotNull  

  46.   private CookieGenerator warnCookieGenerator;  

  47.   

  48.   protected final void doBind(RequestContext context, DataBinder binder)  

  49.     throws Exception  

  50.   {  

  51.     HttpServletRequest request = WebUtils.getHttpServletRequest(context);  

  52.   

  53.     Credentials credentials = (Credentials)binder.getTarget();  

  54.   

  55.     if (this.credentialsBinder != null) {  

  56.       this.credentialsBinder.bind(request, credentials);  

  57.     }  

  58.   

  59.     super.doBind(context, binder);  

  60.   }  

  61.   

  62.   public Event referenceData(RequestContext context) throws Exception {  

  63.     context.getRequestScope().put("commandName", getFormObjectName());  

  64.     return success();  

  65.   }  

  66.   

  67.   public final Event submit(RequestContext context) throws Exception { Credentials credentials = (Credentials)getFormObject(context);  

  68.   String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);  

  69.   Service service = WebUtils.getService(context);  

  70.   

  71.   if ((StringUtils.hasText(context.getRequestParameters().get("renew"))) && (ticketGrantingTicketId != null) && (service != null));  

  72.   try  

  73.   {  

  74.     if(ticketGrantingTicketId!=null){  

  75.     String serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials);  

  76.     WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);  

  77.     putWarnCookieIfRequestParameterPresent(context);  

  78.     return warn();  

  79.     }  

  80.     else{  

  81.          try  

  82.             {  

  83.               WebUtils.putTicketGrantingTicketInRequestScope(context, this.centralAuthenticationService.createTicketGrantingTicket(credentials));  

  84.   

  85.               putWarnCookieIfRequestParameterPresent(context);  

  86.               return success();  

  87.             } catch (TicketException ex) {  

  88.               populateErrorsInstance(context, ex);   

  89.             }  

  90.     }  

  91.   } catch (TicketException e) {  

  92.     if ((e.getCause() != null) && (AuthenticationException.class.isAssignableFrom(e.getCause().getClass())))  

  93.     {  

  94.       populateErrorsInstance(context, e);  

  95.       return error();  

  96.     }  

  97.     this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);  

  98.   

  99.     if (this.logger.isDebugEnabled()) {  

  100.       this.logger.debug("Attempted to generate a ServiceTicket using renew=true with different credentials", e);  

  101.     }  

  102.   

  103.     try  

  104.     {  

  105.       WebUtils.putTicketGrantingTicketInRequestScope(context, this.centralAuthenticationService.createTicketGrantingTicket(credentials));  

  106.   

  107.       putWarnCookieIfRequestParameterPresent(context);  

  108.       return success();  

  109.     } catch (TicketException ex) {  

  110.       populateErrorsInstance(context, e);   

  111.     }  

  112.   }  

  113.     

  114.     

  115.   return error();  

  116.   }  

  117.   

  118. // add the method of judge the reason of the error :name or password  

  119.   public final Event errorJudge(RequestContext context) throws Exception {  

  120.         List list = new ArrayList();  

  121.         HttpServletResponse response = WebUtils.getHttpServletResponse(context);  

  122.         HttpServletRequest request = WebUtils.getHttpServletRequest(context);  

  123.         Credentials credentials = (Credentials)getFormObject(context);  

  124.         StringBuffer sql = new StringBuffer();  

  125.         sql.append("select id,userName,password,enable,errorTime from user where userName = '");  

  126.         sql.append(((UsernamePasswordCredentials)credentials).getUsername());  

  127.         sql.append("'");  

  128.           

  129.         list = getJdbcTemplate().queryForList(sql.toString());  

  130.         if(list.size()==0){  

  131.             sendMessage(request,response, TYPE1, 0);  

  132.         }else{  

  133.             Map map = (Map)list.get(0);  

  134.               User user = new User();  

  135.               user.setId(new Integer(map.get("id").toString()));  

  136.               user.setPassword(map.get("password").toString());  

  137.               user.setUserName(map.get("userName").toString());  

  138.               user.setDateSpan((Timestamp)(map.get("errorTime")));  

  139.               user.setCount(new Integer(map.get("enable").toString()));  

  140.             sendMessage(request,response, TYPE2, user.getCount());  

  141.         }  

  142.          return success();  

  143.           

  144.   }  

  145.     

  146.   public String sendMessage(HttpServletRequest request,HttpServletResponse response,int type,int count) throws IOException{  

  147.         

  148.         

  149.       StringBuffer str = new StringBuffer();  

  150.       str.append("{");  

  151.       str.append("status : /"false/",");  

  152.       if(type==TYPE1){  

  153.           str.append("errorMessage : /" your userName Error");  

  154.       }else if(type==TYPE2){  

  155.           if(count!=0){  

  156.               str.append("errorMessage : /" your password Error");  

  157.               str.append("please retry");  

  158.               str.append("you left ");  

  159.               str.append(count);  

  160.               str.append("Times to login!");  

  161.           }else{  

  162.               str.append("errorMessage : /" your have try 5 time in 30 mins so please after 30mins");  

  163.           }  

  164.             

  165.       }else{  

  166.             

  167.       }  

  168.       str.append("/"}");  

  169.       request.setAttribute("string", str);  

  170.       System.out.println(str.toString());  

  171.       return str.toString();  

  172.         

  173.      // response.getWriter().write(str.toString());  

  174.   }  

  175.     

  176.     

  177.     

  178.   public DataSource getDataSource() {  

  179.     return dataSource;  

  180. }  

  181.   

  182. public void setDataSource(DataSource dataSource) {  

  183.     this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);  

  184.     this.dataSource = dataSource;  

  185. }  

  186.   

  187. public SimpleJdbcTemplate getJdbcTemplate() {  

  188.     return jdbcTemplate;  

  189. }  

  190.   

  191. public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {  

  192.     this.jdbcTemplate = jdbcTemplate;  

  193. }  

  194.   

  195. public CredentialsBinder getCredentialsBinder() {  

  196.     return credentialsBinder;  

  197. }  

  198.   

  199. public CentralAuthenticationService getCentralAuthenticationService() {  

  200.     return centralAuthenticationService;  

  201. }  

  202.   

  203. public CookieGenerator getWarnCookieGenerator() {  

  204.     return warnCookieGenerator;  

  205. }  

  206.   

  207. private final Event warn()  

  208.   {  

  209.     return result("warn");  

  210.   }  

  211.   

  212.   private final void populateErrorsInstance(RequestContext context, TicketException e)  

  213.   {  

  214.     Errors errors;  

  215.     try {  

  216.       errors = getFormErrors(context);  

  217.       errors.reject(e.getCode(), e.getCode());  

  218.     } catch (Exception fe) {  

  219.       this.logger.error(fe, fe);  

  220.     }  

  221.   }  

  222.   

  223.   private void putWarnCookieIfRequestParameterPresent(RequestContext context)  

  224.   {  

  225.     HttpServletResponse response = WebUtils.getHttpServletResponse(context);  

  226.   

  227.     if (StringUtils.hasText(context.getExternalContext().getRequestParameterMap().get("warn")))  

  228.     {  

  229.       this.warnCookieGenerator.addCookie(response, "true");  

  230.     }  

  231.     else this.warnCookieGenerator.removeCookie(response);  

  232.   }  

  233.   

  234.   public final void setCentralAuthenticationService(CentralAuthenticationService centralAuthenticationService)  

  235.   {  

  236.     this.centralAuthenticationService = centralAuthenticationService;  

  237.   }  

  238.   

  239.   public final void setCredentialsBinder(CredentialsBinder credentialsBinder)  

  240.   {  

  241.     this.credentialsBinder = credentialsBinder;  

  242.   }  

  243.   

  244.   public final void setWarnCookieGenerator(CookieGenerator warnCookieGenerator) {  

  245.     this.warnCookieGenerator = warnCookieGenerator;  

  246.   }  

  247.   

  248.   protected void initAction() {  

  249.     if (getFormObjectClass() == null) {  

  250.       setFormObjectClass(UsernamePasswordCredentials.class);  

  251.       setFormObjectName("credentials");  

  252.       setValidator(new UsernamePasswordCredentialsValidator());  

  253.   

  254.       this.logger.info("FormObjectClass not set.  Using default class of " + getFormObjectClass().getName() + " with formObjectName " + getFormObjectName() + " and validator " + getValidator().getClass().getName() + ".");  

  255.     }  

  256.   

  257.     Assert.isTrue(Credentials.class.isAssignableFrom(getFormObjectClass()), "CommandClass must be of type Credentials.");  

  258.   

  259.     if (this.credentialsBinder != null)  

  260.       Assert.isTrue(this.credentialsBinder.supports(getFormObjectClass()), "CredentialsBinder does not support supplied FormObjectClass: " + getClass().getName());  

  261.   }  

  262.   

  263.   

  264. }  


 

然后修改真正验证的核心类QueryDatabaseAuthenticationHandler  cas-server-support-jdbc-3.3.3.jar包

首先修改deployerConfigContext.xml


[java] view plaincopy

  1. 替换  

  2. <bean class="org.jasig.cas.adaptors.jdbc.QueryDatabaseAuthenticationHandler">  

  3.                 <property name="dataSource" ref="casDataSource" />   

  4.                 <property name="sql" value="select password from user where lower(userName) = lower(?)" />   

  5.   

  6. 为  

  7. <bean class="flow.QueryDatabaseAuthenticationHandler">  

  8.                 <property name="dataSource" ref="casDataSource" />  

  9.                 <property name="sql" value="select id,userName,password,enable,errorTime from user where lower(userName) = lower(?)" />   

  10.                 </bean>   


 

新建自定义类QueryDatabaseAuthenticationHandler

 


[java] view plaincopy

  1. package flow;  

  2.   

  3.   

  4. import java.sql.Date;  

  5. import java.sql.Timestamp;  

  6. import java.util.ArrayList;  

  7. import java.util.List;  

  8. import java.util.Map;  

  9.   

  10. import org.inspektr.common.ioc.annotation.NotNull;  

  11. import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;  

  12. import org.jasig.cas.authentication.handler.AuthenticationException;  

  13. import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;  

  14. import org.springframework.dao.IncorrectResultSizeDataAccessException;  

  15.   

  16. public final class QueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler  

  17. {  

  18.   

  19.   @NotNull  

  20.   private String sql;  

  21.   private static long MIN = 60000;  

  22.   private static int STATIC_COUNT = 5;  

  23.   private static int TYPE_1 = 1;  

  24.   private static int TYPE_2 = 2;  

  25.     

  26.   protected final boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials)  

  27.     throws AuthenticationException  

  28.   {  

  29.     String username = credentials.getUsername();  

  30.     String password = credentials.getPassword();  

  31.     String encryptedPassword = getPasswordEncoder().encode(password);  

  32.     

  33.       String sql_temp = "select id,userName,password,enable,errorTime from user where userName = '"+username+"'";  

  34.       Map map = queryDB(sql_temp);  

  35.       if(map==null)  

  36.           return false;  

  37.       User user = cabineUser(map);  

  38.       //new build start  

  39.             if(isTimeOverVaildate(user.getDateSpan())){  

  40.                   update(STATIC_COUNT, user.getId(), TYPE_2);  

  41.                   User user_temp = cabineUser(queryDB(sql_temp));  

  42.                   return passwordVaildateLogic(user_temp,encryptedPassword);  

  43.             }else{  

  44.                 if(user.getCount()>0){  

  45.                   return passwordVaildateLogic(user,encryptedPassword);  

  46.                 }else{  

  47.                     return false;  

  48.                 }  

  49.             }  

  50.       //new build end  

  51.           

  52.   }  

  53.     

  54.   //common password vaildate logic  

  55.   public boolean passwordVaildateLogic(User user,String encryptedPassword){  

  56.       if(passwordVaildate(user, encryptedPassword)){  

  57.           return true;  

  58.       }else{  

  59.           update(user.getCount()-1,user.getId(), TYPE_2);  

  60.           return false;  

  61.       }  

  62.   }  

  63.     

  64.   //password vaildate action  

  65.   public boolean passwordVaildate(User user,String encryptedPassword){  

  66.       return user.getPassword().equals(encryptedPassword);  

  67.   }  

  68.   //query the map in DB  

  69.   public Map queryDB(String sql){  

  70.       List list = new ArrayList();  

  71.       list = getJdbcTemplate().queryForList(sql);  

  72.        if(list.size()==0)  

  73.               return null;  

  74.        return (Map)list.get(0);  

  75.   }  

  76.     

  77.   //cabine the user  

  78.   public User cabineUser(Map map){  

  79.       User user = new User();  

  80.         user.setId(new Integer(map.get("id").toString()));  

  81.         user.setPassword(map.get("password").toString());  

  82.         user.setUserName(map.get("userName").toString());  

  83.         user.setDateSpan((Timestamp)(map.get("errorTime")));  

  84.         user.setCount(new Integer(map.get("enable").toString()));  

  85.       return user;  

  86.   }  

  87.     

  88.   //update time(type1) or time and count(type2) @param count,type   

  89.   public void update(int count,int id,int type){  

  90.       String sqlUpdate_type1 = "UPDATE user SET enable = ? WHERE id = ?";  

  91.       String sqlUpdate_type2 = "UPDATE user SET enable = ?,errorTime=? WHERE id = ?";  

  92.       if(type ==1){  

  93.           Object param[] = new Object[] {count,id};    

  94.           getJdbcTemplate().update(sqlUpdate_type1, param);  

  95.       }else if(type ==2){  

  96.           Object param[] = new Object[] {count,new Timestamp(System.currentTimeMillis()),id};    

  97.           getJdbcTemplate().update(sqlUpdate_type2, param);  

  98.       }  

  99.  }  

  100.   //is time over 30min @param Date  

  101.   public boolean isTimeOverVaildate(Timestamp date){  

  102.       long time1 = System.currentTimeMillis();  

  103.       long time2 = date.getTime();  

  104.       if(System.currentTimeMillis()-date.getTime()>30*MIN)  

  105.           return true;  

  106.       return false;  

  107.   }  

  108.   

  109. public void setSql(String sql)  

  110.   {  

  111.     this.sql = sql;  

  112.   }  

  113.   

  114.   

  115.   public String getSql() {  

  116.     return sql;  

  117.   }  

  118. }  


 

 

最后修改 simple-loginflow.xml中的一个FLOW结果,这是我自己的自定义flow 其他的可以类似的改。

 

[java] view plaincopy

  1. <action-state id="submit">  

  2.         <action bean="authenticationViaFormAction" method="submit" />  

  3.         <transition on="success" to="sendTicketGrantingTicket" />  

  4.         <transition on="error" to="errorJudge" />  

  5.     </action-state>  

  6.       

  7.       

  8.     <action-state id="errorJudge">  

  9.         <action bean="authenticationViaFormAction"  method="errorJudge"/>  

  10.         <transition on="success" to="statusErrorCallbackView6"/>  

  11.     </action-state>  


 

statusErrorCallbackView6中的内容为


[java] view plaincopy

  1. <%     

  2.     response.getWriter().write(request.getAttribute("string").toString());  

  3. %>  

  4.   

  5. 其中的getAttribute("string")是在AuthenticationViaFormAction的sendMessage(这个方法在errorJudge里面有调用)方法里设的这个sendmessage就是把json格式的的信息放到request中。当页面返回时候得到那个属性的值。  


 

这就是全部配置

 

 

 


cas 的 http://....../sdf.action?ticket=.........类网址

产生原因是因为CAS授权的链接的Ticket是有次数限制和时间限制,如果不修改配置,默认的Ticket只能使用一次,10秒就会过期,所以,基本上一刷页面就会碰到这个错误.


将里面的这句修改一下:

    <bean id="serviceTicketExpirationPolicy" class="org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy"
          c:numberOfUses="1" c:timeToKill="${st.timeToKillInSeconds:10}" c:timeUnit-ref="SECONDS"/>

修改后:

    <bean id="serviceTicketExpirationPolicy" class="org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy"
          c:numberOfUses="2" c:timeToKill="${st.timeToKillInSeconds:100}" c:timeUnit-ref="SECONDS"/>

这样Ticket就能刷两次,过期时间也延长到100秒了。



[转]Postgres的日志实用功能

不得不说,Postgres的日志(pg_log,类似oracle的alter文件,非pg_xlog)确实是很灵活,功能也很丰富的,下面是借用postgres的日志来实现一些管理功能,下面涉及的参数都在文件$PGDATA/postgresql.conf里面。 

OS:CentOS 6.2 
DB:Postgres 9.2.3 

1.日志审计 
审计是值记录用户的登陆退出以及登陆后在数据库里的行为操作,可以根据安全等级不一样设置不一样级别的审计, 
此处涉及的参数文件有:

logging_collector --是否开启日志收集开关,默认off,开启要重启DBlog_destination --日志记录类型,默认是stderr,只记录错误输出log_directory --日志路径,默认是$PGDATA/pg_loglog_filename --日志名称,默认是postgresql-%Y-%m-%d_%H%M%S.loglog_connections --用户session登陆时是否写入日志,默认offlog_disconnections --用户session退出时是否写入日志,默认offlog_rotation_age --保留单个文件的最大时长,默认是1d,也有1h,1min,1s,个人觉得不实用log_rotation_size --保留单个文件的最大尺寸,默认是10MB

配置值:

logging_collector = onlog_destination = 'csvlog'log_directory = '/home/postgres/pg_log'log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'log_connections = onlog_disconnections = onlog_rotation_age = 1dlog_rotation_size = 20MB

配置完重启DB,检查日志情况

[postgres@localhost pg_log]$ ls -ltotal 4-rw-------. 1 postgres postgres 672 Mar 29 08:25 postgresql-2013-03-29_000000.csv-rw-------. 1 postgres postgres 0 Mar 29 00:00 postgresql-2013-03-29_000000.log[postgres@localhost pg_log]$ --登陆并退出,日志内容有访问的IP(local),访问用户,登陆和退出时间等信息,对检查超级用户的登陆退出是很有效的[postgres@localhost pg_log]$ psqlpsql (9.2.3)Type "help" for help.postgres=# \q[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv 2013-03-29 10:38:36.934 PDT,,,2236,"",5155d19c.8bc,1,"",2013-03-29 10:38:36 PDT,,0,LOG,00000,"connection received: host=[local]",,,,,,,,,""2013-03-29 10:38:36.938 PDT,"postgres","postgres",2236,"[local]",5155d19c.8bc,2,"authentication",2013-03-29 10:38:36 PDT,2/11858,0,LOG,00000,"connection authorized: user=postgres database=postgres",,,,,,,,,""2013-03-29 10:38:42.365 PDT,"postgres","postgres",2236,"[local]",5155d19c.8bc,3,"idle",2013-03-29 10:38:36 PDT,,0,LOG,00000,"disconnection: session time: 0:00:05.431 user=postgres database=postgres host=[local]",,,,,,,,,"psql"

记录用户登陆数据库后的各种操作,postgres日志里分成了3类,通过参数pg_statement来控制,默认的pg_statement参数值是none,即不记录,可以设置ddl(记录create,drop和alter)、mod(记录ddl+insert,delete,update和truncate)和all(mod+select)。 

示例: 
[postgres@localhost ~]$ vi $PGDATA/postgresql.conf 
log_statement = ddl

postgres=# show log_statement; log_statement --------------- ddl(1 row)postgres=# create table t_ken_yon(id int);CREATE TABLEpostgres=# drop table t_ken_yon ;DROP TABLEpostgres=# [postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv 2013-03-29 11:01:29.048 PDT,"postgres","postgres",2324,"[local]",5155d681.914,3,"idle",2013-03-29 10:59:29 PDT,2/11945,0,LOG,00000,"statement: create table t_ken_yon(id int);",,,,,,,,,"psql"2013-03-29 11:01:36.087 PDT,"postgres","postgres",2324,"[local]",5155d681.914,4,"idle",2013-03-29 10:59:29 PDT,2/11948,0,LOG,00000,"statement: drop table t_ken_yon ;",,,,,,,,,"psql"--修改为mod级别,并reloadpostgres=# show log_statement; log_statement --------------- mod(1 row)postgres=# insert into t_ken_yon values(1),(2);INSERT 0 2postgres=# delete from t_ken_yon where id =1;DELETE 1[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv2013-03-29 11:04:08.148 PDT,,,5554,,514933a6.15b2,42,,2013-03-19 20:57:26 PDT,,0,LOG,00000,"received SIGHUP, reloading configuration files",,,,,,,,,""2013-03-29 11:04:08.151 PDT,,,5554,,514933a6.15b2,43,,2013-03-19 20:57:26 PDT,,0,LOG,00000,"parameter ""log_statement"" changed to ""mod""",,,,,,,,,""2013-03-29 11:05:33.346 PDT,"postgres","postgres",2324,"[local]",5155d681.914,6,"idle",2013-03-29 10:59:29 PDT,2/11952,0,LOG,00000,"statement: insert into t_ken_yon values(1),(2);",,,,,,,,,"psql"2013-03-29 11:05:52.033 PDT,"postgres","postgres",2324,"[local]",5155d681.914,7,"idle",2013-03-29 10:59:29 PDT,2/11953,0,LOG,00000,"statement: delete from t_ken_yon where id =1;",,,,,,,,,"psql"--修改为all级别,并reloadpostgres=# show log_statement; log_statement --------------- all(1 row)postgres=# select * from t_ken_yon; id ---- 2(1 row)[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv 2013-03-29 11:07:14.820 PDT,,,5554,,514933a6.15b2,44,,2013-03-19 20:57:26 PDT,,0,LOG,00000,"received SIGHUP, reloading configuration files",,,,,,,,,""2013-03-29 11:07:14.821 PDT,,,5554,,514933a6.15b2,45,,2013-03-19 20:57:26 PDT,,0,LOG,00000,"parameter ""log_statement"" changed to ""all""",,,,,,,,,""2013-03-29 11:07:19.784 PDT,"postgres","postgres",2324,"[local]",5155d681.914,8,"idle",2013-03-29 10:59:29 PDT,2/11954,0,LOG,00000,"statement: show log_statement;",,,,,,,,,"psql"2013-03-29 11:07:28.631 PDT,"postgres","postgres",2324,"[local]",5155d681.914,9,"idle",2013-03-29 10:59:29 PDT,2/11955,0,LOG,00000,"statement: select * from t_ken_yon;",,,,,,,,,"psql"

一般的OLTP系统审计级别设置为ddl就够了,因为记录输出各种SQL对性能的影响还是蛮大的,安全级别高一点的也可以设置mod模式,有条件也可以不在数据库层面做,而是购买设备放在网络层监控解析。 

  2.定位慢查询SQL 
可以设置一定时长的参数(log_min_duration_statement),来记录超过该时长的所有SQL,对找出当前数据库的慢查询很有效。 比如log_min_duration_statement = 2s,记录超过2秒的SQL,改完需要reload 

示例:

postgres=# show log_min_duration_statement ; log_min_duration_statement ---------------------------- 2s(1 row)postgres=# \timing Timing is on.postgres=# select now(),pg_sleep(1); now | pg_sleep ------------------------------+---------- 2013-03-29 12:36:48.13353-07 | (1 row)Time: 1001.844 mspostgres=# select now(),pg_sleep(4); now | pg_sleep -------------------------------+---------- 2013-03-29 12:36:28.309595-07 | (1 row)Time: 4002.273 ms[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv 2013-03-29 12:36:19.265 PDT,"postgres","postgres",2324,"[local]",5155d681.914,10,"SELECT",2013-03-29 10:59:29 PDT,2/0,0,LOG,00000,"duration: 4027.183 ms statement: select now(),pg_sleep(4);",,,,,,,,,"psql"

可以看到只记录了4秒的那个SQL,而没有记录1秒的SQL。 

3.监控数据库的checkpoint 
当数据库进行一项大更新操作时,如果参数设置不当,会在日志里留下大量的告警信息,频繁的做checkpoint会导致系统变慢,如:

2013-03-28 17:01:39.523 CST,,,10350,,50bd676b.286e,1,,2012-12-04 11:00:59 CST,,0,LOG,00000,"checkpoints are occurring too frequently (8 seconds apart)",,"Consider increasing the configuration parameter ""checkpoint_segments"".",,,,,,,""2013-03-28 17:01:50.427 CST,,,10350,,50bd676b.286e,2,,2012-12-04 11:00:59 CST,,0,LOG,00000,"checkpoints are occurring too frequently (11 seconds apart)",,"Consider increasing the configuration parameter ""checkpoint_segments"".",,,,,,,""

但是不会记录系统正常的checkpoint,如果你想看系统一天之类发生了多少次checkpoint,以及每次checkpoint的一些详细信息,比如buffer,sync等,就可以通过设置log_checkpoints,该参数默认值是off,修改log_checkpoints = on 示例:

postgres=# show log_checkpoints ; log_checkpoints ----------------- on(1 row)postgres=# checkpoint;CHECKPOINTpostgres=#[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv 2013-03-29 12:43:38.900 PDT,,,5557,,514933a7.15b5,45,,2013-03-19 20:57:27 PDT,,0,LOG,00000,"checkpoint starting: immediate force wait",,,,,,,,,""2013-03-29 12:43:38.941 PDT,,,5557,,514933a7.15b5,46,,2013-03-19 20:57:27 PDT,,0,LOG,00000,"checkpoint complete: wrote 0 buffers (0.0%); 0 transaction log file(s) added, 0 removed, 0 recycled; write=0.009 s, sync=0.000 s, total=0.040 s; sync files=0, longest=0.000 s, average=0.000 s",,,,,,,,,""


 4.监控数据库的锁 
数据库的锁通常可以在pg_locks这个系统表里找,但这只是当前的锁表/行信息,如果你想看一天内有多少个超过死锁时间的锁发生,可以在日志里设置并查看,log_lock_waits 默认是off,可以设置开启。这个可以区分SQL慢是资源紧张还是锁等待的问题。 示例:

postgres=# show log_lock_waits ; log_lock_waits ---------------- on(1 row)postgres=# show deadlock_timeout ; deadlock_timeout ------------------ 1s(1 row)--模拟锁postgres=# begin;BEGINpostgres=# SELECT * FROM t_ken_yon ; id ---- 11(1 row)postgres=# delete from t_ken_yon ;DELETE 1--另一个sessionpostgres=# begin;BEGINpostgres=# delete from t_ken_yon;--查看日志[postgres@localhost pg_log]$ tail -f postgresql-2013-03-29_000000.csv2013-03-29 14:01:02.673 PDT,"postgres","postgres",3056,"[local]",5155f4d9.bf0,6,"DELETE waiting",2013-03-29 13:08:57 PDT,5/12502,2659,LOG,00000,"process 3056 still waiting for ShareLock on transaction 2658 after 1000.398 ms",,,,,,"delete from t_ken_yon;",,,"psql"2013-03-29 14:02:06.208 PDT,"postgres","postgres",3056,"[local]",5155f4d9.bf0,7,"DELETE waiting",2013-03-29 13:08:57 PDT,5/12502,2659,LOG,00000,"process 3056 acquired ShareLock on transaction 2658 after 64535.339 ms",,,,,,"delete from t_ken_yon;",,,"psql"2013-03-29 14:02:06.209 PDT,"postgres","postgres",3056,"[local]",5155f4d9.bf0,8,"DELETE",2013-03-29 13:08:57 PDT,5/12502,2659,LOG,00000,"duration: 64536.118 ms statement: delete from t_ken_yon;",,,,,,,,,"psql"

还有一些Debug功能,适合修改源码调试,一般的的系统上并不需要,暂时比较关注的就这些。


查看当前目录空间占用情况 :du -sh ./* | sort -nr

查看当前目录空间占用情况 :du -sh ./* | sort -nr

一次cas 宕机的处理(提示:cas 服务不可得)

/var/lib/tomcat7/work/Catalina 下删除 localhost整个目录

/var/lib/tomcat7/temp下清空


启动tomcat即可


看到“java.io.IOException: 设备上没有空间”,以为空间没有了,难道是inode没有了吗?使用df -i检查下没问题


使用df,看到/dev/mapper/da--vg-root  281767748 267415100      16648  100% /

空间用完了,在根目录下开始命令:du -sh ./* | sort -nr  依次查找哪个目录占用较多,最后发现/var下某个程序的log太大,删除掉,解决



严重: IOException while loading persisted sessions: java.io.EOFException

java.io.EOFException

at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2325)

at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2794)

at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)

at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)

at org.apache.catalina.util.CustomObjectInputStream.<init>(CustomObjectInputStream.java:56)

at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:244)

at org.apache.catalina.session.StandardManager.load(StandardManager.java:202)

at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:489)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5476)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:744)




------------------------------


严重: Exception loading sessions from persistent storage

java.io.EOFException

at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2325)

at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2794)

at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:801)

at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)

at org.apache.catalina.util.CustomObjectInputStream.<init>(CustomObjectInputStream.java:56)

at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:244)

at org.apache.catalina.session.StandardManager.load(StandardManager.java:202)

at org.apache.catalina.session.StandardManager.startInternal(StandardManager.java:489)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5476)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)

at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:744)

-------------------------------------------------------------------


严重: Exception unloading sessions to persistent storage

java.io.IOException: 设备上没有空间

at java.io.FileOutputStream.writeBytes(Native Method)

at java.io.FileOutputStream.write(FileOutputStream.java:345)

at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)

at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)

at java.io.ObjectOutputStream$BlockDataOutputStream.flush(ObjectOutputStream.java:1822)

at java.io.ObjectOutputStream.flush(ObjectOutputStream.java:718)

at org.apache.catalina.session.StandardManager.doUnload(StandardManager.java:445)

at org.apache.catalina.session.StandardManager.unload(StandardManager.java:351)

at org.apache.catalina.session.StandardManager.stopInternal(StandardManager.java:516)

at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)

at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5655)

at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)

at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1575)

at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1564)

at java.util.concurrent.FutureTask.run(FutureTask.java:262)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)

at java.lang.Thread.run(Thread.java:744)


UEFI+gho+win8.1安装方法

1、使用u盘工具制作可UEFI方式启动的u盘,如http://u.diannaodian.com/,复制一个win8.1gho文件或带有gho的iso文件到u盘

2、bios改成支持UEFI启动的方式,在系统启动时,按f12选择启动菜单,从u盘启动,用分区工具将硬盘分区成gpt分区格式,要先建一个esp启动分区,再建其它的分区,也可使用工具里的快速分区,选择下建esp分区

3、使用win8PE启动,桌面上的电脑店安装工具打开,选择gho,如果是在iso里,也可用,会自动虚拟成光驱盘,自动选择到gho文件,选择下面的修复checkbox



这里有更详细的方法:

http://www.pc841.com/article/20140611-30699.html

openfire 连接实例


        

        if (android.os.Build.VERSION.SDK_INT > 9) {

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            StrictMode.setThreadPolicy(policy);

        }

         ConnectionConfiguration config = new ConnectionConfiguration("chat.lygfls.com", 5222,"mys");

    Connection connection;

    Chat chat = null;

    ServiceDiscoveryManager sdm;

    FileTransferManager filemanager;

     

    /* 这里我们需要特别当心的是先不要告诉openfire服务器你上线了,否则永远也拿不到离线消息

    */ 

    config.setSendPresence(false); 

    config.setReconnectionAllowed(true);

    config.setSecurityMode(SecurityMode.disabled);

    config.setSASLAuthenticationEnabled(false); // true/false

    config.setCompressionEnabled(false);

    connection = new XMPPConnection(config);

    try {


connection.connect();

System.out.println("connection---------->"+connection.isConnected());

if(connection.isConnected()){

connection.login("test", "fkegyss");

}


    }catch(Exception e){

    e.printStackTrace();

    Log.i("错误","连接不上服务");

    }

     

     

     

    OfflineMessageManager offlineManager = new OfflineMessageManager(

    connection);

  try {

  Iterator<org.jivesoftware.smack.packet.Message> it = offlineManager

  .getMessages();


  //System.out.println(offlineManager.supportsFlexibleRetrieval());

  System.out.println("离线消息数量: " + offlineManager.getMessageCount());


 

  Map<String,ArrayList<Message>> offlineMsgs = new HashMap<String,ArrayList<Message>>();

 

  while (it.hasNext()) {

  org.jivesoftware.smack.packet.Message message = it.next();

  System.out

  .println("收到离线消息, Received from 【" + message.getFrom()

  + "】 message: " + message.getBody());

 

  String fromUser = message.getFrom().split("/")[0];


  if(offlineMsgs.containsKey(fromUser))

  {

  offlineMsgs.get(fromUser).add(message);

  }else{

  ArrayList<Message> temp = new ArrayList<Message>();

  temp.add(message);

  offlineMsgs.put(fromUser, temp);

  }

  }


  //在这里进行处理离线消息集合......

  Set<String> keys = offlineMsgs.keySet();

  Iterator<String> offIt = keys.iterator();

  while(offIt.hasNext())

  {

  String key = offIt.next();  

         ArrayList<Message> ms = offlineMsgs.get(key);  

   

         for (int i = 0; i < ms.size(); i++) {  

             System.out.println("-->" + ms.get(i));  

         }  

  }

 

 

  offlineManager.deleteMessages();

  } catch (Exception e) {

  e.printStackTrace();

  }

     

 

  Presence presence = new Presence(Presence.Type.available);  

  connection.sendPacket(presence);//上线了  

 

 

  Message message = new Message("admin@chat.lygfls.com" , Type.chat);

        message.setBody("中文玉奇才;村要堙");

        message.setSubject("title");

        message.setProperty("color", "red");

        connection.sendPacket(message);

 

  /*Message newmsg = new Message();   

  newmsg.setTo("shimiso@csdn.shimiso.com");  

  newmsg.setSubject("重要通知");  

  newmsg.setBody("今天下午2点60分有会!");  

  newmsg.setType(Message.Type.headline);// normal支持离线   

  connection.sendPacket(newmsg); */

  /*Message message = new Message("admin@192.168.200.108" , Type.headline);

         message.setBody("通知消息");

         message.setSubject("title");

         message.setProperty("color", "red");

         connection.sendPacket(message);

         */

     

    //Type.headline通知,Type.normal广播

    /* message = new Message("admin@192.168.200.108" , Type.normal);

         //Message message = new Message(sessid, Type.chat);

         message.setBody("广播消息,大家好");

         message.setSubject("title");

         message.setProperty("color", "red");

         connection.sendPacket(message);*/

 

 

  PacketFilter filter = new MessageTypeFilter(Message.Type.chat);

     

  connection.addPacketListener(new PacketListener() {

           public void processPacket(Packet packet) {

               Message message = (Message) packet;

               if (message.getBody() != null) {

                   String fromName = StringUtils.parseBareAddress(message.getFrom());

                   System.out.println("对方发来:[" + message.getBody() + "] from ["

                           + fromName + "]");

                   }

           }

       }, filter);

       

     

    /* 

    PacketFilter filter = new MessageTypeFilter(Message.Type.chat);

       connection.addPacketListener(new PacketListener() {

           public void processPacket(Packet packet) {

               Message message = (Message) packet;

               if (message.getBody() != null) {

                   String fromName = StringUtils.parseBareAddress(message.getFrom());

                   System.out.println("Got text [" + message.getBody() + "] from ["

                           + fromName + "]");

                   }

           }

       }, filter);

    if(null == chat){

chat = connection.getChatManager().createChat("admin@192.168.200.108", new MessageListener(){

public void processMessage(Chat arg0, Message arg1) {

System.out.println("lg:"+arg1.getLanguage()+":message2-------------------->"+arg1.getBody()+":"+arg1.getFrom());

}

});

}

    try {

    Message message2 = new Message();

    //message.setProperty(IMMessage.KEY_TIME, time);

    message2.setBody("boydsddddddddddddddddddd");

    chat.sendMessage(message2);//这种可发离线消息

//chat.sendMessage("你好");//这种不能发离线消息

connection.disconnect();

} catch (XMPPException e) {

e.printStackTrace();

}*/