-
Notifications
You must be signed in to change notification settings - Fork 9
/
PojoWriter.java
405 lines (339 loc) · 13.2 KB
/
PojoWriter.java
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
* Copyright (c) 2017 Vijay Vijayaram
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.kumarvv.table2pojo.core;
import com.kumarvv.table2pojo.model.DbColumn;
import com.kumarvv.table2pojo.model.UserPrefs;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.WordUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.sql.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import static com.kumarvv.table2pojo.model.UserPrefs.DONE;
public class PojoWriter extends Thread {
private static final String SQL_ALL = "select * from %s where 1>2";
private static final Map<Integer, String> MAP_TYPES = new HashMap<>();
static {
MAP_TYPES.put(Types.CHAR, "String");
MAP_TYPES.put(Types.VARCHAR, "String");
MAP_TYPES.put(Types.LONGVARCHAR, "String");
MAP_TYPES.put(Types.NUMERIC, "BigDecimal");
MAP_TYPES.put(Types.DECIMAL, "BigDecimal");
MAP_TYPES.put(Types.BIT, "Boolean");
MAP_TYPES.put(Types.TINYINT, "Integer");
MAP_TYPES.put(Types.SMALLINT, "Integer");
MAP_TYPES.put(Types.INTEGER, "Integer");
MAP_TYPES.put(Types.BIGINT, "Long");
MAP_TYPES.put(Types.REAL, "Float");
MAP_TYPES.put(Types.FLOAT, "Double");
MAP_TYPES.put(Types.DOUBLE, "Double");
MAP_TYPES.put(Types.BINARY, "byte[]");
MAP_TYPES.put(Types.VARBINARY, "byte[]");
MAP_TYPES.put(Types.LONGVARBINARY, "byte[]");
MAP_TYPES.put(Types.DATE, "Date");
MAP_TYPES.put(Types.TIME, "Time");
MAP_TYPES.put(Types.TIMESTAMP, "Timestamp");
MAP_TYPES.put(Types.CLOB, "Clob");
MAP_TYPES.put(Types.BLOB, "Blob");
MAP_TYPES.put(Types.ARRAY, "Array");
MAP_TYPES.put(Types.STRUCT, "Struct");
MAP_TYPES.put(Types.REF, "Ref");
MAP_TYPES.put(Types.JAVA_OBJECT, "Object");
}
private static final Map<String, String> MAP_IMPORTS = new HashMap<>();
static {
MAP_IMPORTS.put("BigDecimal", "java.math.BigDecimal");
MAP_IMPORTS.put("Date", "java.util.Date");
MAP_IMPORTS.put("Time", "java.sql.Time");
MAP_IMPORTS.put("Timestamp", "java.sql.Timestamp");
}
private static final String NEW_LINE = "\n";
private final UserPrefs prefs;
private final Connection conn;
private final BlockingQueue<String> queue;
/**
* requires connection and table
* @param prefs
* @param conn
*/
public PojoWriter(final UserPrefs prefs, final Connection conn, final BlockingQueue<String> queue, final int id) {
this.prefs = prefs;
this.conn = conn;
this.queue = queue;
this.setName("writer-" + id);
}
/**
* run the generator task
*/
@Override
public void run() {
if (prefs == null || conn == null || queue == null) {
throw new IllegalArgumentException("null values");
}
while (true) {
try {
String table = queue.take();
if (StringUtils.isBlank(table) || DONE.equalsIgnoreCase(table)) {
break;
}
processTable(conn, table);
} catch (InterruptedException ie) {
break;
} catch (Exception e) {
error(e.getMessage());
break;
}
}
info("DONE");
}
/**
* process
* @param conn
* @param tableName
*/
private void processTable(final Connection conn, final String tableName) {
if (conn == null || StringUtils.isEmpty(tableName)) {
return;
}
try (Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(String.format(SQL_ALL, tableName.toUpperCase()));) {
if (rs == null) {
throw new PojoWriterException("table not found");
}
final ResultSetMetaData meta = rs.getMetaData();
final List<DbColumn> columns = new ArrayList<>();
int count = meta.getColumnCount();
for (int i = 1; i <= meta.getColumnCount(); i++) {
DbColumn column = buildDbColumn(meta, i);
if (column != null) {
columns.add(column);
}
}
if (count == 0) {
throw new PojoWriterException("no columns found in table");
}
String pojoPath = generatePojo(tableName, columns);
info("[table=" + tableName + "] generated pojo file: " + pojoPath);
} catch (Exception e) {
error("[table=" + tableName + "] " + e.getMessage().trim());
}
}
/**
* build column using result meta
* @param meta
* @param columnId
* @return
*/
private DbColumn buildDbColumn(ResultSetMetaData meta, int columnId) throws PojoWriterException {
if (meta == null) {
return null;
}
try {
DbColumn column = new DbColumn();
column.setCatelogName(meta.getCatalogName(columnId));
column.setName(meta.getColumnName(columnId));
column.setLabel(meta.getColumnLabel(columnId));
column.setClassName(meta.getColumnClassName(columnId));
column.setType(meta.getColumnType(columnId));
column.setTableName(meta.getColumnTypeName(columnId));
column.setDisplaySize(meta.getColumnDisplaySize(columnId));
column.setPrecision(meta.getPrecision(columnId));
column.setScale(meta.getScale(columnId));
column.setSchemaName(meta.getSchemaName(columnId));
column.setTableName(meta.getTableName(columnId));
column.setJavaType(getJavaType(column));
column.setJavaProperty(toCamelCase(column.getName()));
return column;
} catch (SQLException sqle) {
throw new PojoWriterException(sqle.getMessage());
}
}
/**
* generate pojo
* @param tableName
* @param columns
*/
private String generatePojo(final String tableName, final List<DbColumn> columns) throws PojoWriterException {
if (tableName == null || CollectionUtils.isEmpty(columns)) {
throw new PojoWriterException("invalid table name");
}
final Set<String> imports = new HashSet<>();
final List<String> properties = new ArrayList<>();
final List<String> methods = new ArrayList<>();
columns.forEach(column -> {
generatePojoColumn(column, imports, properties, methods);
});
StringBuilder sb = new StringBuilder();
String pkg = prefs.getPkg();
if (StringUtils.isBlank(pkg)) {
pkg = "pojo";
}
sb.append("package ").append(pkg).append(";").append(NEW_LINE);
sb.append(NEW_LINE);
imports.forEach(s -> sb.append(s).append(NEW_LINE));
sb.append(NEW_LINE);
String pojoName = toMethodName(tableName);
sb.append("public class ").append(pojoName);
sb.append(" implements Serializable {").append(NEW_LINE);
properties.forEach(s -> sb.append(s).append(NEW_LINE));
sb.append(NEW_LINE);
methods.forEach(s -> sb.append(s).append(NEW_LINE));
sb.append("}");
return writePojo(pojoName, sb.toString());
}
/**
* generate pojo column details
* @param column
* @param imports
* @param properties
* @param methods
*/
private void generatePojoColumn(final DbColumn column, final Set<String> imports, final List<String> properties, final List<String> methods) {
if (column == null) {
return;
}
imports.add("import java.io.Serializable;");
if (MAP_IMPORTS.containsKey(column.getJavaType()) && imports != null) {
imports.add("import " + MAP_IMPORTS.get(column.getJavaType()) + ";");
}
properties.add(generatePropertyLine(column));
methods.add(generateGetterSetter(column));
}
/**
* generate propertiy line
* @param column
* @return
*/
protected String generatePropertyLine(final DbColumn column) {
if (column == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("\tprivate ").append(column.getJavaType()).append(" ").append(toCamelCase(column.getName())).append(";");
return sb.toString();
}
/**
* generate getter/setter for column
* @param column
* @return
*/
protected String generateGetterSetter(final DbColumn column) {
if (column == null) {
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("\tpublic ").append(column.getJavaType()).append(" get").append(toMethodName(column.getName())).append("() {\n");
sb.append("\t\treturn ").append(column.getJavaProperty()).append(";").append(NEW_LINE);
sb.append("\t}\n");
sb.append(NEW_LINE);
sb.append("\tpublic void ").append("set").append(toMethodName(column.getName())).append("(")
.append(column.getJavaType()).append(" ").append(column.getJavaProperty()).append(")").append(" {\n");
sb.append("\t\tthis.").append(column.getJavaProperty()).append(" = ").append(column.getJavaProperty()).append(";").append(NEW_LINE);
sb.append("\t}\n");
return sb.toString();
}
/**
* get java type
* @param column
* @return
*/
private String getJavaType(final DbColumn column) {
if (column == null) {
return null;
}
String javaType = MAP_TYPES.get(column.getType());
if (column.getType() == Types.NUMERIC && column.getPrecision() == 1 && column.getScale() == 0) {
return "Boolean";
}
if (column.getType() == Types.NUMERIC && column.getScale() == 0) {
return "Long";
}
return javaType;
}
/**
* db columnName to camelCaseName
* @param str
* @return
*/
private String toCamelCase(String str) {
return WordUtils.uncapitalize(WordUtils.capitalizeFully(str, '_').replaceAll("_", ""));
}
/**
* db columnName to camelCaseName
* @param str
* @return
*/
private String toMethodName(String str) {
return WordUtils.capitalizeFully(str, '_').replaceAll("_", "");
}
/**
* writes pojo into directory
* @param pojoStr
*/
private String writePojo(String pojoName, String pojoStr) throws PojoWriterException {
if (StringUtils.isBlank(pojoName) || StringUtils.isEmpty(pojoStr)) {
throw new PojoWriterException("no pojo content, skipping write");
}
String pkg = prefs.getPkg();
if (StringUtils.isBlank(pkg)) {
pkg = "pojo";
}
String dir = prefs.getDir();
if (StringUtils.isBlank(dir)) {
dir = "out";
}
Path curr = Paths.get(".");
Path out = Paths.get(dir, pkg.split("\\."));
Path targetDir = curr.resolve(out).normalize();
try {
Files.createDirectories(targetDir);
} catch (IOException e) {
throw new PojoWriterException("could not create targetDir: " + targetDir.toString() + ", error: " + e.getMessage());
}
if (!targetDir.toFile().exists() || !targetDir.toFile().isDirectory()) {
throw new PojoWriterException("pojo directory not exists: " + targetDir.toAbsolutePath());
}
Path targetFile = Paths.get(targetDir.toString(), pojoName + ".java");
try {
Files.write(targetFile, pojoStr.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
return targetFile.toString();
} catch (IOException e) {
throw new PojoWriterException("could not write pojo file: " + e.getMessage());
}
}
/**
* error print
* @param msg
*/
private void error(String msg) {
System.out.println("(" + getName() + ") ERROR: " + msg);
}
/**
* info print
* @param msg
*/
private void info(String msg) {
System.out.println("(" + getName() + ") INFO: " + msg);
}
}