Skip to content

Commit 40fc61b

Browse files
PinkieSwirlvelo
andauthored
Cleanup mainly for querydsl-sql-codegen (#788)
Co-authored-by: Marvin <[email protected]>
1 parent 428800d commit 40fc61b

File tree

7 files changed

+71
-89
lines changed

7 files changed

+71
-89
lines changed

querydsl-tooling/querydsl-codegen/src/main/java/com/querydsl/codegen/AbstractModule.java

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@
1818
import java.lang.annotation.Annotation;
1919
import java.lang.reflect.Constructor;
2020
import java.lang.reflect.InvocationTargetException;
21+
import java.util.Arrays;
2122
import java.util.HashMap;
2223
import java.util.Map;
2324
import java.util.ServiceLoader;
25+
import org.jetbrains.annotations.NotNull;
2426

2527
/**
2628
* {@code AbstractModule} provides a base class for annotation based dependency injection
@@ -117,45 +119,44 @@ public final <T> T get(Class<T> iface, String name) {
117119
}
118120
}
119121

120-
@SuppressWarnings("unchecked")
121122
private <T> T createInstance(Class<? extends T> implementation) {
122-
Constructor<?> constructor = null;
123-
for (Constructor<?> c : implementation.getConstructors()) {
124-
if (c.isAnnotationPresent(Inject.class)) {
125-
constructor = c;
126-
break;
127-
}
123+
var constructor =
124+
Arrays.stream(implementation.getConstructors())
125+
.filter(c -> c.isAnnotationPresent(Inject.class))
126+
.findFirst()
127+
.orElseGet(() -> fallbackToDefaultConstructor(implementation));
128+
129+
var args = getConstructorParameters(constructor);
130+
try {
131+
//noinspection unchecked
132+
return (T) constructor.newInstance(args);
133+
// TODO : populate fields as well?!?
134+
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
135+
throw new RuntimeException(e);
128136
}
137+
}
129138

130-
// fallback to default constructor
131-
if (constructor == null) {
132-
try {
133-
constructor = implementation.getConstructor();
134-
} catch (SecurityException | NoSuchMethodException e) {
135-
throw new RuntimeException(e);
139+
private Object @NotNull [] getConstructorParameters(Constructor<?> constructor) {
140+
Class<?>[] parameterTypes = constructor.getParameterTypes();
141+
Annotation[][] parameterAnnotations = constructor.getParameterAnnotations();
142+
var args = new Object[parameterTypes.length];
143+
for (var i = 0; i < parameterTypes.length; i++) {
144+
var named = getNamedAnnotation(parameterAnnotations[i]);
145+
if (named != null) {
146+
args[i] = get(parameterTypes[i], named.value());
147+
} else {
148+
args[i] = get(parameterTypes[i]);
136149
}
137150
}
151+
return args;
152+
}
138153

139-
if (constructor != null) {
140-
var args = new Object[constructor.getParameterTypes().length];
141-
for (var i = 0; i < constructor.getParameterTypes().length; i++) {
142-
var named = getNamedAnnotation(constructor.getParameterAnnotations()[i]);
143-
if (named != null) {
144-
args[i] = get(constructor.getParameterTypes()[i], named.value());
145-
} else {
146-
args[i] = get(constructor.getParameterTypes()[i]);
147-
}
148-
}
149-
try {
150-
return (T) constructor.newInstance(args);
151-
// TODO : populate fields as well?!?
152-
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
153-
throw new RuntimeException(e);
154-
}
155-
156-
} else {
157-
throw new IllegalArgumentException(
158-
"Got no annotated constructor for " + implementation.getName());
154+
private static <T> @NotNull Constructor<? extends T> fallbackToDefaultConstructor(
155+
Class<? extends T> implementation) {
156+
try {
157+
return implementation.getConstructor();
158+
} catch (SecurityException | NoSuchMethodException e) {
159+
throw new RuntimeException(e);
159160
}
160161
}
161162

querydsl-tooling/querydsl-codegen/src/main/java/com/querydsl/codegen/AnnotationHelper.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
import java.lang.annotation.Annotation;
1818

1919
/**
20-
* {@code AnnotationHelper} defines a interface to provide custom annotation processing for {@link
20+
* {@code AnnotationHelper} defines an interface to provide custom annotation processing for {@link
2121
* TypeFactory}.
2222
*
2323
* @author dyorgio
@@ -36,7 +36,7 @@ public interface AnnotationHelper {
3636
* Get specific object that will be used as part of type cache key.
3737
*
3838
* @param annotation Annotation instance.
39-
* @return Any object, normally a annotation param. Can be {@code null}.
39+
* @return Any object, normally an annotation param. Can be {@code null}.
4040
*/
4141
Object getCustomKey(Annotation annotation);
4242

querydsl-tooling/querydsl-codegen/src/main/java/com/querydsl/codegen/BeanSerializer.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,7 @@ public class BeanSerializer implements Serializer {
4848
public static final boolean DEFAULT_PROPERTY_ANNOTATIONS = true;
4949

5050
private static final Function<Property, Parameter> propertyToParameter =
51-
new Function<>() {
52-
@Override
53-
public Parameter apply(Property input) {
54-
return new Parameter(input.getName(), input.getType());
55-
}
56-
};
51+
input -> new Parameter(input.getName(), input.getType());
5752
private final Class<? extends Annotation> generatedAnnotationClass;
5853

5954
private final boolean propertyAnnotations;
@@ -242,7 +237,7 @@ protected void addFullConstructor(EntityType model, CodeWriter writer) throws IO
242237
writer.end();
243238

244239
// full constructor
245-
writer.beginConstructor(model.getProperties(), propertyToParameter::apply);
240+
writer.beginConstructor(model.getProperties(), propertyToParameter);
246241
for (Property property : model.getProperties()) {
247242
writer.line("this.", property.getEscapedName(), " = ", property.getEscapedName(), ";");
248243
}

querydsl-tooling/querydsl-sql-codegen/src/main/java/com/querydsl/sql/codegen/MetaDataExporter.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@
5353
import java.util.Arrays;
5454
import java.util.Collection;
5555
import java.util.Collections;
56-
import java.util.Comparator;
5756
import java.util.HashMap;
5857
import java.util.HashSet;
5958
import java.util.LinkedHashSet;
@@ -169,7 +168,7 @@ private String normalizePackage(String packageName, SchemaAndTable schemaAndTabl
169168
protected Property createProperty(
170169
EntityType classModel, String normalizedColumnName, String propertyName, Type typeModel) {
171170
return new Property(
172-
classModel, propertyName, propertyName, typeModel, Collections.<String>emptyList(), false);
171+
classModel, propertyName, propertyName, typeModel, Collections.emptyList(), false);
173172
}
174173

175174
/**
@@ -184,8 +183,8 @@ public void export(DatabaseMetaData md) throws SQLException {
184183

185184
if (config.getNamingStrategyClass() != null) {
186185
try {
187-
namingStrategy = config.getNamingStrategyClass().newInstance();
188-
} catch (InstantiationException | IllegalAccessException e) {
186+
namingStrategy = config.getNamingStrategyClass().getDeclaredConstructor().newInstance();
187+
} catch (ReflectiveOperationException e) {
189188
throw new RuntimeException(e);
190189
}
191190
} else {
@@ -308,8 +307,8 @@ private void configureModule() {
308307
serializer = new BeanSerializer();
309308
} else {
310309
try {
311-
serializer = config.getBeanSerializerClass().newInstance();
312-
} catch (InstantiationException | IllegalAccessException e) {
310+
serializer = config.getBeanSerializerClass().getDeclaredConstructor().newInstance();
311+
} catch (ReflectiveOperationException e) {
313312
throw new RuntimeException(e);
314313
}
315314
}
@@ -338,8 +337,11 @@ private void configureModule() {
338337
for (CustomType cl : config.getCustomTypes()) {
339338
try {
340339
configuration.register(
341-
(com.querydsl.sql.types.Type) Class.forName(cl.getClassName()).newInstance());
342-
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
340+
Class.forName(cl.getClassName())
341+
.asSubclass(com.querydsl.sql.types.Type.class)
342+
.getDeclaredConstructor()
343+
.newInstance());
344+
} catch (ReflectiveOperationException e) {
343345
throw new RuntimeException(e);
344346
}
345347
}
@@ -361,9 +363,7 @@ private void configureModule() {
361363
}
362364

363365
if (config.getColumnComparatorClass() != null) {
364-
module.bind(
365-
SQLCodegenModule.COLUMN_COMPARATOR,
366-
config.getColumnComparatorClass().asSubclass(Comparator.class));
366+
module.bind(SQLCodegenModule.COLUMN_COMPARATOR, config.getColumnComparatorClass());
367367
}
368368

369369
if (config.getSerializerClass() != null) {
@@ -596,7 +596,7 @@ private void write(Serializer serializer, File targetFile, EntityType type) thro
596596
var generate = true;
597597
var bytes = w.toString().getBytes(config.getSourceEncoding());
598598
if (targetFile.exists() && targetFile.length() == bytes.length) {
599-
var str = new String(Files.readAllBytes(targetFile.toPath()), config.getSourceEncoding());
599+
var str = Files.readString(targetFile.toPath(), config.getSourceEncoding());
600600
if (str.equals(w.toString())) {
601601
generate = false;
602602
}

querydsl-tooling/querydsl-sql-codegen/src/main/java/com/querydsl/sql/codegen/OrdinalPositionComparator.java

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515

1616
import com.querydsl.codegen.Property;
1717
import com.querydsl.sql.ColumnMetadata;
18-
import java.util.Arrays;
1918
import java.util.Comparator;
2019

2120
/** Compares {@link Property} instances based on their ordinal position in the table */
@@ -27,13 +26,12 @@ public OrdinalPositionComparator() {
2726

2827
@Override
2928
public int compare(Property property1, Property property2) {
30-
Integer comparison = null;
31-
for (Property property : Arrays.asList(property1, property2)) {
32-
var data = property.getData();
33-
var columnMetadata = (ColumnMetadata) data.get("COLUMN");
34-
var index = columnMetadata.getIndex();
35-
comparison = comparison == null ? index : comparison - index;
36-
}
37-
return comparison;
29+
return getOrdinalPosition(property1) - getOrdinalPosition(property2);
30+
}
31+
32+
private static int getOrdinalPosition(Property property) {
33+
var data = property.getData();
34+
var columnMetadata = (ColumnMetadata) data.get("COLUMN");
35+
return columnMetadata.getIndex();
3836
}
3937
}

querydsl-tooling/querydsl-sql-codegen/src/main/java/com/querydsl/sql/codegen/ant/AntMetaDataExporter.java

Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -191,36 +191,22 @@ public class AntMetaDataExporter extends Task implements MetadataExporterConfig
191191
private List<RenameMapping> renameMappings = new ArrayList<>();
192192

193193
@Override
194-
@SuppressWarnings({"unchecked", "rawtypes"})
195194
public void execute() {
196195
if (targetFolder == null) {
197196
throw new BuildException("targetFolder is a mandatory property");
198197
}
199198

200-
Connection dbConn = null;
201199
try {
202-
Class.forName(jdbcDriver).newInstance();
203-
204-
dbConn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
200+
Class.forName(jdbcDriver).getDeclaredConstructor().newInstance();
201+
} catch (RuntimeException | ReflectiveOperationException e) {
202+
throw new BuildException(e);
203+
}
205204

205+
try (Connection dbConn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword)) {
206206
var exporter = new MetaDataExporter(this);
207-
208207
exporter.export(dbConn.getMetaData());
209-
210-
} catch (RuntimeException
211-
| SQLException
212-
| ClassNotFoundException
213-
| IllegalAccessException
214-
| InstantiationException e) {
208+
} catch (RuntimeException | SQLException e) {
215209
throw new BuildException(e);
216-
} finally {
217-
if (dbConn != null) {
218-
try {
219-
dbConn.close();
220-
} catch (SQLException e2) {
221-
throw new BuildException(e2);
222-
}
223-
}
224210
}
225211
}
226212

@@ -343,7 +329,7 @@ public Class<? extends NamingStrategy> getNamingStrategyClass() {
343329
return null;
344330
}
345331
try {
346-
return (Class<? extends NamingStrategy>) Class.forName(namingStrategyClass);
332+
return Class.forName(namingStrategyClass).asSubclass(NamingStrategy.class);
347333
} catch (ClassNotFoundException e) {
348334
throw new RuntimeException(e);
349335
}
@@ -357,7 +343,7 @@ public void setNamingStrategyClass(String namingStrategyClass) {
357343
public Class<? extends BeanSerializer> getBeanSerializerClass() {
358344
if (exportBeans && beanSerializerClass != null) {
359345
try {
360-
return (Class<? extends BeanSerializer>) Class.forName(beanSerializerClass);
346+
return Class.forName(beanSerializerClass).asSubclass(BeanSerializer.class);
361347
} catch (ClassNotFoundException e) {
362348
throw new RuntimeException(e);
363349
}
@@ -375,7 +361,7 @@ public Class<? extends Serializer> getSerializerClass() {
375361
return null;
376362
}
377363
try {
378-
return (Class<? extends Serializer>) Class.forName(serializerClass);
364+
return Class.forName(serializerClass).asSubclass(Serializer.class);
379365
} catch (ClassNotFoundException e) {
380366
throw new RuntimeException(e);
381367
}
@@ -581,7 +567,8 @@ public Class<? extends Comparator<Property>> getColumnComparatorClass() {
581567
return null;
582568
}
583569
try {
584-
return (Class<? extends Comparator<Property>>) Class.forName(columnComparatorClass);
570+
return (Class<? extends Comparator<Property>>)
571+
Class.forName(columnComparatorClass).asSubclass(Comparator.class);
585572
} catch (ClassNotFoundException e) {
586573
throw new RuntimeException(e);
587574
}

querydsl-tooling/querydsl-sql-codegen/src/main/java/com/querydsl/sql/codegen/support/TypeMapping.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,14 @@ public void apply(Configuration configuration) {
4141
try {
4242
Class<?> typeClass = Class.forName(type);
4343
if (Type.class.isAssignableFrom(typeClass)) {
44-
configuration.register(table, column, (Type<?>) typeClass.newInstance());
44+
configuration.register(
45+
table, column, (Type<?>) typeClass.getDeclaredConstructor().newInstance());
4546
} else {
4647
configuration.register(table, column, typeClass);
4748
}
4849
} catch (ClassNotFoundException e) {
4950
configuration.register(table, column, new com.querydsl.sql.types.SimpleType(type));
50-
} catch (IllegalAccessException | InstantiationException e) {
51+
} catch (ReflectiveOperationException e) {
5152
throw new RuntimeException(e);
5253
}
5354
}

0 commit comments

Comments
 (0)