1
22
23 package com.liferay.util.dao;
24
25 import com.liferay.portal.kernel.util.StringMaker;
26
27 import java.sql.Connection;
28 import java.sql.PreparedStatement;
29 import java.sql.ResultSet;
30
31
37 public class CounterDAO {
38
39 public static String COUNTER_TABLE = "Counter";
40
41 public synchronized static long increment(String location, String rowName)
42 throws DataAccessException {
43
44 return increment(location, COUNTER_TABLE, rowName);
45 }
46
47 public synchronized static long increment(
48 String location, String tableName, String rowName)
49 throws DataAccessException {
50
51 long currentId = 0;
52
53 Connection con = null;
54 PreparedStatement ps = null;
55 ResultSet rs = null;
56
57 try {
58 con = DataAccess.getConnection(location);
59
60 StringMaker query = new StringMaker();
61
62 query.append(
63 "SELECT currentId FROM " + tableName + " WHERE name = ?");
64
65 ps = con.prepareStatement(query.toString());
66
67 ps.setString(1, rowName);
68
69 rs = ps.executeQuery();
70
71 while (rs.next()) {
72 currentId = rs.getInt(1);
73 }
74
75 if (currentId == 0) {
76 ps = con.prepareStatement(
77 "INSERT INTO " + tableName +
78 " (name, currentId) VALUES (?, ?)");
79
80 ps.setString(1, rowName);
81 ps.setLong(2, ++currentId);
82
83 ps.executeUpdate();
84 }
85 else {
86 ps = con.prepareStatement(
87 "UPDATE " + tableName +
88 " SET currentId = ? WHERE name = ?");
89
90 ps.setLong(1, ++currentId);
91 ps.setString(2, rowName);
92
93 ps.executeUpdate();
94 }
95 }
96 catch (Exception e) {
97 throw new DataAccessException(e);
98 }
99 finally {
100 DataAccess.cleanUp(con, ps, rs);
101 }
102
103 return currentId;
104 }
105
106 public synchronized static void reset(String location, String rowName)
107 throws DataAccessException {
108
109 reset(location, COUNTER_TABLE, rowName);
110 }
111
112 public synchronized static void reset(
113 String location, String tableName, String rowName)
114 throws DataAccessException {
115
116 Connection con = null;
117 PreparedStatement ps = null;
118 ResultSet rs = null;
119
120 try {
121 con = DataAccess.getConnection(location);
122
123 StringMaker update = new StringMaker();
124
125 update.append("DELETE FROM " + tableName + " WHERE name = ?");
126
127 ps = con.prepareStatement(update.toString());
128
129 ps.setString(1, rowName);
130
131 ps.executeUpdate();
132 }
133 catch (Exception e) {
134 throw new DataAccessException(e);
135 }
136 finally {
137 DataAccess.cleanUp(con, ps, rs);
138 }
139 }
140
141 }