KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > IntCounter


1 /*
2  * Created on Mar 13, 2006
3  */

4 package com.openedit.util;
5
6 import java.io.File JavaDoc;
7 import java.io.FileInputStream JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.IOException JavaDoc;
10 import java.util.Properties JavaDoc;
11
12 import com.openedit.OpenEditRuntimeException;
13
14 public class IntCounter
15 {
16     File JavaDoc fieldCounterFile;
17     
18     public synchronized int incrementCount()
19     {
20         try
21         {
22             int i = getCustomerIdCounter();
23             i++;
24             saveCount(i);
25             return i;
26         } catch (IOException JavaDoc ex)
27         {
28             throw new OpenEditRuntimeException(ex);
29         }
30     }
31
32     /**
33      * @throws IOException
34      */

35     protected void saveCount(int inCount) throws IOException JavaDoc
36     {
37         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(getCounterFile());
38         try
39         {
40             Properties JavaDoc fieldCustomerIdCounter = new Properties JavaDoc();
41             fieldCustomerIdCounter.setProperty("currentCount",String.valueOf(inCount));
42             fieldCustomerIdCounter.store(out,"");
43         }
44         finally
45         {
46             out.close();
47         }
48     }
49
50     protected synchronized int getCustomerIdCounter() throws IOException JavaDoc, IllegalStateException JavaDoc
51     {
52         Properties JavaDoc fieldCustomerIdCounter = new Properties JavaDoc();
53         if ( !getCounterFile().exists() )
54         {
55             saveCount(100);
56         }
57         
58         FileInputStream JavaDoc in = new FileInputStream JavaDoc( getCounterFile() );
59         try
60         {
61             fieldCustomerIdCounter.load( in );
62         }
63         finally
64         {
65             in.close();
66         }
67         
68         String JavaDoc count = fieldCustomerIdCounter.getProperty( "currentCount" );
69         if ( count == null )
70         {
71             throw new IllegalStateException JavaDoc( "Could not find valid ID counter " + getCounterFile() );
72         }
73     
74         int i = Integer.parseInt( count );
75         return i;
76     }
77
78     public File JavaDoc getCounterFile()
79     {
80         return fieldCounterFile;
81     }
82
83     public void setCounterFile(File JavaDoc inCounterFile)
84     {
85         fieldCounterFile = inCounterFile;
86     }
87
88     
89     
90 }
91
Popular Tags