2011-7-1

how to get Classpath or path of .class file

in servlet:
String path = getServletContext().getRealPath("/");

in every class:
this.getClass().getClassLoader().getResource("/").getPath();
OR  getClass().getResource("/").getPath();
 in jsp:
request.getContextPath();
get all classpath:
System.getProperty("java.class.path")
 


--
we drink green tea

google+ is cool

google+ is cool
View or comment on green tea iceam china's post »
The Google+ project is currently working out all the kinks with a small group of testers. If you're not able to access Google+, please check back again soon.
Learn more about Google+
You received this message because green tea iceam china shared it with bbzhouxinxin.green@blogger.com. Unsubscribe from these emails.

2011-6-29

3-ways to get a Google+ invitation


First, to ask people you know to get a invitation. If people around you don't have it, Search it at Twitter. There are people who announce that they had get invitation.
second ,to buy one . but it's not encouraged.
third ,wait at google .

By the way, I just get a invitation by the first, and I create a account and I find it's every cool. If you interest in it, leave me a message.
I will send you a invitation .

cheers  good luck

--
we drink green tea

how to get google+ invitation

Google+ have  allowed  users to invite friends. So you can get google+ invitation by other besides Google .

lifehacker had started a thread for handing out invitation. it's here.

note: Google+ is so welcomed,you can't expect get it immediately.

there is the rule of the thread:

  1. Post a reply to a thread once with your email address.
  2. Only post once.
  3.  be patient
  4.  If you get an invite, give other people who is at the thread

cheers good luck


--
we drink green tea

sax与dom的区别

基于事件驱动的解析接口 SAX (实例一) SAX vs. DOM DOM是基于树结构的一种接口;SAX是基于事件驱动的解析接口。 有什么区别呢? 1、SAX 可以解析任意大小的文件,而 DOM 解析的文件大小则和硬件有关。DOM 需要将整个文件加载到内存,而 SAX 不需要。 2、因为 SAX 是不把文件加载到内存,所以不能对文档进行随机存取;而 DOM 可以做到。 3、SAX 相对 DOM 来说是简单易用。 4、如果要从文档的简单系列中获取信息,SAX 是最快的方法。

--
we drink green tea

2011-6-28

how to get google+ invitation


  1. Google+ Invitation.
  2.  
  3. LIKE this Facebook page, and I will send a Google+ Invitation ASAP.
  4.  
  5.  
  6.  
  7. Cheers.
-- I am not sure if  it works,just try
we drink green tea

PreparedStatement的用法(转)

PreparedStatement的用法(转)

关键字: jdbc
jdbc(java database connectivity,java数据库连接)的api中的主要的四个类之一的java.sql.statement要求开发者付出大量的时间和精力。在使用statement获取jdbc访问时所具有的一个共通的问题是输入适当格式的日期和时间戳:2002-02-05 20:56 或者 02/05/02 8:56 pm。 
通过使用java.sql.preparedstatement,这个问题可以自动解决。一个preparedstatement是从java.sql.connection对象和所提供的sql字符串得到的,sql字符串中包含问号(?),这些问号标明变量的位置,然后提供变量的值,最后执行语句,例如: 
stringsql = "select * from people p where p.id = ? and p.name = ?";
preparedstatement ps = connection.preparestatement(sql);
ps.setint(1,id);
ps.setstring(2,name);
resultset rs = ps.executequery(); 
使用preparedstatement的另一个优点是字符串不是动态创建的。下面是一个动态创建字符串的例子: 
stringsql = "select * from people p where p.i = "+id; 

这允许jvm(javavirtual machine,java虚拟机)和驱动/数据库缓存语句和字符串并提高性能。
preparedstatement也提供数据库无关性。当显示声明的sql越少,那么潜在的sql语句的数据库依赖性就越小。
由于preparedstatement具备很多优点,开发者可能通常都使用它,只有在完全是因为性能原因或者是在一行sql语句中没有变量的时候才使用通常的statement。
一个完整的preparedstatement的例子:
java 代码
  1. package jstarproject;   
  2. import java.sql.*;   
  3. public class mypreparedstatement {   
  4. private final string db_driver="com.microsoft.jdbc.sqlserver.sqlserverdriver";   
  5. private final string url = "jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=pubs";   
  6. public mypreparedstatement()    
  7. {   
  8. }   
  9. public void query() throws sqlexception{   
  10. connection conn = this.getconnection();   
  11. string strsql = "select emp_id from employee where emp_id = ?";   
  12. preparedstatement pstmt = conn.preparestatement(strsql);   
  13. pstmt.setstring(1,"pma42628m");   
  14. resultset rs = pstmt.executequery();   
  15.   
  16. while(rs.next()){   
  17. string fname = rs.getstring("emp_id");   
  18. system.out.println("the fname is " + fname);   
  19. }   
  20. rs.close();   
  21. pstmt.close();   
  22. conn.close();   
  23. }   
  24. private connection getconnection() throws sqlexception{   
  25. // class.   
  26. connection conn = null;   
  27. try {   
  28. class.forname(db_driver);   
  29. conn = drivermanager.getconnection(url,"sa","sa");   
  30. }   
  31. catch (classnotfoundexception ex) {}   
  32. return conn;   
  33. }   
  34. //main   
  35. public static void main(string[] args) throws sqlexception {   
  36. mypreparedstatement jdbctest1 = new mypreparedstatement();   
  37. jdbctest1.query();   
  38. }   
  39. }   


为什么要始终使用PreparedStatement代替Statement?为什么要始终使用PreparedStatement代替Statement?


在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement.
基于以下的原因:
一.代码的可读性和可维护性.
虽然用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无论从可读性还是可维护性上来说.都比直接用Statement的代码高很多档次:

java 代码
  1. stmt.executeUpdate("insert into tb_name (col1,col2,col2,col4) values ('"+var1+"','"+var2+"',"+var3+",'"+var4+"')");   
  2.   
  3. perstmt = con.prepareStatement("insert into tb_name (col1,col2,col2,col4) values (?,?,?,?)");   
  4. perstmt.setString(1,var1);   
  5. perstmt.setString(2,var2);   
  6. perstmt.setString(3,var3);   
  7. perstmt.setString(4,var4);   
  8. perstmt.executeUpdate();  


不用我多说,对于第一种方法.别说其他人去读你的代码,就是你自己过一段时间再去读,都会觉得伤心.

二.PreparedStatement尽最大可能提高性能.
每一种数据库都会尽最大努力对预编译语句提供最大的性能优化.因为预编译语句有可能被重复调用.所以语句在被DB的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中(相当于一个涵数)就会得到执行.这并不是说只有一个Connection中多次执行的预编译语句被缓存,而是对于整个DB中,只要预编译的语句语法和缓存中匹配.那么在任何时候就可以不需要再次编译而可以直接执行.而statement的语句中,即使是相同一操作,而由于每次操作的数据不同所以使整个语句相匹配的机会极小,几乎不太可能匹配.比如:
insert into tb_name (col1,col2) values ('11','22');
insert into tb_name (col1,col2) values ('11','23');
即使是相同操作但因为数据内容不一样,所以整个个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存.

当然并不是所以预编译语句都一定会被缓存,数据库本身会用一种策略,比如使用频度等因素来决定什么时候不再缓存已有的预编译结果.以保存有更多的空间存储新的预编译语句.

三.最重要的一点是极大地提高了安全性.

即使到目前为止,仍有一些人连基本的恶义SQL语法都不知道.
String sql = "select * from tb_name where name= '"+varname+"' and passwd='"+varpasswd+"'";
如果我们把[' or '1' = '1]作为varpasswd传入进来.用户名随意,看看会成为什么?

select * from tb_name = '随意' and passwd = '' or '1' = '1';
因为'1'='1'肯定成立,所以可以任何通过验证.更有甚者:
把[';drop table tb_name;]作为varpasswd传入进来,则:
select * from tb_name = '随意' and passwd = '';drop table tb_name;有些数据库是不会让你成功的,但也有很多数据库就可以使这些语句得到执行.

而如果你使用预编译语句.你传入的任何内容就不会和原来的语句发生任何匹配的关系.只要全使用预编译语句,你就用不着对传入的数据做任何过虑.而如果使用普通的statement,有可能要对drop,;等做费尽心机的判断和过虑.

上面的几个原因,还不足让你在任何时候都使用PreparedStatement吗? 

--
we drink green tea

java code to access database

package database;

import java.sql.*;

/**
 * 
@author Administrator
 * 
 
*/
public class DBAccess {
    
private Connection m_conn;

    
private Statement m_stmt;

    String driver 
= "com.microsoft.jdbc.sqlserver.SQLServerDriver";

    String url 
= "jdbc:microsoft:sqlserver://localhost:1433;databasename=sc";

    String uName 
= "sa";

    String uPwd 
= "sa";

    
/**
     * 
     
*/
    
public DBAccess() {
        
this.setDriver(driver);
        
this.setConnection(url, uName, uPwd);
    }

    
public DBAccess(String driver, String url, String userName, String userPWD) {
        
try {
            m_conn 
= DriverManager.getConnection(url, userName, userPWD);
            m_stmt 
= m_conn.createStatement();
        } 
catch (SQLException e) {
            e.printStackTrace();
        }
    }

    
public boolean setDriver(String driver) {
        
try {
            Class.forName(driver);
            
return true;
        } 
catch (Exception e) {
            e.printStackTrace();
        }
        
return false;
    }

    
public boolean setConnection(String url, String userName, String userPWD) {
        
try {
            m_conn 
= DriverManager.getConnection(url, userName, userPWD);
            m_stmt 
= m_conn.createStatement();
            
return true;
        } 
catch (Exception e) {
            e.printStackTrace();
        }
        
return false;
    }

    
// 处理查询
    public ResultSet sendQuery(String sql) {
        
try {
            ResultSet m_rs 
= m_stmt.executeQuery(sql);
            
return m_rs;
        } 
catch (SQLException e) {
            e.printStackTrace();
            
return null;
        }
    }

    
// 处理数据更新
    public int sendUpdate(String sql) {
        
try {
            
return m_stmt.executeUpdate(sql);
        } 
catch (SQLException e) {
            e.printStackTrace();
            
return -1;
        }
    }

    
// 测试程序
    public static void main(String[] arg) {
        DBAccess db 
= new DBAccess();
        String sql 
= "select * from Student";
        ResultSet rs 
= db.sendQuery(sql);
        
try {
            
if (rs != null) {
                
while (rs.next()) {
                    System.out.println(rs.getInt(
"Sno"+ " "
                            
+ rs.getString("Sname"));
                }
            }
        } 
catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

下面罗列了各种数据库使用JDBC连接的方式,可以作为一个手册使用。 

  1、Oracle8/8i/9i数据库(thin模式) 

Class.forName('oracle.jdbc.driver.OracleDriver').newInstance(); 
String url
='jdbc:oracle:thin:@localhost:1521:orcl'//orcl为数据库的SID 
String user='test'
String password
='test'
Connection conn
= DriverManager.getConnection(url,user,password);  


  2、DB2数据库 

Class.forName('com.ibm.db2.jdbc.app.DB2Driver ').newInstance(); 
String url
='jdbc:db2://localhost:5000/sample'//sample为你的数据库名 
String user='admin'
String password
=''
Connection conn
= DriverManager.getConnection(url,user,password);  


  3、Sql Server7.0/2000数据库 

Class.forName('com.microsoft.jdbc.sqlserver.SQLServerDriver').newInstance(); 
String url
='jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb'
//mydb为数据库 
String user='sa'
String password
=''
Connection conn
= DriverManager.getConnection(url,user,password);  


  4、Sybase数据库 

Class.forName('com.sybase.jdbc.SybDriver').newInstance(); 
String url 
=' jdbc:sybase:Tds:localhost:5007/myDB';//myDB为你的数据库名 
Properties sysProps = System.getProperties(); 
SysProps.put(
'user','userid'); 
SysProps.put(
'password','user_password'); 
Connection conn
= DriverManager.getConnection(url, SysProps);  


  5、Informix数据库 

Class.forName('com.informix.jdbc.IfxDriver').newInstance(); 
String url 
= 'jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver
user=testuser;password=testpassword'; //myDB为数据库名 
Connection conn= DriverManager.getConnection(url);  


  6、MySQL数据库 

Class.forName('org.gjt.mm.mysql.Driver').newInstance(); //或者Class.forName('com.mysql.jdbc.Driver');
String url ='jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1' 
//myDB为数据库名 
Connection conn= DriverManager.getConnection(url);  


  7、PostgreSQL数据库 

Class.forName('org.postgresql.Driver').newInstance(); 
String url 
='jdbc:postgresql://localhost/myDB' //myDB为数据库名 
String user='myuser'
String password
='mypassword'
Connection conn
= DriverManager.getConnection(url,user,password);  


  8、access数据库直连用ODBC的

Class.forName('sun.jdbc.odbc.JdbcOdbcDriver') ;
String url
='jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ='+application.getRealPath('/Data/ReportDemo.mdb');
Connection conn 
= DriverManager.getConnection(url,'','');
Statement stmtNew
=conn.createStatement() ; 

--
we drink green tea

2011-6-27

java code to unzip a file

package nio;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class GZIPcompress {
  public static void main(String[] args) throws IOException {
  
       
    
 byte[] buffer = new byte[4096];
    
    
    FileInputStream fin = new FileInputStream("d://pic.zip");
    ZipInputStream gzin = new ZipInputStream(fin);
    ZipEntry z;
File file=new File("d://1");
File files=null;
file.mkdirs();
    while ((z=gzin.getNextEntry())!=null) {
   
    String entryName=z.getName();
    if(!entryName.contains("/"))
    {
    files=new File(file,entryName);
    files.createNewFile();
    System.out.println(files.getAbsolutePath());
    }
    else{
    String filename=entryName.substring(entryName.lastIndexOf("/"));
    System.out.println(filename);
    String innerPath=entryName.substring(0, entryName.lastIndexOf("/"));
    System.out.println(innerPath);
    files=new File(file,innerPath);
    files.mkdirs();
    files=new File(file,entryName);
    files.createNewFile();
   
    }
   
       FileOutputStream out=new FileOutputStream(files);
       int b=0;
       while ((b= gzin.read(buffer)) != -1)
           out.write(buffer, 0, b); 
       out.close(); } 
    gzin.close();
  }
}

--
we drink green tea

code to zip files

package nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * This class defines two static methods for gzipping files and zipping
 * directories. It also defines a demonstration program as a nested class.
 */
public class Compress {
  /** Gzip the contents of the from file and save in the to file. */
  public static void gzipFile(String from, String to) throws IOException {
    // Create stream to read from the from file
    FileInputStream in = new FileInputStream(from);
    // Create stream to compress data and write it to the to file.
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
    // Copy bytes from one stream to the other
    byte[] buffer = new byte[4096];
    int bytes_read;
    while ((bytes_read = in.read(buffer)) != -1)
      out.write(buffer, 0, bytes_read);
    // And close the streams
    in.close();
    out.close();
  }

  /** Zip the contents of the directory, and save it in the zipfile */
  public static void zipDirectory(String dir, String zipfile) throws IOException,
      IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File d = new File(dir);
    if (!d.isDirectory())
      throw new IllegalArgumentException("Compress: not a directory:  " + dir);
    String[] entries = d.list();
    byte[] buffer = new byte[4096]; // Create a buffer for copying
    int bytes_read;

    // Create a stream to compress data and write it to the zipfile
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    // Loop through all entries in the directory
    for (int i = 0; i < entries.length; i++) {
      File f = new File(d, entries[i]);
      if (f.isDirectory())
        continue; // Don't zip sub-directories
      FileInputStream in = new FileInputStream(f); // Stream to read file
      String entryName=f.getName();
      if(i>10)entryName="111/"+entryName;
      ZipEntry entry = new ZipEntry(entryName); // Make a ZipEntry
      
      out.putNextEntry(entry); // Store entry
      while ((bytes_read = in.read(buffer)) != -1)
        // Copy bytes
        out.write(buffer, 0, bytes_read);
      in.close(); // Close input stream
    }
    // When we're done with the whole loop, close the output stream
    out.close();
  }

  /**
   * This nested class is a test program that demonstrates the use of the static
   * methods defined above.
   */
  public static class Test {
    /**
     * Compress a specified file or directory. If no destination name is
     * specified, append .gz to a file name or .zip to a directory name
     */
    public static void main(String args[]) throws IOException {
      
 
      String from ="d://照片";
      String to="d://pic.zip";
      File f = new File(from);
      boolean directory = f.isDirectory(); // Is it a file or directory?
       

      if ((new File(to)).exists()) { // Make sure not to overwrite
        System.err.println("Compress: won't overwrite existing file: " + to);
        System.exit(0);
      }

      // Finally, call one of the methods defined above to do the work.
      if (directory)
        Compress.zipDirectory(from, to);
      else
        Compress.gzipFile(from, to);
    }
  }
}

   


--
we drink green tea

how to gzip a file using java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.GZIPOutputStream;

public class Main {
  public static void main(String[] argvthrows Exception {
    String outFilename = "outfile.gzip";
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(outFilename));

    String inFilename = "infilename";
    FileInputStream in = new FileInputStream(inFilename);

    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) 0) {
      out.write(buf, 0, len);
    }
    in.close();

    out.finish();
    out.close();
  }
}


--
we drink green tea

sample code for NIO communiciation

  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.ServerSocket;  
  4. import java.net.Socket;  
  5. import java.nio.ByteBuffer;  
  6. import java.nio.channels.*;  
  7. import java.util.Set;  
  8.   
  9.   
  10. public class TestChannel {  
  11.     public static void main(String args[]) throws IOException{  
  12.         TestChannel tt=new TestChannel();  
  13.         //tt.initServerChannel(992);  
  14.         tt.initSelector(992);  
  15.     }  
  16.       
  17.     //最初的java  socket实现方式,直接通过serversocket和socket通信  
  18.     public void initServerSocket(int port) throws IOException{  
  19.         ServerSocketChannel ssc=ServerSocketChannel.open();  
  20.         //ssc.configureBlocking(false);  
  21.         ServerSocket ss=new ServerSocket(port);  
  22.         while(true){  
  23.             Socket socket=ss.accept();  
  24.                 System.out.println("socket accepted");  
  25.                 byte[] buf=new byte[1024];  
  26.                 try{  
  27.                 socket.getInputStream().read(buf);  
  28.                 }  
  29.                 catch(Exception ex){  
  30.                     socket.close();  
  31.                 }  
  32.                 System.out.println(new String(buf));  
  33.               
  34.         }  
  35.     }  
  36.     //通过Channel实现的non-blocking通信方式  
  37.     public void initServerChannel(int port) throws IOException{  
  38.         ServerSocketChannel ssc=ServerSocketChannel.open();  
  39.         ssc.configureBlocking(false);  
  40.         ServerSocket ss=ssc.socket();  
  41.         ss.bind(new InetSocketAddress(port));  
  42.         while(true){  
  43.             SocketChannel sc=ssc.accept();  
  44.             if(sc!=null){  
  45.                 Socket socket=sc.socket();  
  46.                 System.out.println("socket accepted");  
  47.                 byte[] buf=new byte[1024];  
  48.                 try{  
  49.                 socket.getInputStream().read(buf);  
  50.                 }  
  51.                 catch(Exception ex){  
  52.                     socket.close();  
  53.                 }  
  54.                 System.out.println(new String(buf));  
  55.             }  
  56.         }  
  57.     }  
  58.     //通过selector和channel进行multiplexed通信,像mina就是通过这种方式实现的  
  59.     public void initSelector(int port) throws IOException{  
  60.         Selector selector=Selector.open();  
  61.         //register server channel  
  62.         ServerSocketChannel ssc=ServerSocketChannel.open();  
  63.         ssc.configureBlocking(false);  
  64.         ServerSocket ss=ssc.socket();  
  65.         ss.bind(new InetSocketAddress(port));  
  66.         ssc.register(selector, SelectionKey.OP_ACCEPT);  
  67.         while(true){  
  68.             int interestNo=selector.select();  
  69.             if(interestNo==0)  
  70.                 continue;  
  71.             Set<SelectionKey> keys=selector.selectedKeys();  
  72.             for(SelectionKey key:keys){  
  73.                 //接受Socket连接请求  
  74.                 if(key.isAcceptable()){  
  75.                     SocketChannel sc=ssc.accept();  
  76.                     try{  
  77.                     sc.configureBlocking(false);  
  78.                     sc.register(selector, SelectionKey.OP_READ);  
  79.                     }  
  80.                     catch(Exception ex){  
  81.                         sc.close();  
  82.                     }  
  83.                     System.out.println("connection accepted");  
  84.                     keys.remove(key);  
  85.                 }  
  86.                 else if(key.isReadable()){  
  87.                     SocketChannel sc=(SocketChannel)key.channel();  
  88.                     ByteBuffer bbuf=ByteBuffer.allocate(1024);  
  89.                     try{  
  90.                     sc.read(bbuf);  
  91.                     }  
  92.                     catch(Exception ex){  
  93.                         sc.close();  
  94.                     }  
  95.                     System.out.println(new String(bbuf.array()));  
  96.                     keys.remove(key);  
  97.                 }  
  98.                 else  
  99.                     keys.remove(key);  
  100.                     continue;  
  101.                       
  102.                 }  
  103.             }  
  104.         }  
  105.     }  

 client:

 

Java代码  收藏代码
  1. public class TestChannelClient {  
  2. public static void main(String args[]) throws UnknownHostException, IOException{  
  3.     Socket sc=new Socket("127.0.0.1",992);  
  4.     OutputStream out=sc.getOutputStream();  
  5.     out.write("hello".getBytes());  
  6.     out.flush();  
  7. }  
  8. }  

--
we drink green tea