├── src └── main │ ├── resources │ ├── thread.jpg │ ├── thread3.jpg │ ├── config.properties │ ├── config_1.properties │ ├── db.properties │ └── config.xml │ └── java │ └── com │ └── andieguo │ ├── databasejdbc │ ├── UserDao.java │ ├── DBHelper.java │ ├── User.java │ └── DBConnection.java │ ├── jsondemo │ ├── book.json │ ├── GsonDemo.java │ └── Book.java │ ├── xmldemo │ ├── ZAgricultrue.xml │ ├── createbooks.xml │ ├── books.xml │ ├── Book.java │ ├── LoopXMLFile.java │ ├── ReadXMLFile.java │ └── CreateXMLFile.java │ ├── iodemo │ └── PrintSteamTester.java │ ├── databasedemo │ ├── config.properties │ ├── DB.java │ └── DBHelper.java │ ├── generics │ ├── Cat.java │ ├── Magpie.java │ ├── Bird.java │ ├── ListFactory.java │ ├── Animal.java │ └── AnimalTest.java │ ├── thread │ ├── TimerDemo.java │ ├── product │ │ ├── ProducerConsumer.java │ │ ├── Consumer.java │ │ ├── Producer.java │ │ ├── Product.java │ │ └── ProductStack.java │ ├── TimerTaskDemo.java │ ├── ThreadSecurityDemo.java │ ├── TimerTest.java │ ├── VolatileTest.java │ ├── RunTimeDemo.java │ └── ThreadTest2.java │ ├── reflectiondemo │ ├── Person.java │ └── DumpMethods.java │ ├── utildemo │ ├── HexTest.java │ ├── DecimalFormatTest.java │ └── EnumerationTester.java │ ├── lang3 │ ├── TeacherBean.java │ ├── SchoolBean.java │ ├── SimpleJavaTester.java │ └── UtilsTester.java │ ├── collectionsdemo │ ├── StackDemo.java │ ├── IteratorTester.java │ └── VectorTester.java │ ├── stringdemo │ └── StringTester.java │ ├── trycatch │ └── TryCatchTester.java │ ├── arraydemo │ └── ArrayTester.java │ ├── saxparserdemo │ ├── saxbooks.xml │ ├── books.xml │ ├── Book.java │ ├── XMLParserSAX.java │ ├── SaxHandler.java │ └── CreateXMLFile.java │ ├── enumdemo │ └── EnumTester.java │ ├── propertiesutil │ ├── PropertyParseExceptionTest.java │ ├── PropertyParseException.java │ ├── PropertyRetrieverTest.java │ └── PropertyRetriever.java │ └── propertiesdemo │ ├── PropertiesHelperTest.java │ ├── PropertiesHelper.java │ └── PropertiesTester.java ├── .gitignore └── pom.xml /src/main/resources/thread.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/resources/thread.jpg -------------------------------------------------------------------------------- /src/main/resources/thread3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/resources/thread3.jpg -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasejdbc/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.databasejdbc; 2 | 3 | public class UserDao { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/jsondemo/book.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/java/com/andieguo/jsondemo/book.json -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/ZAgricultrue.xml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/java/com/andieguo/xmldemo/ZAgricultrue.xml -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasejdbc/DBHelper.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/java/com/andieguo/databasejdbc/DBHelper.java -------------------------------------------------------------------------------- /src/main/java/com/andieguo/iodemo/PrintSteamTester.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andieguo/JavaDemo/HEAD/src/main/java/com/andieguo/iodemo/PrintSteamTester.java -------------------------------------------------------------------------------- /src/main/resources/config.properties: -------------------------------------------------------------------------------- 1 | #modifyThu May 08 16:23:31 CST 2014 2 | #Thu May 08 16:23:31 CST 2014 3 | url=jdbc:mysql://localhost:3306/ 4 | username=root 5 | password=root 6 | database=bbs 7 | -------------------------------------------------------------------------------- /src/main/resources/config_1.properties: -------------------------------------------------------------------------------- 1 | #andieguo modifyFri May 09 21:14:20 CST 2014 2 | #Fri May 09 21:14:20 CST 2014 3 | password=root 4 | url=jdbc\:mysql\://localhost\:3306/ 5 | database=bbs 6 | username=root 7 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasedemo/config.properties: -------------------------------------------------------------------------------- 1 | #modifyThu May 08 16:23:31 CST 2014 2 | #Thu May 08 16:23:31 CST 2014 3 | url=jdbc:mysql://localhost:3306/ 4 | username=root 5 | password=root 6 | database=bbs 7 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/Cat.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | public class Cat extends Animal { 4 | 5 | public Cat(String name) { 6 | super(name); 7 | } 8 | 9 | public void jump(){ 10 | System.out.println(this.getName() + " can jump."); 11 | } 12 | 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | 14 | bin/ 15 | .settings/ 16 | .classpath 17 | .project 18 | /target/ 19 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/TimerDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | import java.util.Timer; 4 | 5 | public class TimerDemo { 6 | public static void main(String args[]){ 7 | Timer timer = new Timer(); 8 | System.out.println("-----------"); 9 | timer.schedule(new TimerTaskDemo(), 2000, 1000); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/Magpie.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | public class Magpie extends Bird { 4 | 5 | public Magpie(String name) { 6 | super(name); 7 | // TODO Auto-generated constructor stub 8 | } 9 | 10 | public void sing(){ 11 | System.out.println(getName() + " can not only eat,but sing"); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/resources/db.properties: -------------------------------------------------------------------------------- 1 | #mysql DB properties 2 | DB_DRIVER_CLASS=com.mysql.jdbc.Driver 3 | DB_URL=jdbc:mysql://localhost:3306/bbs 4 | DB_USERNAME=root 5 | DB_PASSWORD=root 6 | 7 | #Oracle DB Properties 8 | #DB_DRIVER_CLASS=oracle.jdbc.driver.OracleDriver 9 | #DB_URL=jdbc:oracle:thin:@localhost:1571:MyDBSID 10 | #DB_USERNAME=scott 11 | #DB_PASSWORD=tiger 12 | -------------------------------------------------------------------------------- /src/main/resources/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | modifyThu May 08 22:40:06 CST 2014 5 | andieguo 6 | 123456 7 | andy 8 | 3.14 9 | 10 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/Bird.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | public class Bird extends Animal { 4 | 5 | public Bird(String name) { 6 | super(name); 7 | // TODO Auto-generated constructor stub 8 | } 9 | 10 | public Bird(Integer size,Integer weight){ 11 | super(size, weight); 12 | } 13 | 14 | public void fly(){ 15 | System.out.println(this.getName() + " can fly."); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/product/ProducerConsumer.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread.product; 2 | 3 | public class ProducerConsumer { 4 | public static void main(String[] args) { 5 | ProductStack ps = new ProductStack(); 6 | Producer p = new Producer(ps, "11"); 7 | Consumer c = new Consumer(ps, "12"); 8 | new Thread(p).start(); 9 | new Thread(c).start(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/reflectiondemo/Person.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.reflectiondemo; 2 | 3 | public class Person { 4 | 5 | private String name; 6 | private String password; 7 | public String getName() { 8 | return name; 9 | } 10 | public void setName(String name) { 11 | this.name = name; 12 | } 13 | public String getPassword() { 14 | return password; 15 | } 16 | public void setPassword(String password) { 17 | this.password = password; 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/utildemo/HexTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.utildemo; 2 | 3 | public class HexTest { 4 | static int[] blooddata = new int[4]; 5 | public static void main(String[] args) { 6 | blooddata[0] = (0x3D & 0xff) | ((0x00 << 8) & 0xff00); 7 | blooddata[1] = (0x6A & 0xff) | ((0x00 << 8) & 0xff00); 8 | blooddata[2] = (blooddata[0]+blooddata[1])/2; 9 | blooddata[3] = (0x3e & 0xff); 10 | for(int i : blooddata){ 11 | System.out.println(i); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/TimerTaskDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.TimerTask; 6 | 7 | public class TimerTaskDemo extends TimerTask{ 8 | 9 | @Override 10 | public void run() { 11 | // TODO Auto-generated method stub 12 | SimpleDateFormat simpleDateFormat=null; 13 | simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 14 | System.out.println(""+simpleDateFormat.format(new Date())); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/utildemo/DecimalFormatTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.utildemo; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | public class DecimalFormatTest { 6 | public static void main(String[] args) { 7 | DecimalFormat df2= new DecimalFormat("0.0"); 8 | System.out.println(df2.format(11111.111111));//1230.10 9 | 10 | DecimalFormat df4 = new DecimalFormat("#.00"); 11 | System.out.println(df4.format(1230.1));//1230.10 12 | 13 | DecimalFormat df3 = new DecimalFormat("#.##"); 14 | System.out.println(df3.format(1230.1));//1230.10 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/product/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread.product; 2 | 3 | public class Consumer implements Runnable { 4 | String name; 5 | 6 | ProductStack ps = null; 7 | 8 | Consumer(ProductStack ps, String name) { 9 | this.ps = ps; 10 | this.name = name; 11 | } 12 | 13 | public void run() { 14 | for (int i = 0; i < 20; i++) { 15 | Product product = ps.pop(name); 16 | try { 17 | Thread.sleep((int) (Math.random() * 1000)); 18 | } catch (InterruptedException e) { 19 | e.printStackTrace(); 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/product/Producer.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread.product; 2 | 3 | public class Producer implements Runnable { 4 | String name; 5 | 6 | ProductStack ps = null; 7 | 8 | Producer(ProductStack ps, String name) { 9 | this.ps = ps; 10 | this.name = name; 11 | } 12 | 13 | public void run() { 14 | for (int i = 0; i < 20; i++) { 15 | Product product = new Product(i, name); 16 | ps.push(product); 17 | try { 18 | Thread.sleep((int) (Math.random() * 200)); 19 | } catch (InterruptedException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/utildemo/EnumerationTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.utildemo; 2 | 3 | import java.util.Enumeration; 4 | import java.util.Vector; 5 | 6 | public class EnumerationTester { 7 | public static void main(String args[]) { 8 | Enumeration days; 9 | Vector dayNames = new Vector(); 10 | dayNames.add("Sunday"); 11 | dayNames.add("Monday"); 12 | dayNames.add("Tuesday"); 13 | dayNames.add("Wednesday"); 14 | dayNames.add("Thursday"); 15 | dayNames.add("Friday"); 16 | dayNames.add("Saturday"); 17 | days = dayNames.elements(); 18 | while (days.hasMoreElements()) { 19 | System.out.println(days.nextElement()); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/ThreadSecurityDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | public class ThreadSecurityDemo { 4 | private static int sum = 10; 5 | 6 | public static void main(String[] args){ 7 | 8 | Runnable runnable1 = new Runnable() { 9 | public void run() { 10 | sum = sum + 1; 11 | } 12 | }; 13 | 14 | Runnable runnable2 = new Runnable() { 15 | public void run() { 16 | sum = sum - 1; 17 | } 18 | }; 19 | 20 | Thread thread2 = new Thread(runnable2); 21 | Thread thread1 = new Thread(runnable1); 22 | thread1.start(); 23 | thread2.start(); 24 | System.out.println(sum); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasejdbc/User.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.databasejdbc; 2 | 3 | public class User { 4 | private Integer id; 5 | private String username; 6 | private String password; 7 | private Boolean gender; 8 | public Integer getId() { 9 | return id; 10 | } 11 | public void setId(Integer id) { 12 | this.id = id; 13 | } 14 | public String getUsername() { 15 | return username; 16 | } 17 | public void setUsername(String username) { 18 | this.username = username; 19 | } 20 | public String getPassword() { 21 | return password; 22 | } 23 | public void setPassword(String password) { 24 | this.password = password; 25 | } 26 | public Boolean getGender() { 27 | return gender; 28 | } 29 | public void setGender(Boolean gender) { 30 | this.gender = gender; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/ListFactory.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | import java.util.ArrayList; 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | public class ListFactory{ 8 | 9 | private T t; 10 | 11 | public T getT() { 12 | return t; 13 | } 14 | 15 | public void setT(T t) { 16 | this.t = t; 17 | } 18 | /** 19 | * 限制泛型可用类型 20 | * 在定义泛型类别时,预设可以使用任何的类型来实例化泛型类型中的类型。 21 | * 但是如果想限制使用泛型类别时,只能用某个特定类型或者是其子类型才能实例化该类型时,可以在定义类型时,使用extends关键字指定这个类型必须是继承某个类,或者实现某个接口,也可以是这个类或接口本身。 22 | *  此处注意,虽然List是一个接口,但是关键字仍然是extends而不是implements。 23 | * @param args 24 | */ 25 | public static void main(String[] args) { 26 | ListFactory listFactory = new ListFactory(); 27 | ListFactory listFactory2 = new ListFactory(); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasedemo/DB.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.databasedemo; 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 | 9 | public class DB { 10 | 11 | private Connection conn = null; 12 | public DB(String url,String username,String password){ 13 | try { 14 | Class.forName("com.mysql.jdbc.Driver"); 15 | conn = DriverManager.getConnection(url,username,password); 16 | System.out.println(conn); 17 | } catch (ClassNotFoundException e) { 18 | e.printStackTrace(); 19 | } catch (SQLException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | 24 | public ResultSet runSql(String sql) throws SQLException{ 25 | Statement statement= conn.createStatement(); 26 | return statement.executeQuery(sql); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/lang3/TeacherBean.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.lang3; 2 | 3 | import java.io.Serializable; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | 8 | public class TeacherBean implements Serializable{ 9 | 10 | /** 11 | * 12 | */ 13 | private static final long serialVersionUID = -7109407035176922569L; 14 | private String name; 15 | 16 | public TeacherBean() { 17 | super(); 18 | } 19 | 20 | public TeacherBean(String name) { 21 | super(); 22 | this.name = name; 23 | } 24 | 25 | public String getName() { 26 | return name; 27 | } 28 | 29 | public void setName(String name) { 30 | this.name = name; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/TimerTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | import java.util.Date; 4 | import java.util.Timer; 5 | import java.util.TimerTask; 6 | public class TimerTest { 7 | static class MyTimerTask1 extends TimerTask { 8 | public void run() { 9 | new Timer().schedule(new MyTimerTask2(), 2000); 10 | } 11 | } 12 | static class MyTimerTask2 extends TimerTask { 13 | public void run() { 14 | new Timer().schedule(new MyTimerTask1(), 3000); 15 | } 16 | } 17 | public static void main(String[] args) { 18 | Timer timer = new Timer(); 19 | timer.schedule(new MyTimerTask2(), 2000); 20 | while(true) { 21 | System.out.println(new Date().getSeconds()); 22 | try { 23 | Thread.sleep(1000); 24 | } catch (InterruptedException e) { 25 | // TODO Auto-generated catch block 26 | e.printStackTrace(); 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/collectionsdemo/StackDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.collectionsdemo; 2 | 3 | import java.util.Stack; 4 | 5 | import junit.framework.TestCase; 6 | 7 | public class StackDemo extends TestCase { 8 | 9 | public void push(Stack st, int a) { 10 | st.push(new Integer(a)); 11 | } 12 | 13 | public Integer pop(Stack st) { 14 | if (!st.isEmpty()) { 15 | Integer a = st.pop(); 16 | return a; 17 | } 18 | return null; 19 | 20 | } 21 | 22 | public void pushTest() { 23 | Stack st = new Stack(); 24 | push(st, 1); 25 | push(st, 2); 26 | push(st, 3); 27 | push(st, 4); 28 | push(st, 5); 29 | System.out.println(st); 30 | pop(st); 31 | System.out.println(st); 32 | pop(st); 33 | pop(st); 34 | System.out.println(st); 35 | pop(st); 36 | pop(st); 37 | pop(st); 38 | System.out.println(st); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/stringdemo/StringTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.stringdemo; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class StringTester extends TestCase{ 6 | 7 | public void subStringTest(){ 8 | String channel = "00:12:4B:00:02:60:E5:3D_A0"; 9 | String mac = channel.substring(0, channel.length()-3); 10 | System.out.println(mac);//00:12:4B:00:02:60:E5:3D 11 | } 12 | 13 | public void splitTest(){ 14 | String channel = "00:12:4B:00:02:60:E5:3D_A0"; 15 | String[] dat = channel.split("_"); 16 | String mac = dat[0];// 00:12:4B:00:02:60:E5:3D 17 | String command = dat[1];//A0 18 | System.out.println("mac:"+mac+",command:"+command); 19 | } 20 | 21 | public String getChannel(){ 22 | String command = "{A0=?}"; 23 | String[] array = command.split("="); 24 | System.out.println(array[0].substring(1)); 25 | return array[0].substring(0); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/VolatileTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | public class VolatileTest { 4 | public static volatile int a = -1; 5 | 6 | public static void main(String[] args) { 7 | Thread thread1 = new Thread(){ 8 | 9 | @Override 10 | public void run() { 11 | a = 10; 12 | try { 13 | Thread.sleep(10); 14 | } catch (InterruptedException e) { 15 | // TODO Auto-generated catch block 16 | e.printStackTrace(); 17 | } 18 | a = a + 1000; 19 | } 20 | }; 21 | thread1.start(); 22 | 23 | Thread thread2 = new Thread(){ 24 | 25 | @Override 26 | public void run() { 27 | a = 100; 28 | try { 29 | Thread.sleep(10); 30 | } catch (InterruptedException e) { 31 | // TODO Auto-generated catch block 32 | e.printStackTrace(); 33 | } 34 | a = a + 1000; 35 | } 36 | }; 37 | thread2.start(); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/trycatch/TryCatchTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.trycatch; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class TryCatchTester extends TestCase { 6 | 7 | public int add(int a,int b){ 8 | System.out.println("执行add方法"); 9 | throw new NullPointerException(); 10 | // return a+b; 11 | } 12 | //除非调用system.exit()让程序退出或断电等因素致使程序中止,否则,无论任何因素,finally块都一定会执行!! 13 | public int add1(){ 14 | try { 15 | //finally在return语句之后,跳转到上一级程序之前执行。 16 | System.out.println("执行test1的try方法"); 17 | int result = add(1, 2); 18 | System.out.println("执行完add方法"); 19 | // return result; 20 | } catch (Exception e) { 21 | System.out.println("执行catch方法"); 22 | return -2; 23 | } finally {//finally一定会执行,在return之前。(准确说,应该是return ;语句) 24 | System.out.println("执行test1的finally方法"); 25 | } 26 | return -1; 27 | } 28 | 29 | public void test1(){ 30 | System.out.println(add1()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/product/Product.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread.product; 2 | 3 | public class Product { 4 | int id; 5 | private String producedBy = "N/A"; 6 | private String consumedBy = "N/A"; 7 | 8 | Product(int id, String producedBy) { 9 | this.id = id; 10 | this.producedBy = producedBy; 11 | } 12 | 13 | public void consume(String consumedBy) { 14 | this.consumedBy = consumedBy; 15 | } 16 | 17 | public String toString() { 18 | return "Product : " + id + ", produced by " + producedBy 19 | + ", consumed by " + consumedBy; 20 | } 21 | 22 | public String getProducedBy() { 23 | return producedBy; 24 | } 25 | 26 | public void setProducedBy(String producedBy) { 27 | this.producedBy = producedBy; 28 | } 29 | 30 | public String getConsumedBy() { 31 | return consumedBy; 32 | } 33 | 34 | public void setConsumedBy(String consumedBy) { 35 | this.consumedBy = consumedBy; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/arraydemo/ArrayTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.arraydemo; 2 | 3 | import junit.framework.TestCase; 4 | 5 | /** 6 | * 7 | * 类ArrayTester.java的实现描述:java数组遍历 8 | * @author andyguo.gd 2016年8月6日 下午1:12:36 9 | */ 10 | public class ArrayTester extends TestCase { 11 | 12 | public void test() { 13 | int[][] numbers = new int[][] { { 2, 3, 4, 5, 7, 8 }, { 20, 30, 40 }, { 200, 300 }, { 2000, 3000 } }; 14 | //使用增强for循环 15 | for (int i[] : numbers) { 16 | for (int j : i) { 17 | System.out.print(j + " "); 18 | } 19 | System.out.println(); 20 | } 21 | } 22 | 23 | public void test2() { 24 | int[][] numbers = new int[][] { { 2, 3, 4, 5, 7, 8 }, { 20, 30, 40 }, { 200, 300 }, { 2000, 3000 } }; 25 | for (int i = 0; i < numbers.length; i++) { 26 | for (int j = 0; j < numbers[i].length; j++) { 27 | System.out.print(numbers[i][j] + " "); 28 | } 29 | System.out.println(); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasedemo/DBHelper.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.databasedemo; 2 | 3 | import java.sql.ResultSet; 4 | import java.sql.SQLException; 5 | 6 | import com.andieguo.propertiesdemo.PropertiesHelper; 7 | 8 | public class DBHelper { 9 | 10 | public static DB getDB() { 11 | String url = PropertiesHelper.getProperty("url"); 12 | String username = PropertiesHelper.getProperty("username"); 13 | String password = PropertiesHelper.getProperty("password"); 14 | String database = PropertiesHelper.getProperty("database"); 15 | return new DB(url + database, username, password); 16 | } 17 | 18 | public static void main(String[] args) { 19 | DB db = getDB(); 20 | try { 21 | ResultSet rs = db.runSql("select * from admin"); 22 | while (rs.next()) { 23 | System.out.println(rs.getString("name")); 24 | System.out.println(rs.getString("password")); 25 | } 26 | } catch (SQLException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/saxbooks.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Everyday Italian 5 | Giada De Laurentiis 6 | 2005 7 | 30.0 8 | 9 | 10 | Harry Potter 11 | J K. Rowling 12 | 2005 13 | 29.99 14 | 15 | 16 | XQuery Kick Start 17 | James McGovern 18 | Per Bothner 19 | Kurt Cagle 20 | James Linn 21 | Vaidyanathan Nagarajan 22 | 2003 23 | 49.99 24 | 25 | 26 | Learning XML 27 | Erik T. Ray 28 | 2003 29 | 39.95 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/createbooks.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Everyday Italian 5 | Giada De Laurentiis 6 | 2005 7 | 30.0 8 | 9 | 10 | Harry Potter 11 | J K. Rowling 12 | 2005 13 | 29.99 14 | 15 | 16 | XQuery Kick Start 17 | James McGovern 18 | Per Bothner 19 | Kurt Cagle 20 | James Linn 21 | Vaidyanathan Nagarajan 22 | 2003 23 | 49.99 24 | 25 | 26 | Learning XML 27 | Erik T. Ray 28 | 2003 29 | 39.95 30 | 31 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/enumdemo/EnumTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.enumdemo; 2 | 3 | import junit.framework.TestCase; 4 | 5 | public class EnumTester extends TestCase { 6 | 7 | public enum SensorKey { 8 | 9 | KEY_Information("Information", "key_Information"), 10 | KEY_Light("Light", "key_Light"), 11 | KEY_Appliance("Appliance", "key_Appliance"); 12 | 13 | private String activity; 14 | private String key; 15 | 16 | private SensorKey(String activity, String key) {// ˽�еĻ��Ѻõ� 17 | this.key = key; 18 | this.activity = activity; 19 | } 20 | 21 | public String getKey() { 22 | return key; 23 | } 24 | 25 | public String getActivity() { 26 | return activity; 27 | } 28 | } 29 | 30 | public void test() { 31 | System.out.println(SensorKey.KEY_Appliance.getKey()); 32 | } 33 | 34 | public void test2() { 35 | for (SensorKey sensorKey : SensorKey.values()) {// ����ö�� 36 | System.out.println(sensorKey.getKey() + ":" + sensorKey.getActivity()); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/books.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Everyday Italian 6 | Giada De Laurentiis 7 | 2005 8 | 30.00 9 | 10 | 11 | Harry Potter 12 | J K. Rowling 13 | 2005 14 | 29.99 15 | 16 | 17 | XQuery Kick Start 18 | James McGovern 19 | Per Bothner 20 | Kurt Cagle 21 | James Linn 22 | Vaidyanathan Nagarajan 23 | 2003 24 | 49.99 25 | 26 | 27 | Learning XML 28 | Erik T. Ray 29 | 2003 30 | 39.95 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/books.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Everyday Italian 6 | Giada De Laurentiis 7 | 2005 8 | 30.00 9 | 10 | 11 | Harry Potter 12 | J K. Rowling 13 | 2005 14 | 29.99 15 | 16 | 17 | XQuery Kick Start 18 | James McGovern 19 | Per Bothner 20 | Kurt Cagle 21 | James Linn 22 | Vaidyanathan Nagarajan 23 | 2003 24 | 49.99 25 | 26 | 27 | Learning XML 28 | Erik T. Ray 29 | 2003 30 | 39.95 31 | 32 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/Animal.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | public class Animal { 4 | 5 | private String name; 6 | 7 | private Integer size; 8 | 9 | private Integer weight; 10 | 11 | public Animal(String name){ 12 | this.name = name; 13 | } 14 | 15 | public Animal(Integer size, Integer weight) { 16 | super(); 17 | this.size = size; 18 | this.weight = weight; 19 | } 20 | 21 | public String getName() { 22 | return name; 23 | } 24 | 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | 29 | public Integer getSize() { 30 | return size; 31 | } 32 | 33 | public void setSize(Integer size) { 34 | this.size = size; 35 | } 36 | 37 | public Integer getWeight() { 38 | return weight; 39 | } 40 | 41 | public void setWeight(Integer weight) { 42 | this.weight = weight; 43 | } 44 | 45 | public void eat(){ 46 | System.out.println(this.getName() + " cat eat."); 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "Animal [name=" + name + ", size=" + size + ", weight=" + weight + "]"; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/lang3/SchoolBean.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.lang3; 2 | 3 | import java.io.Serializable; 4 | 5 | import org.apache.commons.lang3.builder.ToStringBuilder; 6 | import org.apache.commons.lang3.builder.ToStringStyle; 7 | 8 | public class SchoolBean implements Serializable{ 9 | 10 | /** 11 | * 12 | */ 13 | private static final long serialVersionUID = -2618428079233870928L; 14 | 15 | private String name; 16 | 17 | private TeacherBean teacher; 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public TeacherBean getTeacher() { 28 | return teacher; 29 | } 30 | 31 | public void setTeacher(TeacherBean teacher) { 32 | this.teacher = teacher; 33 | } 34 | 35 | public SchoolBean(String name, TeacherBean teacher) { 36 | super(); 37 | this.name = name; 38 | this.teacher = teacher; 39 | } 40 | 41 | public SchoolBean() { 42 | super(); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return ToStringBuilder.reflectionToString(this, ToStringStyle.DEFAULT_STYLE); 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/RunTimeDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | public class RunTimeDemo { 8 | 9 | public static void main(String[] args){ 10 | //runCommand(); 11 | runCommand2(); 12 | } 13 | private static void runCommand2() { 14 | try { 15 | String [] cmd={"cmd","/C","start F:\\hello.txt"}; 16 | Process proc =Runtime.getRuntime().exec(cmd); 17 | } catch (IOException e) { 18 | e.printStackTrace(); 19 | } 20 | } 21 | private static void runCommand() { 22 | String command = "ipconfig"; 23 | Runtime run = Runtime.getRuntime(); 24 | try { 25 | Process p = run.exec(command); 26 | BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 27 | String strline; 28 | while((strline = in.readLine())!=null){ 29 | System.out.println(strline); 30 | } 31 | if (p.waitFor() != 0) { 32 | if (p.exitValue() == 1) 33 | System.err.println("hello"); 34 | } 35 | in.close(); 36 | } catch (Exception e) { 37 | e.printStackTrace(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/collectionsdemo/IteratorTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.collectionsdemo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Map; 8 | 9 | public class IteratorTester { 10 | public static void main(String args[]) { 11 | List myList = new ArrayList(); 12 | 13 | myList.add("1"); 14 | myList.add("2"); 15 | myList.add("3"); 16 | myList.add("4"); 17 | myList.add("5"); 18 | 19 | Iterator it = myList.iterator(); 20 | while (it.hasNext()) { 21 | String value = it.next(); 22 | System.out.println("List Value:" + value); 23 | if (value.equals("3")); 24 | //myList.remove(value); 25 | } 26 | 27 | Map myMap = new HashMap(); 28 | myMap.put("1", "1"); 29 | myMap.put("2", "2"); 30 | myMap.put("3", "3"); 31 | 32 | Iterator it1 = myMap.keySet().iterator(); 33 | while (it1.hasNext()) { 34 | String key = it1.next(); 35 | System.out.println("Map Value:" + myMap.get(key)); 36 | if (key.equals("2")) { 37 | myMap.put("1", "4"); 38 | // myMap.put("4", "4"); 39 | } 40 | } 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/jsondemo/GsonDemo.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.jsondemo; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.FileReader; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | 8 | import com.google.gson.Gson; 9 | 10 | public class GsonDemo { 11 | public static void main(String[] args) { 12 | jsonToObject(); 13 | } 14 | 15 | @SuppressWarnings("unused") 16 | private static void objectToJson() { 17 | Book book = new Book("story","en"," The ordinary world","andy",2013,45.0); 18 | Gson gson = new Gson(); 19 | 20 | String json = gson.toJson(book); 21 | try { 22 | FileWriter writer = new FileWriter("src/com/andieguo/jsondemo/book.json"); 23 | writer.write(json); 24 | writer.close(); 25 | } catch (IOException e) { 26 | e.printStackTrace(); 27 | } 28 | System.out.println(json); 29 | } 30 | 31 | private static void jsonToObject() { 32 | Gson gson = new Gson(); 33 | try { 34 | BufferedReader br = new BufferedReader(new FileReader("src/com/andieguo/jsondemo/book.json")); 35 | Book book = gson.fromJson(br, Book.class); 36 | System.out.println(book.toString()); 37 | } catch (IOException e) { 38 | e.printStackTrace(); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/product/ProductStack.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread.product; 2 | public class ProductStack { 3 | int index = 0; 4 | 5 | Product[] arrProduct = new Product[6]; 6 | 7 | public synchronized void push(Product product) { 8 | while (index == arrProduct.length) 9 | { 10 | try { 11 | 12 | System.out.println(product.getProducedBy() + " is waiting."); 13 | wait(); 14 | } catch (InterruptedException e) { 15 | e.printStackTrace(); 16 | } 17 | } 18 | System.out.println(product.getProducedBy() + " sent a notifyAll()."); 19 | 20 | notifyAll(); 21 | arrProduct[index] = product; 22 | index++; 23 | System.out.println(product.getProducedBy() + " ������: " + product); 24 | } 25 | 26 | public synchronized Product pop(String consumerName) { 27 | while (index == 0) { 28 | try { 29 | System.out.println(consumerName + " is waiting."); 30 | wait(); 31 | } catch (InterruptedException e) { 32 | e.printStackTrace(); 33 | } 34 | } 35 | 36 | System.out.println(consumerName + " sent a notifyAll()."); 37 | notifyAll(); 38 | index--; 39 | Product product = arrProduct[index]; 40 | product.consume(consumerName); 41 | System.out.println(product.getConsumedBy() + " : " + product); 42 | return product; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/Book.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.xmldemo; 2 | 3 | public class Book { 4 | private String category; 5 | private String titleLang; 6 | private String title; 7 | private String author; 8 | private Integer year; 9 | private Double price; 10 | 11 | 12 | @Override 13 | public String toString() { 14 | return "Book [category=" + category + ", titleLang=" + titleLang + ", title=" + title + ", author=" + author + ", year=" + year + ", price=" + price + "]"; 15 | } 16 | public String getCategory() { 17 | return category; 18 | } 19 | public void setCategory(String category) { 20 | this.category = category; 21 | } 22 | public String getTitleLang() { 23 | return titleLang; 24 | } 25 | public void setTitleLang(String titleLang) { 26 | this.titleLang = titleLang; 27 | } 28 | public String getTitle() { 29 | return title; 30 | } 31 | public void setTitle(String title) { 32 | this.title = title; 33 | } 34 | public String getAuthor() { 35 | return author; 36 | } 37 | public void setAuthor(String author) { 38 | this.author = author; 39 | } 40 | public Integer getYear() { 41 | return year; 42 | } 43 | public void setYear(Integer year) { 44 | this.year = year; 45 | } 46 | public Double getPrice() { 47 | return price; 48 | } 49 | public void setPrice(Double price) { 50 | this.price = price; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/Book.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.saxparserdemo; 2 | 3 | public class Book { 4 | private String category; 5 | private String titleLang; 6 | private String title; 7 | private String author; 8 | private Integer year; 9 | private Double price; 10 | 11 | 12 | @Override 13 | public String toString() { 14 | return "Book [category=" + category + ", titleLang=" + titleLang + ", title=" + title + ", author=" + author + ", year=" + year + ", price=" + price + "]"; 15 | } 16 | public String getCategory() { 17 | return category; 18 | } 19 | public void setCategory(String category) { 20 | this.category = category; 21 | } 22 | public String getTitleLang() { 23 | return titleLang; 24 | } 25 | public void setTitleLang(String titleLang) { 26 | this.titleLang = titleLang; 27 | } 28 | public String getTitle() { 29 | return title; 30 | } 31 | public void setTitle(String title) { 32 | this.title = title; 33 | } 34 | public String getAuthor() { 35 | return author; 36 | } 37 | public void setAuthor(String author) { 38 | this.author = author; 39 | } 40 | public Integer getYear() { 41 | return year; 42 | } 43 | public void setYear(Integer year) { 44 | this.year = year; 45 | } 46 | public Double getPrice() { 47 | return price; 48 | } 49 | public void setPrice(Double price) { 50 | this.price = price; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/propertiesutil/PropertyParseExceptionTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.propertiesutil; 2 | 3 | 4 | import junit.framework.TestCase; 5 | 6 | 7 | /** 8 | * Tests the property exception class. 9 | */ 10 | public class PropertyParseExceptionTest extends TestCase { 11 | 12 | 13 | public void testMinimalConstructor() { 14 | 15 | PropertyParseException e = new PropertyParseException("message"); 16 | assertEquals("message", e.getMessage()); 17 | assertNull(e.getPropertyKey()); 18 | assertNull(e.getPropertyValue()); 19 | assertNull(e.getCause()); 20 | } 21 | 22 | 23 | public void testPropertyKeyConstructor() { 24 | 25 | PropertyParseException e = new PropertyParseException("message", "key"); 26 | assertEquals("message", e.getMessage()); 27 | assertEquals("key", e.getPropertyKey()); 28 | assertNull(e.getPropertyValue()); 29 | assertNull(e.getCause()); 30 | } 31 | 32 | 33 | public void testFullConstructor() { 34 | 35 | PropertyParseException e = new PropertyParseException("message", "key", "value"); 36 | assertEquals("message", e.getMessage()); 37 | assertEquals("key", e.getPropertyKey()); 38 | assertEquals("value", e.getPropertyValue()); 39 | assertNull(e.getCause()); 40 | } 41 | 42 | 43 | 44 | public void testFullConstructorWithNulls() { 45 | 46 | PropertyParseException e = new PropertyParseException(null, null, null); 47 | assertNull(e.getMessage()); 48 | assertNull(e.getPropertyKey()); 49 | assertNull(e.getPropertyValue()); 50 | assertNull(e.getCause()); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/jsondemo/Book.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.jsondemo; 2 | 3 | public class Book { 4 | private String category; 5 | private String titleLang; 6 | private String title; 7 | private String author; 8 | private Integer year; 9 | private Double price; 10 | 11 | 12 | public Book(String category, String titleLang, String title, String author, Integer year, Double price) { 13 | super(); 14 | this.category = category; 15 | this.titleLang = titleLang; 16 | this.title = title; 17 | this.author = author; 18 | this.year = year; 19 | this.price = price; 20 | } 21 | @Override 22 | public String toString() { 23 | return "Book [category=" + category + ", titleLang=" + titleLang + ", title=" + title + ", author=" + author + ", year=" + year + ", price=" + price + "]"; 24 | } 25 | public String getCategory() { 26 | return category; 27 | } 28 | public void setCategory(String category) { 29 | this.category = category; 30 | } 31 | public String getTitleLang() { 32 | return titleLang; 33 | } 34 | public void setTitleLang(String titleLang) { 35 | this.titleLang = titleLang; 36 | } 37 | public String getTitle() { 38 | return title; 39 | } 40 | public void setTitle(String title) { 41 | this.title = title; 42 | } 43 | public String getAuthor() { 44 | return author; 45 | } 46 | public void setAuthor(String author) { 47 | this.author = author; 48 | } 49 | public Integer getYear() { 50 | return year; 51 | } 52 | public void setYear(Integer year) { 53 | this.year = year; 54 | } 55 | public Double getPrice() { 56 | return price; 57 | } 58 | public void setPrice(Double price) { 59 | this.price = price; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/LoopXMLFile.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.xmldemo; 2 | 3 | import java.io.File; 4 | 5 | import javax.xml.parsers.DocumentBuilder; 6 | import javax.xml.parsers.DocumentBuilderFactory; 7 | 8 | import org.w3c.dom.Document; 9 | import org.w3c.dom.NamedNodeMap; 10 | import org.w3c.dom.Node; 11 | import org.w3c.dom.NodeList; 12 | 13 | public class LoopXMLFile { 14 | public static void main(String[] args) { 15 | loopXMLFile(); 16 | } 17 | 18 | private static void loopXMLFile(){ 19 | try { 20 | File file = new File("src/com/andieguo/xmldemo/books.xml"); 21 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 22 | DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 23 | Document doc = dBuilder.parse(file); 24 | if(doc.hasChildNodes()){ 25 | printNote(doc.getChildNodes()); 26 | } 27 | } catch (Exception e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | 32 | private static void printNote(NodeList nodeList){ 33 | for(int i=0; i"); 37 | System.out.println(node.getTextContent()); 38 | if(node.hasAttributes()){ 39 | NamedNodeMap nodeMap = node.getAttributes(); 40 | for(int j=0;j"); 49 | } 50 | 51 | 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/XMLParserSAX.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.saxparserdemo; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.util.List; 6 | 7 | import javax.xml.parsers.SAXParser; 8 | import javax.xml.parsers.SAXParserFactory; 9 | 10 | import org.xml.sax.InputSource; 11 | import org.xml.sax.XMLReader; 12 | 13 | public class XMLParserSAX { 14 | 15 | public static void main(String[] args) { 16 | //List books = xmlReader(new File("src/com/andieguo/saxparserdemo/books.xml")); 17 | List books = saxParser(new File("src/com/andieguo/saxparserdemo/books.xml")); 18 | for (Book book : books) { 19 | System.out.println(book.toString()); 20 | } 21 | } 22 | public static List saxParser(File file) { 23 | try { 24 | SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); 25 | SAXParser saxParser = saxParserFactory.newSAXParser(); 26 | SaxHandler saxHandler = new SaxHandler(); 27 | saxParser.parse(file, saxHandler); 28 | List books = saxHandler.getBookList(); 29 | return books; 30 | } catch (Exception e) { 31 | e.printStackTrace(); 32 | } 33 | return null; 34 | } 35 | public static List xmlReader(File file) { 36 | try { 37 | SAXParserFactory factory = SAXParserFactory.newInstance(); 38 | SAXParser parser = factory.newSAXParser(); 39 | XMLReader reader = parser.getXMLReader(); 40 | SaxHandler saxHandler = new SaxHandler(); 41 | reader.setContentHandler(saxHandler); 42 | reader.parse(new InputSource(new FileInputStream(file))); 43 | List books = saxHandler.getBookList(); 44 | return books; 45 | } catch (Exception e) { 46 | e.printStackTrace(); 47 | } 48 | return null; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/propertiesdemo/PropertiesHelperTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.propertiesdemo; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileOutputStream; 5 | import java.io.OutputStream; 6 | import java.util.Date; 7 | 8 | import junit.framework.TestCase; 9 | 10 | public class PropertiesHelperTest extends TestCase { 11 | 12 | public void getProperty() { 13 | System.out.println(PropertiesHelper.getProperty("KEY")); 14 | } 15 | 16 | public void store() { 17 | PropertiesHelper.setProperty("database", "bbs"); 18 | try { 19 | OutputStream out = new FileOutputStream("config.properties"); 20 | PropertiesHelper.store(out, "modify" + new Date()); 21 | } catch (FileNotFoundException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | 26 | public void storeXML(){ 27 | try { 28 | OutputStream out = new FileOutputStream("config.xml"); 29 | PropertiesHelper.storeXML(out, "modify" + new Date()); 30 | } catch (FileNotFoundException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | 35 | public void setProperties(){ 36 | PropertiesHelper.setProperty("Weight", "70"); 37 | PropertiesHelper.printEntry(); 38 | } 39 | 40 | public void put(){ 41 | PropertiesHelper.put("Height", 20); 42 | PropertiesHelper.put("Scannable", true); 43 | PropertiesHelper.put("Weight", 70.0); 44 | PropertiesHelper.put("Weight", 80.0); 45 | PropertiesHelper.printEntry(); 46 | } 47 | 48 | public void list(){ 49 | PropertiesHelper.list(System.out); 50 | } 51 | 52 | public void printEntry() { 53 | PropertiesHelper.printEntry(); 54 | } 55 | 56 | public void printKey(){ 57 | PropertiesHelper.printKey(); 58 | } 59 | 60 | public void printEnumeration(){ 61 | PropertiesHelper.printEnumeration(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/reflectiondemo/DumpMethods.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.reflectiondemo; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.Stack; 5 | 6 | import junit.framework.TestCase; 7 | 8 | public class DumpMethods extends TestCase { 9 | public static void main(String[] args) { 10 | getDeclaredMethods("java.util.Stack"); 11 | } 12 | 13 | private static void getDeclaredMethods(String className) { 14 | try { 15 | Class c = Class.forName(className); 16 | Method m[] = c.getDeclaredMethods(); 17 | for (int i = 0; i < m.length; i++) { 18 | System.out.println(m[i].toString()); 19 | } 20 | } catch (ClassNotFoundException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | public void getClassTester() { 26 | try { 27 | Class stringClass = Class.forName("java.lang.String"); 28 | Class intClass = int.class; 29 | Class integerClass = Integer.class; 30 | 31 | System.out.println(integerClass.getDeclaredMethods()[0].toString()); 32 | System.out.println(Stack.class.getDeclaredMethods()[0].toString()); 33 | } catch (ClassNotFoundException e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | 38 | public void isInstanceTest() { 39 | Class c = DumpMethods.class; 40 | boolean b = c.isInstance(new DumpMethods()); 41 | System.out.println(b); 42 | } 43 | 44 | public void invokeTest(){ 45 | Class c = Person.class; 46 | try{ 47 | Method setNameMethod = c.getMethod("setName", String.class); 48 | Method getNameMethod = c.getMethod("getName", null); 49 | Person p = (Person) c.newInstance(); 50 | setNameMethod.invoke(p, "andy"); 51 | String name = (String) getNameMethod.invoke(p, null); 52 | System.out.println(name); 53 | }catch(Exception e){ 54 | System.out.println(e.toString()); 55 | } 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/thread/ThreadTest2.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.thread; 2 | 3 | public class ThreadTest2 { 4 | public static void main(String[] args) { 5 | final Business business = new Business(); 6 | new Thread(new Runnable() { 7 | public void run() { 8 | threadExecute(business, "sub"); 9 | } 10 | }).start(); 11 | threadExecute(business, "main"); 12 | 13 | } 14 | public static void threadExecute(Business business, String threadType) { 15 | for(int i = 0; i < 10; i++) { 16 | try { 17 | if("main".equals(threadType)) { 18 | business.main(i); 19 | } else { 20 | business.sub(i); 21 | } 22 | } catch (InterruptedException e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | } 27 | } 28 | /** 29 | sub thread seq of 0, loop of 0 30 | sub thread seq of 1, loop of 0 31 | main thread seq of 0, loop of 0 32 | main thread seq of 1, loop of 0 33 | main thread seq of 2, loop of 0 34 | main thread seq of 3, loop of 0 35 | 36 | sub thread seq of 0, loop of 1 37 | sub thread seq of 1, loop of 1 38 | main thread seq of 0, loop of 1 39 | main thread seq of 1, loop of 1 40 | main thread seq of 2, loop of 1 41 | main thread seq of 3, loop of 1 42 | * @author Administrator 43 | * 44 | */ 45 | class Business { 46 | private boolean bool = true; 47 | public synchronized void main(int loop) throws InterruptedException { 48 | while(bool) { 49 | this.wait(); 50 | } 51 | for(int i = 0; i < 4; i++) { 52 | System.out.println("main thread seq of " + i + ", loop of " + loop); 53 | } 54 | bool = true; 55 | this.notify(); 56 | } 57 | public synchronized void sub(int loop) throws InterruptedException { 58 | while(!bool) { 59 | this.wait(); 60 | } 61 | for(int i = 0; i < 2; i++) { 62 | System.out.println("sub thread seq of " + i + ", loop of " + loop); 63 | } 64 | bool = false; 65 | this.notify(); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.andieguo.demo 6 | JavaDemo 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | JavaDemo 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 16 | 17 | 18 | 19 | junit 20 | junit 21 | 3.8.1 22 | test 23 | 24 | 25 | 26 | com.google.code.gson 27 | gson 28 | 2.2.4 29 | 30 | 31 | org.apache.commons 32 | commons-lang3 33 | 3.4 34 | 35 | 36 | 37 | org.apache.commons 38 | commons-collections4 39 | 4.1 40 | 41 | 42 | 43 | commons-beanutils 44 | commons-beanutils 45 | 1.8.3 46 | 47 | 48 | 49 | org.springframework 50 | spring-beans 51 | 4.3.3.RELEASE 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/collectionsdemo/VectorTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.collectionsdemo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Enumeration; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Vector; 8 | 9 | public class VectorTester { 10 | 11 | 12 | public static void main(String args[]) { 13 | 14 | vectortest(); 15 | } 16 | @SuppressWarnings({ "unchecked", "rawtypes" }) 17 | private static void vectortest() { 18 | // initial size is 3, increment is 2 19 | Vector v = new Vector(3, 2); 20 | System.out.println("Initial size: " + v.size()); 21 | System.out.println("Initial capacity: " + v.capacity()); 22 | v.addElement(new Integer(1)); 23 | v.addElement(new Integer(2)); 24 | v.addElement(new Integer(3)); 25 | v.addElement(new Integer(4)); 26 | System.out.println("Capacity after four additions: " + v.capacity()); 27 | 28 | v.addElement(new Double(5.45)); 29 | System.out.println("Current capacity: " + v.capacity()); 30 | v.addElement(new Double(6.08)); 31 | v.addElement(new Integer(7)); 32 | System.out.println("Current capacity: " + v.capacity()); 33 | v.addElement(new Float(9.4)); 34 | v.addElement(new Integer(10)); 35 | System.out.println("Current capacity: " + v.capacity()); 36 | v.addElement(new Integer(11)); 37 | v.addElement(new Integer(12)); 38 | System.out.println("First element: " + (Integer) v.firstElement()); 39 | System.out.println("Last element: " + (Integer) v.lastElement()); 40 | if (v.contains(new Integer(3))) 41 | System.out.println("Vector contains 3."); 42 | // enumerate the elements in the vector. 43 | Enumeration vEnum = v.elements(); 44 | System.out.println("\nElements in vector:"); 45 | while (vEnum.hasMoreElements()) 46 | System.out.print(vEnum.nextElement() + " "); 47 | System.out.println(); 48 | } 49 | 50 | @SuppressWarnings({ "unchecked", "rawtypes" }) 51 | public void listTest(){ 52 | List list = new ArrayList(); 53 | list.add(new Integer(11)); 54 | list.add(new Double(12.0)); 55 | Iterator it = list.iterator(); 56 | while(it.hasNext()){ 57 | System.out.println(it.next()); 58 | } 59 | } 60 | 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/ReadXMLFile.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.xmldemo; 2 | 3 | import java.io.File; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import javax.xml.parsers.DocumentBuilder; 8 | import javax.xml.parsers.DocumentBuilderFactory; 9 | 10 | import org.w3c.dom.Document; 11 | import org.w3c.dom.Element; 12 | import org.w3c.dom.Node; 13 | import org.w3c.dom.NodeList; 14 | 15 | public class ReadXMLFile { 16 | 17 | public static void main(String[] args) { 18 | File file = new File("src/com/andieguo/xmldemo/books.xml"); 19 | List books = readXMLFile(file); 20 | for (Book book : books) { 21 | System.out.println(book.toString()); 22 | } 23 | } 24 | 25 | public static List readXMLFile(File file) { 26 | List lists = new ArrayList(); 27 | try { 28 | 29 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 30 | DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 31 | Document doc = dBuilder.parse(file); 32 | NodeList bookList = doc.getElementsByTagName("book"); 33 | for (int i = 0; i < bookList.getLength(); i++) { 34 | Node bookNode = bookList.item(i); 35 | if (bookNode.getNodeType() == Node.ELEMENT_NODE) { 36 | Element bookElement = (Element) bookNode; 37 | Book book = new Book(); 38 | book.setCategory(bookElement.getAttribute("category")); 39 | Element titleElement = (Element) bookElement.getElementsByTagName("title").item(0); 40 | book.setTitle(titleElement.getTextContent()); 41 | book.setTitleLang(titleElement.getAttribute("lang")); 42 | NodeList authorList = bookElement.getElementsByTagName("author"); 43 | String author = ""; 44 | for (int j = 0; j < authorList.getLength(); j++) { 45 | author = author + authorList.item(j).getTextContent() + "/"; 46 | } 47 | author = author.substring(0, author.length() - 1); 48 | book.setAuthor(author); 49 | book.setYear(Integer.valueOf(bookElement.getElementsByTagName("year").item(0).getTextContent())); 50 | book.setPrice(Double.valueOf(bookElement.getElementsByTagName("price").item(0).getTextContent())); 51 | lists.add(book); 52 | } 53 | 54 | } 55 | } catch (Exception e) { 56 | e.printStackTrace(); 57 | } 58 | return lists; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/SaxHandler.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.saxparserdemo; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.xml.sax.Attributes; 7 | import org.xml.sax.SAXException; 8 | import org.xml.sax.helpers.DefaultHandler; 9 | 10 | public class SaxHandler extends DefaultHandler { 11 | 12 | private List bookList = null; 13 | private Book book = null; 14 | private boolean bTitle = false; 15 | private boolean bAuthor = false; 16 | private boolean bYear = false; 17 | private boolean bPrice = false; 18 | 19 | public List getBookList() { 20 | return bookList; 21 | } 22 | 23 | @Override 24 | public void startDocument() throws SAXException { 25 | super.startDocument(); 26 | } 27 | 28 | @Override 29 | public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 30 | if (qName.equalsIgnoreCase("book")) { 31 | String category = attributes.getValue("category"); 32 | book = new Book(); 33 | book.setCategory(category); 34 | if (bookList == null) { 35 | bookList = new ArrayList(); 36 | } 37 | } else if (qName.equalsIgnoreCase("title")) { 38 | String titleLang = attributes.getValue("lang"); 39 | book.setTitleLang(titleLang); 40 | bTitle = true; 41 | } else if (qName.equalsIgnoreCase("author")) { 42 | bAuthor = true; 43 | } else if (qName.equalsIgnoreCase("year")) { 44 | bYear = true; 45 | } else if (qName.equalsIgnoreCase("price")) { 46 | bPrice = true; 47 | } 48 | } 49 | 50 | @Override 51 | public void endElement(String uri, String localName, String qName) throws SAXException { 52 | if (qName.equalsIgnoreCase("book")) { 53 | bookList.add(book); 54 | } 55 | } 56 | 57 | @Override 58 | public void characters(char[] ch, int start, int length) throws SAXException { 59 | if (bTitle) { 60 | book.setTitle(new String(ch, start, length)); 61 | bTitle = false; 62 | } else if (bAuthor) { 63 | if (book.getAuthor() == null) { 64 | book.setAuthor(new String(ch, start, length)); 65 | } else { 66 | book.setAuthor(book.getAuthor() + "/" + new String(ch, start, length)); 67 | } 68 | bAuthor = false; 69 | } else if (bYear) { 70 | book.setYear(Integer.parseInt(new String(ch, start, length))); 71 | bYear = false; 72 | } else if (bPrice) { 73 | book.setPrice(Double.parseDouble(new String(ch, start, length))); 74 | bPrice = false; 75 | } 76 | } 77 | 78 | @Override 79 | public void endDocument() throws SAXException { 80 | super.endDocument(); 81 | } 82 | 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/generics/AnimalTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.generics; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.HashSet; 6 | import java.util.Iterator; 7 | import java.util.List; 8 | 9 | import junit.framework.TestCase; 10 | 11 | public class AnimalTest extends TestCase { 12 | 13 | private List animalList = new ArrayList(); 14 | 15 | //Cat是Animal的子类 16 | private List catList = new ArrayList(); 17 | 18 | //Bird是Magpie的父类 19 | private List birdList = new ArrayList(); 20 | 21 | //Animal是Magpie的父类 22 | private List magpieList = new ArrayList(); 23 | 24 | private List birddList = new ArrayList(); 25 | 26 | //compare比较器 27 | public void testAct4(){ 28 | birddList.add(new Magpie("mage")); 29 | birddList.add(new Bird("cat")); 30 | Arrays.asList("a", "b", "c"); 31 | HashSet s2 = new HashSet(Arrays.asList("a", "b", "c")); 32 | } 33 | 34 | public void testAct3(){ 35 | List list = new ArrayList(); 36 | list.add(new Cat("cat1")); 37 | list.add(new Cat("bird1")); 38 | list.add(new Cat("magpie1")); 39 | List magpieList = list; 40 | Iterator iterator = magpieList.iterator(); 41 | while(iterator.hasNext()){ 42 | Cat cat = (Cat)iterator.next(); 43 | cat.jump(); 44 | } 45 | } 46 | 47 | 48 | public void act(List list) { 49 | for (Animal animal : list) { 50 | animal.eat(); 51 | } 52 | } 53 | 54 | /** 55 | * 类型通配声明 56 | * 使用或是的声明方式,意味着您只能通过该名称来取得所参考的实例的信息,或者是移除某些信息,但不能增加或者改写它的信息。 57 | * @param list 58 | */ 59 | public void act1(List list){ 60 | list.add(null); 61 | //list.add(new Cat("cat1")); 62 | for (Animal animal : list) { 63 | animal.eat(); 64 | } 65 | } 66 | 67 | public void testAct(){ 68 | List list = new ArrayList(); 69 | list.add(new Cat("cat1")); 70 | list.add(new Bird("bird1")); 71 | list.add(new Magpie("magpie1")); 72 | act(list); 73 | List catList = new ArrayList(); 74 | catList.add(new Cat("cat1")); 75 | catList.add(new Cat("cat2")); 76 | catList.add(new Cat("cat3")); 77 | act(list); 78 | } 79 | 80 | public void testAct1(){ 81 | List list = new ArrayList(); 82 | list.add(new Cat("cat1")); 83 | list.add(new Bird("bird1")); 84 | list.add(new Magpie("magpie1")); 85 | act1(list); 86 | List catList = new ArrayList(); 87 | catList.add(new Cat("cat1")); 88 | catList.add(new Cat("cat2")); 89 | catList.add(new Cat("cat3")); 90 | act1(catList); 91 | } 92 | 93 | 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/xmldemo/CreateXMLFile.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.xmldemo; 2 | 3 | import java.io.File; 4 | import java.util.List; 5 | 6 | import javax.xml.parsers.DocumentBuilder; 7 | import javax.xml.parsers.DocumentBuilderFactory; 8 | import javax.xml.transform.OutputKeys; 9 | import javax.xml.transform.Transformer; 10 | import javax.xml.transform.TransformerFactory; 11 | import javax.xml.transform.dom.DOMSource; 12 | import javax.xml.transform.stream.StreamResult; 13 | 14 | import org.w3c.dom.Document; 15 | import org.w3c.dom.Element; 16 | 17 | public class CreateXMLFile { 18 | 19 | public static void main(String[] args) { 20 | File file = new File("src/com/andieguo/xmldemo/books.xml"); 21 | List books = ReadXMLFile.readXMLFile(file); 22 | createXMLFile(books); 23 | } 24 | 25 | public static void createXMLFile(List books) { 26 | Document doc; 27 | Element bookstore; 28 | Element book; 29 | Element title; 30 | Element author; 31 | Element year; 32 | Element price; 33 | try { 34 | DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 35 | DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder(); 36 | doc = dbBuilder.newDocument(); 37 | if (doc != null) { 38 | bookstore = doc.createElement("bookstore"); 39 | for (int i = 0; i < books.size(); i++) { 40 | book = doc.createElement("book"); 41 | book.setAttribute("category", books.get(i).getCategory()); 42 | title = doc.createElement("title"); 43 | title.appendChild(doc.createTextNode(books.get(i).getTitle())); 44 | title.setAttribute("lang", books.get(i).getTitleLang()); 45 | book.appendChild(title); 46 | String[] strAuthor = books.get(i).getAuthor().split("/"); 47 | for(int j=0;j> entrySet() { 62 | return prop.entrySet(); 63 | } 64 | 65 | public static Set keySet() { 66 | return prop.keySet(); 67 | } 68 | 69 | public static Enumeration propertyNames(){ 70 | return prop.propertyNames(); 71 | } 72 | 73 | public static void list(PrintStream out){ 74 | prop.list(out); 75 | } 76 | 77 | public static void printEntry() { 78 | Set> props = PropertiesHelper.entrySet(); 79 | for (Entry entrys : props) { 80 | System.out.println(entrys.getKey() + ":" + entrys.getValue()); 81 | } 82 | } 83 | 84 | public static void printKey() { 85 | Set keys = PropertiesHelper.keySet(); 86 | for (Object obj : keys) { 87 | System.out.println(obj + ":" + PropertiesHelper.getProperty(obj.toString())); 88 | } 89 | } 90 | 91 | public static void printEnumeration(){ 92 | Enumeration e = PropertiesHelper.propertyNames(); 93 | while(e.hasMoreElements()){ 94 | String key = (String) e.nextElement(); 95 | String value = PropertiesHelper.getProperty(key); 96 | System.out.println(key+":"+value); 97 | } 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/databasejdbc/DBConnection.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.databasejdbc; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.sql.Connection; 6 | import java.sql.DriverManager; 7 | import java.sql.PreparedStatement; 8 | import java.sql.ResultSet; 9 | import java.sql.ResultSetMetaData; 10 | import java.sql.SQLException; 11 | import java.sql.Statement; 12 | import java.util.ArrayList; 13 | import java.util.HashMap; 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.Properties; 17 | 18 | /** 19 | * 20 | * @author andieguo 21 | * 22 | */ 23 | public class DBConnection { 24 | 25 | public static Connection getConnection() { 26 | Properties props = new Properties(); 27 | FileInputStream fis = null; 28 | Connection con = null; 29 | try { 30 | fis = new FileInputStream("db.properties"); 31 | props.load(fis); 32 | Class.forName(props.getProperty("DB_DRIVER_CLASS")); 33 | con = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USERNAME"), props.getProperty("DB_PASSWORD")); 34 | }catch (Exception e) { 35 | e.printStackTrace(); 36 | } 37 | return con; 38 | } 39 | 40 | public static void closeResultSet(ResultSet rs) { 41 | if (rs != null) { 42 | try { 43 | rs.close(); 44 | rs = null; 45 | } catch (SQLException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | 51 | public static void closeStatement(Statement stm) { 52 | if (stm != null) { 53 | try { 54 | stm.close(); 55 | stm = null; 56 | } catch (SQLException e) { 57 | e.printStackTrace(); 58 | } 59 | } 60 | } 61 | 62 | public static void closePreparedStatement(PreparedStatement pstm) { 63 | if (pstm != null) { 64 | try { 65 | pstm.close(); 66 | pstm = null; 67 | } catch (SQLException e) { 68 | e.printStackTrace(); 69 | } 70 | } 71 | } 72 | 73 | public static void closeConnection(Connection con) { 74 | if (con != null) { 75 | try { 76 | con.close(); 77 | con = null; 78 | } catch (SQLException e) { 79 | e.printStackTrace(); 80 | } 81 | con = null; 82 | } 83 | } 84 | 85 | 86 | public static void close(ResultSet rs, PreparedStatement ps, Connection conn) { 87 | if (rs != null) { 88 | try { 89 | rs.close(); 90 | rs = null; 91 | } catch (SQLException e) { 92 | e.printStackTrace(); 93 | } 94 | } 95 | if (ps != null) { 96 | try { 97 | ps.close(); 98 | ps = null; 99 | } catch (SQLException e) { 100 | e.printStackTrace(); 101 | } 102 | } 103 | if (conn != null) { 104 | try { 105 | conn.close(); 106 | conn = null; 107 | } catch (SQLException e) { 108 | e.printStackTrace(); 109 | } 110 | } 111 | } 112 | 113 | 114 | public static void main(String[] args) { 115 | System.out.println(getConnection()); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/propertiesutil/PropertyParseException.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.propertiesutil; 2 | 3 | 4 | /** 5 | * Thrown on a property parse exception. Intended to report missing or invalid 6 | * properties. 7 | * 8 | * @see com.thetransactioncompany.util.PropertyRetriever 9 | * 10 | * @author Vladimir Dzhuvinov 11 | */ 12 | public class PropertyParseException 13 | extends Exception { 14 | 15 | 16 | /** 17 | * The key of the property that caused the exception, {@code null} if 18 | * unknown or not applicable. 19 | */ 20 | private final String propertyKey; 21 | 22 | 23 | /** 24 | * The value of the property that caused the exception, {@code null} if 25 | * unknown or not applicable. 26 | */ 27 | private final String propertyValue; 28 | 29 | 30 | /** 31 | * Creates a new property parse exception with the specified message. 32 | * 33 | * @param message The exception message. 34 | */ 35 | public PropertyParseException(final String message) { 36 | 37 | super(message); 38 | propertyKey = null; 39 | propertyValue = null; 40 | } 41 | 42 | 43 | /** 44 | * Creates a new property parse exception with the specified message and 45 | * property key. 46 | * 47 | * @param message The exception message. 48 | * @param propertyKey The key of the property that caused the exception, 49 | * {@code null} if unknown or not applicable. 50 | */ 51 | public PropertyParseException(final String message, final String propertyKey) { 52 | 53 | super(message); 54 | this.propertyKey = propertyKey; 55 | propertyValue = null; 56 | } 57 | 58 | 59 | /** 60 | * Creates a new property parse exception with the specified message, 61 | * property key and property value. 62 | * 63 | * @param message The exception message. 64 | * @param propertyKey The key of the property that caused the 65 | * exception, {@code null} if unknown or not 66 | * applicable. 67 | * @param propertyValue The value of the property that caused the 68 | * exception, {@code null} if unknown or not 69 | * applicable. 70 | */ 71 | public PropertyParseException(final String message, final String propertyKey, final String propertyValue) { 72 | 73 | super(message); 74 | this.propertyKey = propertyKey; 75 | this.propertyValue = propertyValue; 76 | } 77 | 78 | 79 | /** 80 | * Returns the key of the property that caused the exception, 81 | * {@code null} if unknown or not applicable. 82 | * 83 | * @return The key of the offending property. 84 | */ 85 | public String getPropertyKey() { 86 | 87 | return propertyKey; 88 | } 89 | 90 | 91 | /** 92 | * Returns the value of the property that caused the exception, 93 | * {@code null} if unknown or not applicable. 94 | * 95 | * @return The value of the offending property. 96 | */ 97 | public String getPropertyValue() { 98 | 99 | return propertyValue; 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/saxparserdemo/CreateXMLFile.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.saxparserdemo; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.util.List; 6 | 7 | import javax.xml.transform.OutputKeys; 8 | import javax.xml.transform.Transformer; 9 | import javax.xml.transform.sax.SAXTransformerFactory; 10 | import javax.xml.transform.sax.TransformerHandler; 11 | import javax.xml.transform.stream.StreamResult; 12 | 13 | import org.xml.sax.helpers.AttributesImpl; 14 | 15 | public class CreateXMLFile { 16 | 17 | 18 | public static void main(String[] args) { 19 | List books = XMLParserSAX.xmlReader(new File("src/com/andieguo/saxparserdemo/books.xml")); 20 | createXML(books); 21 | 22 | } 23 | 24 | public static void createXML(List books) { 25 | 26 | try { 27 | SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); 28 | TransformerHandler handler = factory.newTransformerHandler(); 29 | Transformer info = handler.getTransformer(); 30 | info.setOutputProperty(OutputKeys.INDENT, "yes"); 31 | info.setOutputProperty(OutputKeys.ENCODING, "utf-8"); 32 | info.setOutputProperty(OutputKeys.VERSION, "1.0"); 33 | StreamResult result = new StreamResult(new FileOutputStream(new File("src/com/andieguo/saxparserdemo/saxbooks.xml"))); 34 | handler.setResult(result); 35 | handler.startDocument(); 36 | AttributesImpl impl = new AttributesImpl(); 37 | impl.clear(); 38 | handler.startElement("", "", "bookstore", impl); 39 | for(int i=0;i keys = prop.keySet(); 106 | for(Object key:keys){ 107 | System.out.println("key:"+key.toString()+",value:"+prop.get(key)); 108 | } 109 | Set> entrys = prop.entrySet(); 110 | for(Entry entry:entrys){ 111 | System.out.println("key:"+entry.getKey()+",value:"+entry.getValue()); 112 | } 113 | Enumeration e = prop.propertyNames(); 114 | while (e.hasMoreElements()) { 115 | String key = (String) e.nextElement(); 116 | String value = prop.getProperty(key); 117 | System.out.println("Key : " + key + ", Value : " + value); 118 | } 119 | } catch (IOException ex) { 120 | ex.printStackTrace(); 121 | } finally { 122 | if (input != null) { 123 | try { 124 | input.close(); 125 | } catch (IOException e) { 126 | e.printStackTrace(); 127 | } 128 | } 129 | } 130 | } 131 | 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/lang3/SimpleJavaTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.lang3; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Arrays; 5 | import java.util.Collections; 6 | import java.util.Comparator; 7 | import java.util.HashSet; 8 | import java.util.Iterator; 9 | import java.util.List; 10 | import java.util.Set; 11 | 12 | import org.apache.commons.lang3.ArrayUtils; 13 | 14 | import com.andieguo.generics.Animal; 15 | import com.andieguo.generics.Bird; 16 | 17 | import junit.framework.Assert; 18 | import junit.framework.TestCase; 19 | 20 | /** 21 | * 来源于 http://www.programcreek.com 22 | * @author andyguo.gd 23 | * 24 | */ 25 | public class SimpleJavaTester extends TestCase { 26 | 27 | @SuppressWarnings("unused") 28 | public void testArrayDefine(){ 29 | String[] aArray = new String[5];//指定长度 30 | String[] bArray = {"a","b","c", "d", "e"}; 31 | String[] cArray = new String[]{"a","b","c","d","e"};//直接初始化,间接指定长度 32 | } 33 | 34 | /** 35 | * 数组转型 36 | */ 37 | public void testArrayPrimitive(){ 38 | // convert Integer[] to int[] 39 | Integer[] array = new Integer[]{1,2,3,4,5,6,6}; 40 | int[] primitive = ArrayUtils.toPrimitive(array); 41 | System.out.println(ArrayUtils.toString(primitive)); 42 | // convert int[] to Integer 43 | Integer[] arrayNew = ArrayUtils.toObject(primitive); 44 | System.out.println(ArrayUtils.toString(arrayNew)); 45 | } 46 | 47 | /** 48 | * convert List to int[] 49 | * 1)将List to Integer[] 50 | * 2)将Integer[] to int[] 51 | */ 52 | public void testConvert1(){ 53 | Integer[] array = new Integer[]{1,2,3,4,5,6,6}; 54 | List list = new ArrayList(Arrays.asList(array)); 55 | Integer[] arrayNew = new Integer[list.size()];//指定数组长度 56 | list.toArray(arrayNew); 57 | int[] primitiveNew = ArrayUtils.toPrimitive(arrayNew); 58 | System.out.println(ArrayUtils.toString(primitiveNew)); 59 | } 60 | 61 | /** 62 | * convert int[] to List 63 | * 1 将int[] to Integer[] 64 | * 2 将Integer[] to List 65 | */ 66 | public void testConvert2(){ 67 | int[] array = new int[]{1,2,3,4,5,6,6}; 68 | Integer[] arrayNew = ArrayUtils.toObject(array); 69 | List list = new ArrayList(Arrays.asList(arrayNew)); 70 | System.out.println(list); 71 | } 72 | 73 | /** 74 | * 将array转换成List/set 75 | */ 76 | public void testArrayToList(){ 77 | Integer[] array = new Integer[]{1,2,3,4,5,6,6}; 78 | List list = new ArrayList(Arrays.asList(array)); 79 | Set set = new HashSet(Arrays.asList(array)); 80 | list.add(7);//supported 81 | System.out.println(list); 82 | System.out.println(set); 83 | } 84 | 85 | /** 86 | * Covnert an ArrayList to an array 87 | */ 88 | public void testListToArray(){ 89 | ArrayList list = new ArrayList(Arrays.asList("a", "b", "c", "d")); 90 | String[] array = new String[list.size()];//指定数组长度 91 | list.toArray(array); 92 | System.out.println(ArrayUtils.toString(array)); 93 | } 94 | 95 | /** 96 | * asList的使用误区 97 | */ 98 | public void testAsList(){ 99 | Integer[] array = new Integer[]{1,2,3,4,5,6}; 100 | List list = Arrays.asList(array); 101 | Assert.assertEquals(true, list.contains(6));//supported 102 | list.add(7);//java.lang.UnsupportedOperationException 103 | System.out.println(list); 104 | } 105 | 106 | /** 107 | * 从array中remove元素 108 | */ 109 | public void testRemoveElemFromArray(){ 110 | String[] array = {"one", "three", "two", "four"}; 111 | array = ArrayUtils.remove(array, 0); 112 | array = ArrayUtils.removeElement(array, "four");//一定要重新赋值给array 113 | System.out.println(ArrayUtils.toString(array)); 114 | } 115 | 116 | /** 117 | * 从List中remove元素 118 | */ 119 | public void testRemoveElemFromList(){ 120 | ArrayList list = new ArrayList(Arrays.asList("a", "b", "c", "d")); 121 | Iterator iterator = list.iterator(); 122 | while(iterator.hasNext()){ 123 | String elm = iterator.next(); 124 | if(elm.equals("a")){ 125 | iterator.remove(); 126 | } 127 | } 128 | System.out.println(list); 129 | } 130 | 131 | /** 132 | * Reverse an array 133 | */ 134 | public void testReverseArray(){ 135 | String[] array = {"one", "three", "two", "four"}; 136 | ArrayUtils.reverse(array); 137 | System.out.println(ArrayUtils.toString(array)); 138 | } 139 | 140 | /** 141 | * Reverse an list 142 | */ 143 | public void testReverseList(){ 144 | //TODO 145 | } 146 | 147 | public void testSortArray(){ 148 | String[] array = {"one", "three", "two", "four"}; 149 | //打印字符串数组 150 | System.out.println("source:"+ArrayUtils.toString(array)); 151 | //binarySearch使用的是compareTo比较方法 152 | System.out.println("index:"+Arrays.binarySearch(array, "one")); 153 | Arrays.sort(array); 154 | System.out.println("sort1:"+ArrayUtils.toString(array)); 155 | System.out.println("index:"+Arrays.binarySearch(array, "one")); 156 | Arrays.sort(array, new Comparator() { 157 | 158 | public int compare(String o1, String o2) { 159 | // TODO Auto-generated method stub 160 | return o2.compareTo(o1); 161 | } 162 | 163 | }); 164 | System.out.println("sort2:"+ArrayUtils.toString(array)); 165 | System.out.println("index:"+Arrays.binarySearch(array, "one")); 166 | } 167 | 168 | public void testSortArrayObject(){ 169 | //public static void sort(T[] a,Comparator c) 170 | Animal[] array = {new Animal(1,2),new Animal(2,3),new Animal(3,4)}; 171 | List list = new ArrayList(Arrays.asList(array)); 172 | Comparator comparator = new Comparator() { 173 | 174 | public int compare(Animal o1, Animal o2) { 175 | // TODO Auto-generated method stub 176 | return o2.getSize().compareTo(o1.getSize()); 177 | } 178 | }; 179 | list.sort(comparator); 180 | System.out.println(list); 181 | 182 | Bird[] birdArray = {new Bird(10,20),new Bird(30,40),new Bird(50,60)}; 183 | List birdList = new ArrayList(Arrays.asList(birdArray)); 184 | birdList.sort(comparator); 185 | System.out.println(birdList); 186 | } 187 | 188 | public void testCollection(){ 189 | Collections.emptyList(); 190 | Collections.copy(null, null); 191 | Collections.sort(null); 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/lang3/UtilsTester.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.lang3; 2 | 3 | import java.util.Date; 4 | import java.util.Map; 5 | 6 | import org.apache.commons.lang3.ArrayUtils; 7 | import org.apache.commons.lang3.BooleanUtils; 8 | import org.apache.commons.lang3.RandomStringUtils; 9 | import org.apache.commons.lang3.RandomUtils; 10 | import org.apache.commons.lang3.SerializationUtils; 11 | import org.apache.commons.lang3.StringUtils; 12 | import org.apache.commons.lang3.SystemUtils; 13 | import org.apache.commons.lang3.Validate; 14 | import org.apache.commons.lang3.builder.ToStringBuilder; 15 | import org.apache.commons.lang3.builder.ToStringStyle; 16 | import org.apache.commons.lang3.math.NumberUtils; 17 | import org.apache.commons.lang3.time.DateFormatUtils; 18 | import org.apache.commons.lang3.time.DateUtils; 19 | import org.apache.commons.lang3.tuple.MutablePair; 20 | import org.apache.commons.lang3.tuple.MutableTriple; 21 | 22 | import com.andieguo.generics.Animal; 23 | 24 | import junit.framework.Assert; 25 | import junit.framework.TestCase; 26 | 27 | public class UtilsTester extends TestCase { 28 | 29 | public void testArrayUtils(){ 30 | String[][] color = new String[][]{{"RED", "#FF0000"},{"GREEN", "#00FF00"},{"BLUE", "#0000FF"}}; 31 | Map colorMap = ArrayUtils.toMap(color); 32 | System.out.println(colorMap); 33 | } 34 | 35 | public void testToString(){ 36 | String[] numbers = new String[]{"1","2","3",null}; 37 | String[][] color = new String[][]{{"RED", "#FF0000"},{"GREEN", "#00FF00"},{"BLUE", "#0000FF"}}; 38 | System.out.println(new ToStringBuilder(numbers, ToStringStyle.DEFAULT_STYLE).append(numbers).toString()); 39 | System.out.println(ArrayUtils.toString(numbers)); 40 | System.out.println(ArrayUtils.toString(color)); 41 | } 42 | 43 | public void testEqual(){ 44 | String[] numbers = new String[]{"1","2","3"}; 45 | String[] numbersNew = new String[]{"2","1","3"}; 46 | Assert.assertEquals(false, ArrayUtils.isEquals(numbers, numbersNew)); 47 | } 48 | 49 | public void testToArray(){ 50 | Integer[] result = ArrayUtils.toArray(1,2,3,4); 51 | System.out.println(ArrayUtils.toString(result)); 52 | } 53 | 54 | public void testBooleanUtils(){ 55 | //对于isFalse方法而言,只有值为false才返回true 56 | Assert.assertEquals(true, BooleanUtils.isFalse(false)); 57 | Assert.assertEquals(false, BooleanUtils.isFalse(true)); 58 | Assert.assertEquals(false, BooleanUtils.isFalse(null)); 59 | Assert.assertEquals(1, BooleanUtils.toInteger(Boolean.TRUE, 1, 0, 2)); 60 | Assert.assertEquals(0, BooleanUtils.toInteger(Boolean.FALSE, 1, 0, 2)); 61 | Assert.assertEquals(2, BooleanUtils.toInteger(null, 1, 0, 2)); 62 | } 63 | 64 | public void testToStringBuilder(){ 65 | System.out.println(ToStringBuilder.reflectionToString(new Animal("cat"),ToStringStyle.DEFAULT_STYLE)); 66 | System.out.println(ToStringBuilder.reflectionToString(new Animal("cat"),ToStringStyle.SHORT_PREFIX_STYLE)); 67 | } 68 | 69 | /** 70 | * commons lang3.3发布之后便有了这个类,用于产生一个范围内的随机数。 71 | */ 72 | public void testRandomUtils(){ 73 | RandomUtils.nextInt(0,10); 74 | RandomUtils.nextDouble(0.0, 10.0); 75 | //产生5位长度的随机字符串,中文环境下是乱码 76 | RandomStringUtils.random(5); 77 | //使用指定的字符生成5位长度的随机字符串 78 | RandomStringUtils.random(5, new char[]{'a','b','c','d','e','f', '1', '2', '3'}); 79 | //生成指定长度的字母和数字的随机组合字符串 80 | RandomStringUtils.randomAlphanumeric(5); 81 | //生成随机数字字符串 82 | RandomStringUtils.randomNumeric(5); 83 | //生成随机[a-z]字符串,包含大小写 84 | RandomStringUtils.randomAlphabetic(5); 85 | //生成从ASCII 32到126组成的随机字符串 86 | RandomStringUtils.randomAscii(4); 87 | } 88 | 89 | /** 90 | * 它的所有操作都不会抛出异常,如果转换不成功返回0,0.0d,0.0f等形式。转换操作也可以指定默认值 91 | */ 92 | public void testNumberUtils(){ 93 | //判断字符串是否为数字 94 | Assert.assertEquals(true, NumberUtils.isNumber("2.3212")); 95 | Assert.assertEquals(false, NumberUtils.isNumber("hello")); 96 | Assert.assertEquals(false, NumberUtils.isNumber(null)); 97 | //将字符串转换为LONG 98 | Assert.assertEquals(1L, NumberUtils.toLong(null, 1L)); 99 | Assert.assertEquals(1L, NumberUtils.toLong("hello", 1L)); 100 | Assert.assertEquals(2L, NumberUtils.toLong("2", 1L)); 101 | Assert.assertEquals(0L, NumberUtils.toLong(null)); 102 | Assert.assertEquals(0L, NumberUtils.toLong("hello")); 103 | Assert.assertEquals(2L, NumberUtils.toLong("2")); 104 | //判断字符串是否全为数字 105 | Assert.assertEquals(false, NumberUtils.isDigits("0000000000.596")); 106 | Assert.assertEquals(true, NumberUtils.isDigits("0000000000596")); 107 | } 108 | 109 | /** 110 | * 包含判断是否为空,trim及查找字符,分割,联合,子集,取得索引,切换大小写,替换,删除等功能 111 | 及其判断是否为数字,是否为字符等 112 | StringUtils.isNotBlank(null) = false 113 | StringUtils.isNotBlank("") = false 114 | StringUtils.isNotBlank(" ") = false 115 | StringUtils.isNotBlank("bob") = true 116 | StringUtils.isNotBlank(" bob ") = true 117 | 118 | */ 119 | public void testStringUtils(){ 120 | Assert.assertEquals(true, StringUtils.isNotBlank("hello")); 121 | Assert.assertEquals(false, StringUtils.isNotBlank("")); 122 | //判断字符串是否全为数字 123 | Assert.assertEquals(false, StringUtils.isNumeric("12.3")); 124 | Assert.assertEquals(true, StringUtils.isNumeric("123")); 125 | } 126 | 127 | public void testSystemUtils(){ 128 | System.out.println(SystemUtils.getJavaHome().getAbsolutePath()); 129 | System.out.println(SystemUtils.getUserHome().getAbsolutePath()); 130 | } 131 | 132 | /** 133 | * 增强的功能:深拷贝,方便的反序列化Deserialize ,序列化Serialize 等。 134 | */ 135 | public void testSerializationUtils(){ 136 | SchoolBean schoolBean = new SchoolBean(); 137 | schoolBean.setName("第二中学"); 138 | schoolBean.setTeacher(new TeacherBean("校长")); 139 | SchoolBean newSchoolBean = SerializationUtils.clone(schoolBean); 140 | System.out.println(schoolBean); 141 | System.out.println(newSchoolBean); 142 | } 143 | 144 | public void testDateFormatUtils(){ 145 | System.out.println(DateFormatUtils.ISO_DATETIME_FORMAT.format(new Date()));//2016-11-26T08:47:37 146 | System.out.println(DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT.format(new Date()));//2016-11-26T08:47:37 147 | System.out.println(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));//2016-11-26T08:47:37 148 | System.out.println(DateFormatUtils.format(DateUtils.addDays(new Date(), 1), "yyyy-MM-dd HH:mm:ss"));//2016-11-26T08:47:37 149 | } 150 | 151 | /** 152 | * 就是提供了支持返回多个元素的一些类 153 | * Guava的Maps.immutableEntry 154 | * Map.Entry entry2 = Maps.immutableEntry("rensanning.iteye.com", 9527); 155 | * MutableTriple对象是可以比较的 156 | * 元组和列表list一样,都可能用于数据存储,包含多个数据;但是和列表不同的是:列表只能存储相同的数据类型, 157 | * 而元组不一样,它可以存储不同的数据类型,比如同时存储int、string、list等,并且可以根据需求无限扩展。 158 | * 当在一个方法中, 你需要返回几个对象,这几个对象的类型一致,你可以返回一个数组;如果几个对象的类型不同呢,当然你可以返回一个Object[]数组,可是这样在使用结果数组的时候,就需要强转对象的类型,会导致类型不安全;也可以定义一个dto,当多个场景下需要使用的不同,需要定义多个dto,这样会类爆炸,而且重用率极低;在非常接近Java语言的Scala里有元组的定义:val t = (1, 3.14, "Fred"),就是一个不同类型的数据放到一个线性集合里,在Java里我们可以模拟出一个类似的结构,以适合上面的场景 159 | */ 160 | public void testMuttableTriple(){ 161 | MutablePair monday = new MutablePair("星期一",0); 162 | System.out.println(monday.getLeft()); 163 | System.out.println(monday.getRight()); 164 | MutableTriple student = new MutableTriple("婧哥哥","郭婧","郭大侠"); 165 | System.out.println(student.getLeft()); 166 | } 167 | 168 | /** 169 | * 前置校验,校验失败报IllegalArgumentException异常 170 | */ 171 | public void testValidate(){ 172 | int i = 1; 173 | Validate.isTrue(i > 0, "The value must be greater than zero: %d", i); 174 | Validate.isTrue(i < 0, "The value must be greater than zero: %d", i); 175 | Validate.notNull("hello", "The surname must not be %s", "null"); 176 | Validate.notNull("", "The surname must not be %s", "null"); 177 | } 178 | 179 | } 180 | -------------------------------------------------------------------------------- /src/main/java/com/andieguo/propertiesutil/PropertyRetrieverTest.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.propertiesutil; 2 | 3 | 4 | import java.net.URL; 5 | import java.util.Properties; 6 | 7 | import junit.framework.TestCase; 8 | 9 | 10 | /** 11 | * Tests the property retriever class. 12 | * 13 | * @author Vladimir Dzhuvinov 14 | */ 15 | public class PropertyRetrieverTest extends TestCase { 16 | 17 | 18 | public void testGetBoolean() 19 | throws Exception { 20 | 21 | Properties props = new Properties(); 22 | props.setProperty("app.enable", "true"); 23 | props.setProperty("app.reload", "false"); 24 | 25 | PropertyRetriever pr = new PropertyRetriever(props); 26 | 27 | assertTrue(pr.getBoolean("app.enable")); 28 | assertFalse(pr.getBoolean("app.reload")); 29 | 30 | try { 31 | pr.getBoolean("app.disable"); 32 | fail(); 33 | } catch (PropertyParseException e) { 34 | assertEquals("app.disable", e.getPropertyKey()); 35 | } 36 | } 37 | 38 | 39 | public void testGetOptBoolean() 40 | throws Exception { 41 | 42 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 43 | 44 | assertTrue(pr.getOptBoolean("app.enable", true)); 45 | } 46 | 47 | 48 | public void testGetOptBooleanEmpty() 49 | throws Exception { 50 | 51 | Properties props = new Properties(); 52 | props.setProperty("app.enable", " "); 53 | 54 | PropertyRetriever pr = new PropertyRetriever(props); 55 | 56 | assertTrue(pr.getOptBoolean("app.enable", true)); 57 | } 58 | 59 | 60 | public void testGetInt() 61 | throws Exception { 62 | 63 | Properties props = new Properties(); 64 | props.setProperty("app.threadCount", "10"); 65 | 66 | PropertyRetriever pr = new PropertyRetriever(props); 67 | 68 | assertEquals(10, pr.getInt("app.threadCount")); 69 | 70 | try { 71 | pr.getInt("app.someCount"); 72 | fail(); 73 | } catch (PropertyParseException e) { 74 | assertEquals("app.someCount", e.getPropertyKey()); 75 | } 76 | } 77 | 78 | 79 | public void testgetOptInt() 80 | throws Exception { 81 | 82 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 83 | 84 | assertEquals(10, pr.getOptInt("app.threadCount", 10)); 85 | } 86 | 87 | 88 | public void testgetOptIntEmpty() 89 | throws Exception { 90 | 91 | Properties props = new Properties(); 92 | props.setProperty("app.threadCount", " "); 93 | 94 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 95 | 96 | assertEquals(10, pr.getOptInt("app.threadCount", 10)); 97 | } 98 | 99 | 100 | public void testGetLong() 101 | throws Exception { 102 | 103 | Properties props = new Properties(); 104 | props.setProperty("app.timeout", "1000"); 105 | 106 | PropertyRetriever pr = new PropertyRetriever(props); 107 | 108 | assertEquals(1000l, pr.getLong("app.timeout")); 109 | 110 | try { 111 | pr.getInt("app.someTimeout"); 112 | fail(); 113 | } catch (PropertyParseException e) { 114 | assertEquals("app.someTimeout", e.getPropertyKey()); 115 | } 116 | } 117 | 118 | 119 | public void testGetOptLong() 120 | throws Exception { 121 | 122 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 123 | 124 | assertEquals(1000l, pr.getOptLong("app.timeout", 1000l)); 125 | } 126 | 127 | 128 | public void testGetOptLongEmpty() 129 | throws Exception { 130 | 131 | Properties props = new Properties(); 132 | props.setProperty("app.timeout", " "); 133 | 134 | PropertyRetriever pr = new PropertyRetriever(props); 135 | 136 | assertEquals(1000l, pr.getOptLong("app.timeout", 1000l)); 137 | } 138 | 139 | 140 | public void testGetFloat() 141 | throws Exception { 142 | 143 | Properties props = new Properties(); 144 | props.setProperty("app.pi", "3.14"); 145 | 146 | PropertyRetriever pr = new PropertyRetriever(props); 147 | 148 | assertEquals(new Float("3.14"), pr.getFloat("app.pi")); 149 | 150 | try { 151 | pr.getInt("app.someFloat"); 152 | fail(); 153 | } catch (PropertyParseException e) { 154 | assertEquals("app.someFloat", e.getPropertyKey()); 155 | } 156 | } 157 | 158 | 159 | public void testGetOptFloat() 160 | throws Exception { 161 | 162 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 163 | 164 | assertEquals(new Float("3.14"), pr.getOptFloat("app.pi", new Float(3.14))); 165 | } 166 | 167 | 168 | public void testGetString() 169 | throws Exception { 170 | 171 | Properties props = new Properties(); 172 | props.setProperty("app.name", "CoolApp"); 173 | 174 | PropertyRetriever pr = new PropertyRetriever(props); 175 | 176 | assertEquals("CoolApp", pr.getString("app.name")); 177 | 178 | try { 179 | pr.getInt("app.someString"); 180 | fail(); 181 | } catch (PropertyParseException e) { 182 | assertEquals("app.someString", e.getPropertyKey()); 183 | } 184 | } 185 | 186 | 187 | public void testGetOptString() 188 | throws Exception { 189 | 190 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 191 | 192 | assertEquals("CoolApp", pr.getOptString("app.name", "CoolApp")); 193 | } 194 | 195 | 196 | public void testGetOptStringEmpty() 197 | throws Exception { 198 | 199 | Properties props = new Properties(); 200 | props.setProperty("app.name", " "); 201 | 202 | PropertyRetriever pr = new PropertyRetriever(props); 203 | 204 | assertEquals("CoolApp", pr.getOptString("app.name", "CoolApp")); 205 | } 206 | 207 | 208 | public void testGetEnumString() 209 | throws Exception { 210 | 211 | Properties props = new Properties(); 212 | props.setProperty("app.color", "red"); 213 | 214 | PropertyRetriever pr = new PropertyRetriever(props); 215 | 216 | String[] colors = {"red", "green", "blue"}; 217 | 218 | assertEquals("red", pr.getEnumString("app.color", colors)); 219 | } 220 | 221 | 222 | public void testGetOptEnumString() 223 | throws Exception { 224 | 225 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 226 | 227 | String[] colors = {"red", "green", "blue"}; 228 | 229 | assertEquals("red", pr.getOptEnumString("app.color", colors, "red")); 230 | } 231 | 232 | 233 | public void testGetOptEnumStringEmpty() 234 | throws Exception { 235 | 236 | Properties props = new Properties(); 237 | props.setProperty("app.color", " "); 238 | 239 | PropertyRetriever pr = new PropertyRetriever(props); 240 | 241 | String[] colors = {"red", "green", "blue"}; 242 | 243 | assertEquals("red", pr.getOptEnumString("app.color", colors, "red")); 244 | } 245 | 246 | 247 | public void testGetEnum() 248 | throws Exception { 249 | 250 | Properties props = new Properties(); 251 | props.setProperty("app.timeUnit", "SECONDS"); 252 | 253 | PropertyRetriever pr = new PropertyRetriever(props); 254 | 255 | assertEquals(java.util.concurrent.TimeUnit.SECONDS, pr.getEnum("app.timeUnit", java.util.concurrent.TimeUnit.class)); 256 | } 257 | 258 | 259 | public void testGetOptEnum() 260 | throws Exception { 261 | 262 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 263 | 264 | assertEquals(java.util.concurrent.TimeUnit.SECONDS, 265 | pr.getOptEnum("app.timeUnit", 266 | java.util.concurrent.TimeUnit.class, 267 | java.util.concurrent.TimeUnit.SECONDS)); 268 | } 269 | 270 | 271 | public void testGetOptEnumEmpty() 272 | throws Exception { 273 | 274 | Properties props = new Properties(); 275 | props.setProperty("app.timeUnit", " "); 276 | 277 | PropertyRetriever pr = new PropertyRetriever(props); 278 | 279 | assertEquals(java.util.concurrent.TimeUnit.SECONDS, 280 | pr.getOptEnum("app.timeUnit", 281 | java.util.concurrent.TimeUnit.class, 282 | java.util.concurrent.TimeUnit.SECONDS)); 283 | } 284 | 285 | 286 | public void testGetURL() 287 | throws Exception { 288 | 289 | Properties props = new Properties(); 290 | props.setProperty("app.url", "http://app.com"); 291 | 292 | PropertyRetriever pr = new PropertyRetriever(props); 293 | 294 | assertEquals(new URL("http://app.com"), pr.getURL("app.url")); 295 | } 296 | 297 | 298 | public void testGetOptURL() 299 | throws Exception { 300 | 301 | PropertyRetriever pr = new PropertyRetriever(new Properties()); 302 | 303 | assertEquals(new URL("http://app.com"), pr.getOptURL("app.url", new URL("http://app.com"))); 304 | } 305 | 306 | 307 | public void testGetOptURLEmpty() 308 | throws Exception { 309 | 310 | Properties props = new Properties(); 311 | props.setProperty("app.url", " "); 312 | 313 | PropertyRetriever pr = new PropertyRetriever(props); 314 | 315 | assertEquals(new URL("http://app.com"), pr.getOptURL("app.url", new URL("http://app.com"))); 316 | } 317 | } -------------------------------------------------------------------------------- /src/main/java/com/andieguo/propertiesutil/PropertyRetriever.java: -------------------------------------------------------------------------------- 1 | package com.andieguo.propertiesutil; 2 | 3 | 4 | import java.net.MalformedURLException; 5 | import java.net.URL; 6 | import java.util.Properties; 7 | 8 | 9 | /** 10 | * Provides typed retrieval of {@link java.util.Properties} as {@code boolean}, 11 | * {@code int}, {@code long}, {@code float}, {@code double}, 12 | * {@link java.lang.String}, {@link java.net.URL} or {@code enum} values. 13 | * 14 | * @author Vladimir Dzhuvinov 15 | */ 16 | public class PropertyRetriever { 17 | 18 | 19 | /** 20 | * The property hashtable to parse. 21 | */ 22 | private Properties props; 23 | 24 | 25 | /** 26 | * Creates a new retriever for the specified properties. 27 | * 28 | * @param props The properties hasthtable. 29 | */ 30 | public PropertyRetriever(final Properties props) { 31 | 32 | this.props = props; 33 | } 34 | 35 | 36 | /** 37 | * Retrieves a boolean value. 38 | * 39 | * @param key The property name. 40 | * 41 | * @return The property as a boolean value. 42 | * 43 | * @throws PropertyParseException On a missing or invalid property. 44 | */ 45 | public boolean getBoolean(final String key) 46 | throws PropertyParseException { 47 | 48 | String value = props.getProperty(key); 49 | 50 | if (value == null) 51 | throw new PropertyParseException("Missing property", key); 52 | 53 | if (value.equalsIgnoreCase("true")) 54 | return true; 55 | 56 | else if (value.equalsIgnoreCase("false")) 57 | return false; 58 | 59 | else 60 | throw new PropertyParseException("Invalid boolean property", key, value); 61 | } 62 | 63 | 64 | /** 65 | * Retrieves an optional boolean value. 66 | * 67 | * @param key The property name. 68 | * @param def The default value if the property value is undefined or 69 | * empty. 70 | * 71 | * @return The property as a boolean. 72 | * 73 | * @throws PropertyParseException On an invalid property. 74 | */ 75 | public boolean getOptBoolean(final String key, final boolean def) 76 | throws PropertyParseException { 77 | 78 | String value = props.getProperty(key); 79 | 80 | if (value == null || value.trim().isEmpty()) 81 | return def; 82 | 83 | if (value.equalsIgnoreCase("true")) 84 | return true; 85 | 86 | if (value.equalsIgnoreCase("false")) 87 | return false; 88 | 89 | throw new PropertyParseException("Invalid boolean property", key, value); 90 | } 91 | 92 | 93 | /** 94 | * Retrieves an integer value. 95 | * 96 | * @param key The property name. 97 | * 98 | * @return The property as an integer. 99 | * 100 | * @throws PropertyParseException On a missing or invalid property. 101 | */ 102 | public int getInt(final String key) 103 | throws PropertyParseException { 104 | 105 | String value = props.getProperty(key); 106 | 107 | if (value == null) 108 | throw new PropertyParseException("Missing property", key); 109 | 110 | try { 111 | return Integer.parseInt(value); 112 | 113 | } catch (NumberFormatException e) { 114 | 115 | throw new PropertyParseException("Invalid int property", key, value); 116 | } 117 | } 118 | 119 | 120 | /** 121 | * Retrieves an optional integer value. 122 | * 123 | * @param key The property name. 124 | * @param def The default value if the property value is undefined or 125 | * empty. 126 | * 127 | * @return The property as an integer. 128 | * 129 | * @throws PropertyParseException On an invalid property. 130 | */ 131 | public int getOptInt(final String key, final int def) 132 | throws PropertyParseException { 133 | 134 | String value = props.getProperty(key); 135 | 136 | if (value == null || value.trim().isEmpty()) 137 | return def; 138 | 139 | try { 140 | return Integer.parseInt(value); 141 | 142 | } catch (NumberFormatException e) { 143 | 144 | throw new PropertyParseException("Invalid int property", key); 145 | } 146 | } 147 | 148 | 149 | /** 150 | * Retrieves a long value. 151 | * 152 | * @param key The property name. 153 | * 154 | * @return The property as a long. 155 | * 156 | * @throws PropertyParseException On a missing or invalid property. 157 | */ 158 | public long getLong(final String key) 159 | throws PropertyParseException { 160 | 161 | String value = props.getProperty(key); 162 | 163 | if (value == null) 164 | throw new PropertyParseException("Missing property", key); 165 | 166 | try { 167 | return Long.parseLong(value); 168 | 169 | } catch (NumberFormatException e) { 170 | 171 | throw new PropertyParseException("Invalid long property", key, value); 172 | } 173 | } 174 | 175 | 176 | /** 177 | * Retrieves an optional long value. 178 | * 179 | * @param key The property name. 180 | * @param def The default value if the property value is undefined or 181 | * empty. 182 | * 183 | * @return The property as a long. 184 | * 185 | * @throws PropertyParseException On an invalid property. 186 | */ 187 | public long getOptLong(final String key, final long def) 188 | throws PropertyParseException { 189 | 190 | String value = props.getProperty(key); 191 | 192 | if (value == null || value.trim().isEmpty()) 193 | return def; 194 | 195 | try { 196 | return Long.parseLong(value); 197 | 198 | } catch (NumberFormatException e) { 199 | 200 | throw new PropertyParseException("Invalid long property", key, value); 201 | } 202 | } 203 | 204 | 205 | /** 206 | * Retrieves a float value. 207 | * 208 | * @param key The property name. 209 | * 210 | * @return The property as a float. 211 | * 212 | * @throws PropertyParseException On a missing or invalid property. 213 | */ 214 | public float getFloat(final String key) 215 | throws PropertyParseException { 216 | 217 | String value = props.getProperty(key); 218 | 219 | if (value == null) 220 | throw new PropertyParseException("Missing property", key); 221 | 222 | try { 223 | return Float.parseFloat(value); 224 | 225 | } catch (NumberFormatException e) { 226 | 227 | throw new PropertyParseException("Invalid float property", key, value); 228 | } 229 | } 230 | 231 | 232 | /** 233 | * Retrieves an optional float value. 234 | * 235 | * @param key The property name. 236 | * @param def The default value if the property value is undefined or 237 | * empty. 238 | * 239 | * @return The property as a float. 240 | * 241 | * @throws PropertyParseException On an invalid property. 242 | */ 243 | public float getOptFloat(final String key, final float def) 244 | throws PropertyParseException { 245 | 246 | String value = props.getProperty(key); 247 | 248 | if (value == null || value.trim().isEmpty()) 249 | return def; 250 | 251 | try { 252 | return Float.parseFloat(value); 253 | 254 | } catch (NumberFormatException e) { 255 | 256 | throw new PropertyParseException("Invalid float property", key, value); 257 | } 258 | } 259 | 260 | 261 | /** 262 | * Retrieves a double value. 263 | * 264 | * @param key The property name. 265 | * 266 | * @return The property as a double. 267 | * 268 | * @throws PropertyParseException On a missing or invalid property. 269 | */ 270 | public double getDouble(final String key) 271 | throws PropertyParseException { 272 | 273 | String value = props.getProperty(key); 274 | 275 | if (value == null) 276 | throw new PropertyParseException("Missing property", key); 277 | 278 | try { 279 | return Double.parseDouble(value); 280 | 281 | } catch (NumberFormatException e) { 282 | 283 | throw new PropertyParseException("Invalid double property", key, value); 284 | } 285 | } 286 | 287 | 288 | /** 289 | * Retrieves an optional double value. 290 | * 291 | * @param key The property name. 292 | * @param def The default value if the property value is undefined or 293 | * empty. 294 | * 295 | * @return The property as a double. 296 | * 297 | * @throws PropertyParseException On an invalid property. 298 | */ 299 | public double getOptDouble(final String key, final double def) 300 | throws PropertyParseException { 301 | 302 | String value = props.getProperty(key); 303 | 304 | if (value == null || value.trim().isEmpty()) 305 | return def; 306 | 307 | try { 308 | return Double.parseDouble(value); 309 | 310 | } catch (NumberFormatException e) { 311 | 312 | throw new PropertyParseException("Invalid double property", key, value); 313 | } 314 | } 315 | 316 | 317 | /** 318 | * Retrieves a string value. 319 | * 320 | * @param key The property name. 321 | * 322 | * @return The property as a string. 323 | * 324 | * @throws PropertyParseException On a missing or invalid property. 325 | */ 326 | public String getString(final String key) 327 | throws PropertyParseException { 328 | 329 | String value = props.getProperty(key); 330 | 331 | if (value == null) 332 | throw new PropertyParseException("Missing property", key); 333 | 334 | return value; 335 | } 336 | 337 | 338 | /** 339 | * Retrieves an optional string value. 340 | * 341 | * @param key The property name. 342 | * @param def The default value if the property value is undefined or 343 | * empty. 344 | * 345 | * @return The property as a string. 346 | * 347 | * @throws PropertyParseException On an invalid property. 348 | */ 349 | public String getOptString(final String key, final String def) 350 | throws PropertyParseException { 351 | 352 | String value = props.getProperty(key); 353 | 354 | if (value == null || value.trim().isEmpty()) 355 | return def; 356 | 357 | return value; 358 | } 359 | 360 | 361 | /** 362 | * Retrieves an enumerated string value. String case is ignored during 363 | * comparison. 364 | * 365 | * @param key The property name. 366 | * @param enums A string array defining the acceptable values. 367 | * 368 | * @return The property as a string. 369 | * 370 | * @throws PropertyParseException On a missing or invalid property. 371 | */ 372 | public String getEnumString(final String key, final String[] enums) 373 | throws PropertyParseException { 374 | 375 | String value = props.getProperty(key); 376 | 377 | if (value == null) 378 | throw new PropertyParseException("Missing property", key); 379 | 380 | for (String en: enums) { 381 | 382 | if (en.equalsIgnoreCase(value)) 383 | return value; 384 | } 385 | 386 | throw new PropertyParseException("Invalid enum string property", key, value); 387 | } 388 | 389 | 390 | /** 391 | * Retrieves an enumerated string value. String case is ignored during 392 | * comparison. 393 | * 394 | * @param key The property name. 395 | * @param enums A string array defining the acceptable values. 396 | * @param def The default value if the property value is undefined or 397 | * empty. 398 | * 399 | * @return The property as a string. 400 | * 401 | * @throws PropertyParseException On an invalid property. 402 | */ 403 | public String getOptEnumString(final String key, final String[] enums, final String def) 404 | throws PropertyParseException { 405 | 406 | String value = props.getProperty(key); 407 | 408 | if (value == null || value.trim().isEmpty()) 409 | return def; 410 | 411 | for (String en: enums) { 412 | 413 | if (en.equalsIgnoreCase(value)) 414 | return value; 415 | } 416 | 417 | throw new PropertyParseException("Invalid enum string property", key, value); 418 | } 419 | 420 | 421 | /** 422 | * Retrieves an enumerated constant. String case is ignored during 423 | * comparison. 424 | * 425 | * @param key The property name. 426 | * @param enumClass The enumeration class specifying the acceptable 427 | * values. 428 | * 429 | * @return The matching enumerated constant. 430 | * 431 | * @throws PropertyParseException On a missing or invalid property. 432 | */ 433 | public > T getEnum(final String key, final Class enumClass) 434 | throws PropertyParseException { 435 | 436 | String value = props.getProperty(key); 437 | 438 | if (value == null) 439 | throw new PropertyParseException("Missing property", key); 440 | 441 | for (T en: enumClass.getEnumConstants()) { 442 | 443 | if (en.toString().equalsIgnoreCase(value)) 444 | return en; 445 | } 446 | 447 | // No match? -> raise exception 448 | throw new PropertyParseException("Invalid enum property", key, value); 449 | } 450 | 451 | 452 | /** 453 | * Retrieves an optional enumerated constant. String case is ignored 454 | * during comparison. 455 | * 456 | * @param key The property name. 457 | * @param enumClass The enumeration class specifying the acceptable 458 | * values. 459 | * @param def The default value if the property value is 460 | * undefined or empty. 461 | * 462 | * @return The matching enumerated constant. 463 | * 464 | * @throws PropertyParseException On a missing or invalid property. 465 | */ 466 | public > T getOptEnum(final String key, final Class enumClass, final T def) 467 | throws PropertyParseException { 468 | 469 | String value = props.getProperty(key); 470 | 471 | if (value == null || value.trim().isEmpty()) 472 | return def; 473 | 474 | for (T en: enumClass.getEnumConstants()) { 475 | 476 | if (en.toString().equalsIgnoreCase(value)) 477 | return en; 478 | } 479 | 480 | // No match? -> raise exception 481 | throw new PropertyParseException("Invalid enum property", key, value); 482 | } 483 | 484 | 485 | /** 486 | * Retrieves a URL value. 487 | * 488 | * @param key The property name. 489 | * 490 | * @return The property as a URL. 491 | * 492 | * @throws PropertyParseException On a missing or invalid property. 493 | */ 494 | public URL getURL(final String key) 495 | throws PropertyParseException { 496 | 497 | String value = props.getProperty(key); 498 | 499 | if (value == null) 500 | throw new PropertyParseException("Missing property", key); 501 | 502 | try { 503 | return new URL(value); 504 | 505 | } catch (MalformedURLException e) { 506 | 507 | throw new PropertyParseException("Invalid URL property: " + e.getMessage(), key, value); 508 | } 509 | } 510 | 511 | 512 | /** 513 | * Retrieves an optional URL value. 514 | * 515 | * @param key The property name. 516 | * @param def The default value if the property value is undefined or 517 | * empty. 518 | * 519 | * @return The property as a URL. 520 | * 521 | * @throws PropertyParseException On an invalid property. 522 | */ 523 | public URL getOptURL(final String key, final URL def) 524 | throws PropertyParseException { 525 | 526 | String value = props.getProperty(key); 527 | 528 | if (value == null || value.trim().isEmpty()) 529 | return def; 530 | 531 | try { 532 | return new URL(value); 533 | 534 | } catch (MalformedURLException e) { 535 | 536 | throw new PropertyParseException("Invalid URL property: " + e.getMessage(), key, value); 537 | } 538 | } 539 | } 540 | --------------------------------------------------------------------------------