forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbUtil.java
More file actions
executable file
·342 lines (282 loc) · 10.9 KB
/
Copy pathDbUtil.java
File metadata and controls
executable file
·342 lines (282 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.utils.db;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Id;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.PrimaryKeyJoinColumns;
import javax.persistence.SecondaryTable;
import javax.persistence.SecondaryTables;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
public class DbUtil {
protected final static Logger s_logger = Logger.getLogger(DbUtil.class);
private static Map<String, Connection> s_connectionForGlobalLocks = new HashMap<String, Connection>();
public static Connection getConnectionForGlobalLocks(String name, boolean forLock) {
synchronized(s_connectionForGlobalLocks) {
if(forLock) {
if(s_connectionForGlobalLocks.get(name) != null) {
s_logger.error("Sanity check failed, global lock name " + name + " is already in use");
assert(false);
}
Connection connection = Transaction.getStandaloneConnection();
if(connection != null) {
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
try {
connection.close();
} catch(SQLException sqlException) {
}
return null;
}
s_connectionForGlobalLocks.put(name, connection);
return connection;
}
return null;
} else {
Connection connection = s_connectionForGlobalLocks.get(name);
s_connectionForGlobalLocks.remove(name);
return connection;
}
}
}
public static void removeConnectionForGlobalLocks(String name) {
synchronized(s_connectionForGlobalLocks) {
s_connectionForGlobalLocks.remove(name);
}
}
public static String getColumnName(Field field, AttributeOverride[] overrides) {
if (overrides != null) {
for (AttributeOverride override : overrides) {
if (override.name().equals(field.getName())) {
return override.column().name();
}
}
}
assert(field.getAnnotation(Embedded.class) == null) : "Cannot get column name from embedded field: " + field.getName();
Column column = field.getAnnotation(Column.class);
return column != null ? column.name() : field.getName();
}
public static String getColumnName(Field field) {
return getColumnName(field, null);
}
public static String getReferenceColumn(PrimaryKeyJoinColumn pkjc) {
return pkjc.referencedColumnName().length() != 0
? pkjc.referencedColumnName()
: pkjc.name();
}
public static PrimaryKeyJoinColumn[] getPrimaryKeyJoinColumns(Class<?> clazz) {
PrimaryKeyJoinColumn pkjc = clazz.getAnnotation(PrimaryKeyJoinColumn.class);
if (pkjc != null) {
return new PrimaryKeyJoinColumn[] { pkjc };
}
PrimaryKeyJoinColumns pkjcs = clazz.getAnnotation(PrimaryKeyJoinColumns.class);
if (pkjcs != null) {
return pkjcs.value();
}
return null;
}
public static Field findField(Class<?> clazz, String columnName) {
for (Field field : clazz.getDeclaredFields()) {
if (field.getAnnotation(Embedded.class) != null || field.getAnnotation(EmbeddedId.class) != null) {
findField(field.getClass(), columnName);
} else {
if (columnName.equals(DbUtil.getColumnName(field))) {
return field;
}
}
}
return null;
}
public static final AttributeOverride[] getAttributeOverrides(AnnotatedElement ae) {
AttributeOverride[] overrides = null;
AttributeOverrides aos = ae.getAnnotation(AttributeOverrides.class);
if (aos != null) {
overrides = aos.value();
}
if (overrides == null || overrides.length == 0) {
AttributeOverride override = ae.getAnnotation(AttributeOverride.class);
if (override != null) {
overrides = new AttributeOverride[1];
overrides[0] = override;
} else {
overrides = new AttributeOverride[0];
}
}
return overrides;
}
public static final boolean isPersistable(Field field) {
if (field.getAnnotation(Transient.class) != null) {
return false;
}
int modifiers = field.getModifiers();
return !(Modifier.isFinal(modifiers) ||
Modifier.isStatic(modifiers) ||
Modifier.isTransient(modifiers));
}
public static final boolean isIdField(Field field) {
if (field.getAnnotation(Id.class) != null) {
return true;
}
if (field.getAnnotation(EmbeddedId.class) != null) {
assert (field.getClass().getAnnotation(Embeddable.class) != null) : "Class " + field.getClass().getName() + " must be Embeddable to be used as Embedded Id";
return true;
}
return false;
}
public static final SecondaryTable[] getSecondaryTables(AnnotatedElement clazz) {
SecondaryTable[] sts = null;
SecondaryTable stAnnotation = clazz.getAnnotation(SecondaryTable.class);
if (stAnnotation == null) {
SecondaryTables stsAnnotation = clazz.getAnnotation(SecondaryTables.class);
sts = stsAnnotation != null ? stsAnnotation.value() : new SecondaryTable[0];
} else {
sts = new SecondaryTable[] {stAnnotation};
}
return sts;
}
public static final String getTableName(Class<?> clazz) {
Table table = clazz.getAnnotation(Table.class);
return table != null ? table.name() : clazz.getSimpleName();
}
public static boolean getGlobalLock(String name, int timeoutSeconds) {
Connection conn = getConnectionForGlobalLocks(name, true);
if(conn == null) {
s_logger.error("Unable to acquire DB connection for global lock system");
return false;
}
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("SELECT COALESCE(GET_LOCK(?, ?),0)");
pstmt.setString(1, name);
pstmt.setInt(2, timeoutSeconds);
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.first()) {
if(rs.getInt(1) > 0) {
return true;
} else {
if(s_logger.isDebugEnabled())
s_logger.debug("GET_LOCK() timed out on lock : " + name);
}
}
} catch (SQLException e) {
s_logger.error("GET_LOCK() throws exception ", e);
} catch (Throwable e) {
s_logger.error("GET_LOCK() throws exception ", e);
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (Throwable e) {
s_logger.error("What the heck? ", e);
}
}
}
removeConnectionForGlobalLocks(name);
try {
conn.close();
} catch (SQLException e) {
}
return false;
}
public static Class<?> getEntityBeanType(GenericDao<?, Long> dao) {
return dao.getEntityBeanType();
}
public static boolean releaseGlobalLock(String name) {
Connection conn = getConnectionForGlobalLocks(name, false);
if(conn == null) {
s_logger.error("Unable to acquire DB connection for global lock system");
assert(false);
return false;
}
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement("SELECT COALESCE(RELEASE_LOCK(?), 0)");
pstmt.setString(1, name);
ResultSet rs = pstmt.executeQuery();
if(rs != null && rs.first())
return rs.getInt(1) > 0;
s_logger.error("RELEASE_LOCK() returns unexpected result : " + rs.getInt(1));
} catch (SQLException e) {
s_logger.error("RELEASE_LOCK() throws exception ", e);
} catch (Throwable e) {
s_logger.error("RELEASE_LOCK() throws exception ", e);
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
conn.close();
} catch(SQLException e) {
}
}
return false;
}
public static void closeResources(final Connection connection,
final Statement statement, final ResultSet resultSet) {
closeResultSet(resultSet);
closeStatement(statement);
closeConnection(connection);
}
public static void closeResources(final Statement statement, final ResultSet resultSet) {
closeResources(null, statement, resultSet);
}
public static void closeResultSet(final ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (Exception e) {
s_logger.warn("Ignored exception while closing result set.",e);
}
}
public static void closeStatement(final Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
s_logger.warn("Ignored exception while closing statement.",e);
}
}
public static void closeConnection(final Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
s_logger.warn("Ignored exception while close connection.",e);
}
}
}